Computer Programming II Lecture 1

advertisement
Computer Programming II
Lecture 1
Array
An array is a series of elements of the same type placed
in contiguous memory locations that can be
individually referenced by adding an index to a unique
identifier.
Array
Index number:
-Values that indicate specific locations within arrays.
-The first element in every array is the zero element.
- The last element in every array is the n-1 element.
arr[0]
10
arr[1]
20
arr[2]
30
arr[3]
40
arr[4]
50
One dimensional array
Declaration :
Data_type array_name [ array_size ] ;
For example :
int number [ 5 ];
char name [ 7 ] ;
One dimensional array
Initializing arrays :
int arr[5] = { 16, 2, 77, 40, 12071 };
Or
int arr[ ] = { 16, 2, 77, 40, 12071 };
One dimensional array
Accessing the values of an array:
arr [1] = 2;
arr [2] = 77;
Write a program using one dimensional
array to read 4 numbers and print them.
# include <iostream.h>
int main ( )
{
int i, arr[4];
cout<<"Enter the numbers : " <<endl;
for (i=0;i<4;i++)
{
cin>>arr[i];
}
for (i=0;i<4;i++)
cout<<"arr["<<i<<"] :" << arr[i]<<"\t";
return 0;
}
Write a program using one dimensional array
to read 5 numbers and print the sum of them.
# include <iostream.h>
int main ( )
{
int i, arr[5], sum = 0;
cout<<"Enter the numbers : " <<endl;
for (i=0;i<5;i++)
{
cin>>arr[i];
sum = sum + arr [i] ;
}
cout<< " The sum = " << sum << endl ;
return 0;
}
Write a program using one dimensional array
to read 4 numbers and display their square.
Two dimensional array
Declaration :
Data_type array_name [ rows ] [columns];
For example :
int arr [2] [4];
Two dimensional array
Initializing array:
Two-dimensional arrays are initialized row-by-row:
int hours[3][2] = {{8, 5}, {7, 9}, {6, 3}};
In either case, the values are assigned to hours in the
following manner:
hours[0][0] is set to 8
8
5
hours[0][1] is set to 5
7
9
hours[1][0] is set to 7
6
3
hours[1][1] is set to 9
hours[2][0] is set to 6
hours[2][1] is set to 3
Two dimensional array
Accessing the values of an array:
arr [0][1] = 5;
arr [2] [1]= 3;
Example:
# include <iostream.h>
int main ( )
{
int i, j, arr[2][5];
cout<<"Enter the numbers : " <<endl;
for (i=0;i<2;i++)
{
for (j=0;j<5;j++)
{ cin>>arr[i][j]; }
}
for (i=0;i<2;i++)
{
for (j=0;j<5;j++)
{
cout<< arr[i][j]<<"\t";
}
cout<<endl;
}
return 0;
}
Constant Objects and constant Member

Constants: are expressions with a fixed value.
• Defining Constants:
There are two ways to define constant:
1.Using #define preprocessor.
2.Using const keyword.
Constant member
• Using #define preprocessor:
Constant member
• Ex:
Constant member
• Using const keyword :
Constant member
• Ex:
Constant Object
Const Account a1; // using default constructor
Const Account a2(2000); // using parameterized
constructor
Download