Introduction Arrays –Structures of related data items –Static entity - same size throughout program A few types –C-like, pointer-based arrays –C++, arrays as objects
2 int count Enough memory for 1 int float price Enough memory for 1 float char letter Enough memory for 1 char A
Array - Memory Layout The definition: int tests[5]; allocates the following memory: first element second element third element fourth element fifth element
Arrays c[6] Name of array (Note that all elements of this array have the same name, c) c[0] c[1] c[2] c[3] c[11] c[10] c[9] c[8] c[7] c[5] c[4] Position number of the element within array c
Declaring Arrays Declaring arrays - specify: –Name –Type of array –Number of elements –Examples int c[ 10 ]; float hi[ 3284 ]; Declaring multiple arrays of same type –Similar format as other variables –Example int b[ 100 ], x[ 27 ];
Examples Using Arrays Initializers int n[ 5 ] = { 1, 2, 3, 4, 5 }; –If not enough initializers, rightmost elements become 0 –If too many initializers, a syntax error is generated int n[ 5 ] = { 0 } –Sets all the elements to 0 If size omitted, the initializers determine it int n[] = { 1, 2, 3, 4, 5 }; –5 initializers, therefore n is a 5 element array
Accessing Array Elements Array elements can be used as regular variables: tests[0] = 79; cout << tests[0]; cin >> tests[1]; tests[4] = tests[0] + tests[1]; Arrays must be accessed via individual elements: cout << tests; // not legal
Partial Array Initialization If array is initialized at definition with fewer initial values than the size declarator of the array, the remaining elements will be set to 0 or NULL: int tests[5] = {79, 82}; Initial values used in order; cannot skip over elements to initialize noncontiguous range
Implicit Array Sizing Can determine array size by the size of the initialization list: short quizzes[]={12,17,15,11}; Must use either array size declarator or initialization list at array definition
#include using namespace std; int main( ) { const int arraysize =12; int a[arraysize] = {1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45}; int total = 0; for (int i= 0; i<arraysize ; i++) total += a[i]; cout <<" total of array element values is "<< total << endl; return 0; }
#include // using cin for data #include // for set wedith using namespace std; int main() { int i,first_arry[6]; for (i=0;i<6;i++) cin>> first_arry[i] ; cout<<"the Content of array is.\n"; for (i=0;i<6;i++) cout<< first_arry[i]<<"\t"; return 0; }
#include #include // for set wedith using namespace std; int main( ) { int n[10]; for (int i=0; i<10;i++) // initialize array n[i] = 0; cout << "“Element”" << setw(13) << " value" << endl; for (int i=0; i<10;i++) // print array cout << setw(7) <<i<<setw(13) <<n[i]<<endl; return 0; }
#include // adding element in array #include // for set wedith using namespace std; main() { int i,array1[5],sum=0; for (i=0;i<5;i++) cin>> array1[i] ; for (i=0;i<5;i++) sum=sum+array1[i]; cout<< "sum of array item="<<sum; return 0; }
Find max number #include using namespace std; int main() { int i,array1[7],max; for (i=0;i<7;i++) cin>> array1[i] ; max=array1[0]; for (i=0;i<7;i++) if (array1[i] > max ) max=array1[i]; cout<< "max number in array1 is="<<max;}
Adding +5 or multiply array1[i]=2* array1[i]; //Multiply by *2 array1[i]= array1[i] /4; //divided by 4 #include using namespace std; main() { int i,array1[5]={10,15,30,32,21}; for (i=0;i<5;i++) { array1[i]= array1[i]+5; // *3 cout<< array1[i]<<"\t";} }
8.5 Processing Array Contents Array elements can be treated as ordinary variables of the same type as the array When using ++, -- operators, don’t confuse the element with the subscript: tests[i]++; // add 1 to tests[i] tests[i++]; // increment i, no // effect on tests
Strings Can be processed using array name (entire string at once) or using subscripts(element at a time): string city; cout << "Enter city name: "; cin >> city; 'S''a''l''e''m' city[0]city[1]city[2]city[3]city[4]
18 4.6Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort some data Massive amounts must be sorted Bubble sort (sinking sort) –Several passes through the array –Successive pairs of elements are compared If increasing order (or identical), no change If decreasing order, elements exchanged –Repeat these steps for every element
8.9 Two-Dimensional Arrays Can define one array for multiple sets of data Like a table in a spreadsheet Use two size declarators in definition: int exams[4][3]; First declarator is number of rows; second is number of columns
A dynamic 2D array is basically an array of pointers to arrays. You should initialize it using a loop: int** ary = new int*[sizeY]; for(int i = 0; i < sizeY; ++i) ary[i] = new int[sizeX]; The above, for sizeX = 5 and sizeY = 4, would produce the following:Two- dimensional Arrays 20
Two-Dimensional Array Representation int exams[4][3]; Use two subscripts to access element: exams[2][2] = 86; exams[0][0]exams[0][1]exams[0][2] exams[1][0]exams[1][1]exams[1][2] exams[2][0]exams[2][1]exams[2][2] exams[3][0]exams[3][1]exams[3][2] columns rowsrows
Initialization at Definition Two-dimensional arrays are initialized row-by-row: int exams[2][2] = { {84, 78}, {92, 97} }; Can omit inner { }, some initial values in row – array elements without initial values will be set to 0 or NULL
Multi-Dimensional Arrays Can define arrays with any number of dimensions: short rectSolid(2,3,5); float timeGrid(3,4,3,4); When used as parameter, specify all but 1 st dimension: void getRectSolid(short [][3][5]);
Chapter 8 slide 24 Arrays of Structures Use array subscript to access a specific structure in the array Then, use dot operator to access members of structure: cin >> class[25].studentID; cout << class[i].name << "has GPA " << class[i].gpa << endl;
#include using namespace std; int main( ) { int myArray[4][4], index1, index2; for (index1 = 0; index1 < 4; index1++) for (index2 = 0; index2 < 4; index2++) myArray[index1][index2] = index2; for (index1 = 0; index1 < 4; index1++) { for (index2 = 0; index2 < 4; index2++) cout << myArray[index1][index2] << " "; cout << endl;} } 25
26 Two-Dimensional Arrays Two-dimensional array (table): consists of both rows and columns of elements Example: two-dimensional array of integers Array declaration: names the array val and reserves storage for it int val[3][4];
A First Book of C++: From Here To There, Third Edition 27 Locating array elements (Figure 8.9) –val[1][3] uniquely identifies element in row 1, column 3 Examples using elements of val array: price = val[2][3]; val[0][0] = 62; newnum = 4 * (val[1][0] - 5); sumRow = val[0][0] + val[0][1] + val[0][2] + val[0][3]; –The last statement adds the elements in row 0 and sum is stored in sumRow
28 Two-Dimensional Arrays (continued)
29 Two-Dimensional Arrays (continued) Initialization: can be done within declaration statements (as with single- dimension arrays) Example: int val[3][4] = { {8,16,9,52}, {3,15,27,6}, {14,25,2,10} }; –First set of internal braces contains values for row 0, second set for row 1, and third set for row 2 –Commas in initialization braces are required; inner braces can be omitted
A First Book of C++: From Here To There, Third Edition 30 Two-Dimensional Arrays (continued)
#include using namespace std; int main(){ int a[3][3],b[3][3],c[3][3],i,j; cout "; for(i=0;i<3;i++) for(j=0;j<3;j++) cin>>a[i][j]; cout "; for(i=0;i<3;i++) for(j=0;j<3;j++) scanf("%d",&b[i][j]); cout<<"\nThe First matrix is\n"; for(i=0;i<3;i++){ cout<<"\n"; for(j=0;j<3;j++) cout<<"\t"<< a[i][j]; } cout<<"\nThe Second matrix is\n"; for(i=0;i<3;i++){ printf("\n"); for(j=0;j<3;j++) cout<<"\t"<<b[i][j]; } for(i=0;i<3;i++) for(j=0;j<3;j++) c[i][j]=a[i][j]+b[i][j]; cout<<"\nThe Addition of two matrix is\n"; for(i=0;i<3;i++){ cout<<"\n"; for(j=0;j<3;j++) cout<<"\t"<<c[i][j]; } return 0; }
#include int main( ) { int myArray[4][4], index1, index2; for (index1 = 0; index1 < 4; index1++) for (index2 = 0; index2 < 4; index2++) myArray[index1][index2] = index2; for (index1 = 0; index1 < 4; index1++) { for (index2 = 0; index2 < 4; index2++) cout << myArray[index1][index2] << " "; cout << endl;} system("pause"); } 33
#include // matrix multiplication using namespace std; int main() { int m, n, c, d, MatA[100][100], MatB[100][100], Result[100][100]; cout<<"Enter the number of rows and columns of matrices \n"; cin>>m>>n; cout<<"Enter the elements of Matrix A\n"; for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) { cin>>MatA[c][d]; } } cout<<"Enter the elements of Matrix B\n"; for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) { cin>>MatB[c][d]; } } for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) { Result[c][d] = MatA[c][d] + MatB[c][d]; } } cout<<"Resultant Matrix after Addition- \n"; for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < n ; d++ ) cout<<" "<<Result[c][d]; cout<<"\n"; } cin>>c; system("pause"); return 0; } 34
#include using namespace std; int main() { int m, n, p, q, c, d, k, sum = 0; int first[10][10], second[10][10], multiply[10][10]; cout<<"Enter the number of rows and columns of first matrix\n"; cin>>m>>n; cout<<"Enter the elements of first matrix\n"; for ( c = 0 ; c < m ; c++ ) for ( d = 0 ; d < n ; d++ ) cin>>first[c][d]; cout<<"Enter the number of rows and columns of second matrix\n"; cin>>p>>q; if ( n != p ) cout<<"Invalid Matrix Columns or Rows.\n"; else { cout<<"Enter the elements of second matrix\n"; for ( c = 0 ; c < p ; c++ ) for ( d = 0 ; d < q ; d++ ) cin>>second[c][d]; for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < q ; d++ ) { for ( k = 0 ; k < p ; k++ ) { sum = sum + first[c][k]*second[k][d]; } multiply[c][d] = sum; sum = 0; } cout<<"Resultant Matrix is: \n"; for ( c = 0 ; c < m ; c++ ) { for ( d = 0 ; d < q ; d++ ) cout<<"\t"<<multiply[c][d]; cout<<"\n"; } cout<<"Press any key to continue..."; cin>>c; return 0; } 35
#include // matrix multiplication #include main() { //declare variable type int int a[2][2],b[2][2],i,j,k,s; //Input the numbers of first matix cout<<"First Matrix"<<endl; for(i=0;i<2;i++) { for(j=0;j<2;j++) { cout<<"Enter number :"; cin>>a[i][j]; } } //Input the numbers of second matix cout<<"Second Matrix"<<endl; for(i=0;i<2;i++) { for(j=0;j<2;j++) { cout<<"Enter number :"; cin>>b[i][j]; } //display the multipication of matrices cout<<"Multiplication is"<<endl; for(i=0;i<2;i++) { for(j=0;j<2;j++) { for(k=0;k<2;k++) s=s+a[i][k]*b[k][j]; cout<<s<<"\t"; s=0; } cout<<endl; } getch(); } 36
#include using namespace std; int main( ) { const int arraysize =12; int a[arraysize] = {1, 3, 5, 4, 7, 2, 99, 16, 45, 67, 89, 45}; int total = 0; for (int i= 0; i<arraysize ; i++) total += a[i]; cout <<" total of array element values is "<< total << endl; return 0; } Chapter 8 slide 37
Multi dimensional array Chapter 8 slide 38
Printing matrix Chapter 8 slide 39
Adding two matrix Chapter 8 slide 40
Chapter 8 slide 41
Array problem solving in C++ Dr Ahmed Telba
Two-dimensional Arrays A two-dimensional array is like several identical arrays put together. It is useful for storing multiple sets of data.
Multidimensional Array Initialisation You can initialise a multidimensional array in more than one way. Consider this examples to initialise two dimensional array. int test[2][3] = {2, 4, -5, 9, 0, 9}; Better way to initialise this array with same array elements as above. int test[2][3] = { {2, 4, 5}, {9, 0 0}}; 44
Initialization of three dimensional array int test[2][3][4] = {3, 4, 2, 3, 0, -3, 9, 11, 23, 12, 23, 2, 13, 4, 56, 3, 5, 9, 3, 5, 5, 1, 4, 9}; Better way to initialize this array with same elements as above. int test[2][3][4] = { { {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} }, { {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} } }; 45
Better way to initialize this array with same elements as above. int test[2][3][4] = { { {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} }, { {13, 4, 56, 3}, {5, 9, 3, 5}, {3, 1, 4, 9} } }; 46
Example #include using namespace std; int main() { int test[3][2] = { {2, -5}, {4, 0}, {9, 1} }; for(int i = 0; i < 3; ++i) { for(int j = 0; j < 2; ++j) { cout<< "test["<< i << "][" << j << "] = " << test[i][j]<<endl; } return 0; } 47
#include // three dimension array using namespace std; int main() { int test[2][3][2]; // this array can store 12 elements cout<<"Enter 12 values: \n"; for(int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { for(int k = 0; k < 2; ++k ) { cin>>test[i][j][k]; } cout<<"\nDisplaying Value stored:"<<endl; /* Displaying the values with proper index. */ for(int i = 0; i < 2; ++i) { for (int j = 0; j < 3; ++j) { for(int k = 0; k < 2; ++k ) { cout<< "test["<<i<<"]["<<j<<"]["<<k<<"] = "<< test[i][j][k]<<endl; } return 0; } 48
C++ Program to Add Two Matrix Using Multi-dimensional Arrays #include using namespace std; int main(){ int r,c,a[100][100],b[100][100],sum[100][100],i,j; cout << "Enter number of rows (between 1 and 100): "; cin >> r; cout << "Enter number of columns (between 1 and 100): "; cin >> c; cout << endl << "Enter elements of 1st matrix: " << endl; /* Storing elements of first matrix entered by user. */ for(i=0;i<r;++i) for(j=0;j<c;++j) { cout << "Enter element a" << i+1 << j+1 << " : "; cin >> a[i][j]; } /* Storing elements of second matrix entered by user. */ cout << endl << "Enter elements of 2nd matrix: " << endl; for(i=0;i<r;++i) for(j=0;j<c;++j) { cout << "Enter element b" << i+1 << j+1 << " : "; cin >> b[i][j]; } /*Adding Two matrices */ for(i=0;i<r;++i) for(j=0;j<c;++j) sum[i][j]=a[i][j]+b[i][j]; /* Displaying the resultant sum matrix. */ cout << endl << "Sum of two matrix is: " << endl; for(i=0;i<r;++i) for(j=0;j<c;++j) { cout << sum[i][j] << " "; if(j==c-1) cout << endl; } return 0; } 49
//C++ Program to Find Largest Element of an Array #include using namespace std; int main(){ int i,n; float arr[100]; cout << "Enter total number of elements: "; cin >> n; cout << endl; while (n>100 || n<=0) { cout << "Error! number should in range of (1 to 100)." << endl; cout << "Enter the number again: "; cin >> n; } for(i=0;i<n;++i) /* Stores number entered by user. */ { cout << "Enter Number " << i+1 << " : "; cin >> arr[i]; } for(i=1;i<n;++i) /* Loop to store largest number to arr[0] */ { if(arr[0] if you want to find smallest element*/ arr[0]=arr[i]; } cout << "Largest element = " << arr[0]; return 0; } 50
#include //Source Code to Find Transpose of a Matrix Colom change to row and row change Colom using namespace std; int main() { int a[10][10], trans[10][10], r, c, i, j; cout << "Enter rows and columns of matrix: "; cin >> r >> c; /* Storing element of matrix entered by user in array a[][]. */ cout << endl << "Enter elements of matrix: " << endl; for(i=0; i<r; ++i) for(j=0; j<c; ++j) { cout << "Enter elements a" << i+1 << j+1 << ": "; cin >> a[i][j]; } /* Displaying the matrix a[][] */ cout << endl << "Entered Matrix: " << endl; for(i=0; i<r; ++i) for(j=0; j<c; ++j) { cout << " " << a[i][j]; if(j==c-1) cout << endl << endl; } /* Finding transpose of matrix a[][] and storing it in array trans[][]. */ for(i=0; i<r; ++i) for(j=0; j<c; ++j) { trans[j][i]=a[i][j]; } /* Displaying the transpose,i.e, Displaying array trans[][]. */ cout << endl << "Transpose of Matrix: " << endl; for(i=0; i<c; ++i) for(j=0; j<r; ++j) { cout << " " << trans[i][j]; if(j==r-1) cout << endl << endl; } return 0; } 51
#include // matrix addation using namespace std; int main() { int a[10][10]; int b[10][10]; int x,y,i,j; cout<<"\nEnter the number of rows and columns :::\n\n"; cin>>x>>y; cout<<"\n\nEnter elements for Matrix A :::\n\n"; for(i=0;i<x;i++) { for(j=0;j<y;j++) { cin>>a[i][j]; } cout<<"\n"; } cout<<"\n\nEnter elements for Matrix B :::\n\n"; for(i=0;i<x;i++) { for(j=0;j<y;j++) { cin>>b[i][j]; } cout<<"\n"; } cout<<"\n\nMatrix A :\n\n"; for(i=0;i<x;i++) { } 52
//Counted matrix add for(j=0;j<y;j++) { cout<<"\t"<<a[i][j]; } cout<<"\n\n"; } cout<<"\n\nMatrix B :\n\n"; for(i=0;i<x;i++) { for(j=0;j<y;j++) { cout<<"\t"<<b[i][j]; } cout<<"\n\n"; } cout<<"\n\nAddition of Matrix A and Matrix B :\n\n"; for(i=0;i<x;i++) { for(j=0;j<y;j++) { cout<<"\t"<<a[i][j]+b[i][j]; } cout<<"\n\n"; } 53
#include using namespace std; int main() { int i1=9,i2=10,i3=11,i4=12,i5=13; double ava=i1+i2+i3+i4+i5; ava=ava/5; cout << "avarage= "<< ava<<endl; return 0; }
#include // cin num& print it using namespace std; int main() { int a[10],i; for(i=0;i<=9;i++) cin>>a[i]; for(i=0;i<=9;i++) cout<<a[i]<<" "; }
#include // change firstA[0] to third{2] using namespace std; int main() { int A[4],M=0,i; for(i=0;i<=3;i++) cin>>A[i]; { M=A[0]; A[0]=A[2]; A[2]=M;} for(i=0;i<=3;i++) cout<<A[i]<<" ";}
#include // find minimum & maximum of array using namespace std; int main() { int a[10]; for(int i=0;i<=9;i++) cin>>a[i]; int max=a[0]; int min=a[0]; for(int i=0;i<=9;i++) { if(max<a[i]) max=a[i]; if(min>a[i]) min=a[i];} cout<<"Max="<<max<<"\n"; cout<<"Min="<<min<<"\n";}
#include // sum of array element & avarage #include using namespace std; int main() { int A[2][2]; int sum=0,i,j,ava; cout<<"Please enter the elements ofarray\n"; for(i=0;i<=1;i++) for(j=0;j<=1;j++) cin>>A[i][j]; for(i=0;i<=1;i++) for(j=0;j<=1;j++) sum+=A[i][j]; ava=sum/4; cout<< "avarage=\n"<<ava<< endl; cout<<"sum = "<<sum;}
#include // change Coolum by row using namespace std; int main() { int array[3][3],z,i,j; for(i=0;i<=2;i++) for(j=0;j<=2;j++) cin>>array[i][j]; for(i=0;i<=2;i++){ for(j=0;j<=2;j++) z=array[0][i]; array[0][i]=array[i][1]; array[i][1]=z;} cout<<" \n"; for(i=0;i<=2;i++){ for(j=0;j<=2;j++) cout<<array[i][j]<<" "; cout<<endl;}}
#include // matrix 3 by 3 change in row using namespace std; int main() { int p[3][3],m,i,j; for(i=0;i<=2;i++) for(j=0;j<=2;j++) cin>>p[i][j]; for(i=0;i<=2;i++){ for(j=0;j<=2;j++) m=p[i][0]; p[i][0]=p[i][1]; p[i][1]=m;} cout<<" \n"; for(i=0;i<=2;i++){ for(j=0;j<=2;j++) cout<<p[i][j]<<" "; cout<<endl;}}
#include // adding two array using namespace std; int main() { int a[4]={2,4,6,8},i,b[4]={1,3,5,6},c[4]; for(i=0;i<=3;i++) {c[i]=a[i]+b[i]; //cout<<a[i]<<"\t"; //cout<<b[i]<<" "; cout<<c[i]<<" "; }
#include // look for number in array and yes or NO using namespace std; int main() { int a[7]={1,3,5,4,6,7,8}; int i,m=0,n; cout<<"Enter the number :"; cin>>n; for(i=0;i<=6;i++) {if(n==a[i]) {m=1; break;} else m=0;} if(m==1) cout<< "The number is found. "; else cout<< "The number is not found. "; }
#include // enter array then sort from min to max using namespace std; int main() { int a[7],i,j,t; for(i=0;i<7;i++) {cout<<"Enter a["<<i<<"]= "; cin>>a[i];} for(i=0;i<7;i++) {for( j=0; j<7; j++) if(a[i]<a[j]) {t=a[i]; a[i]=a[j]; a[j]=t;}} for(i=0;i<7;i++) cout<<a[i]<<" "; }
#include // enter array then delete one number using namespace std; int main() { int a[6],x,i,j,d=5,k; for(i=0; i<=5;i++) {cout<<"enter a["<<i<<"]="; cin>>a[i]; } cout<<"enter number for delete it: "; cin>>x; k=0; for(i=0; i<=5;i++) if(x==a[i]) {k=k+1; for(j=i; j<=5;j++) a[j]=a[j+1]; d=d-1;} if(k==0) cout<<"not found"<<endl; for(i=0;i<=d;i++) cout<<a[i]<<" "; }
#include //Reverse the array element using namespace std; int main() { int a[10],i; for(i=0;i<=9;i++) cin>>a[i]; for(i=9;i>=0;i--) cout<<a[i]<<" "; }
66
#include // sort odd & even in array using namespace std; int main() { int a[10],i,j,z; for(i=1; i<=10;i++) {cout<<"Enter a["<<i<<"]="; cin>>a[i]; } for(i=0; i<=9;i++) for(j=i+1; j<=9;j++) if(a[i]%2!=0) {z=a[i]; a[i]=a[j]; a[j]=z; } for(i=1; i<=10;i++) cout<<a[i]<<" "; }
#include //enter two Dim matrix & print it using namespace std; int main() { int a[2][2],i,j; for(i=0;i<=1;i++) for(j=0;j<=1;j++) { cout<<"Enter a["<<i<<"]["<<j<<"]= "; cin>>a[i][j];} for(i=0;i<=1;i++) {cout<<endl; for(j=0;j<=1;j++) cout<<a[i][j] <<"\t";} }
#include // minimum number in matrix #include using namespace std; int main() { int A[2][2]={5,6,2,8}; int i,j,min=A[0][0]; for(i=0;i<=1;i++) for(j=0;j<=1;j++) {cout<<"Enter A["<<i<<"]["<<j<<"]= "; //cin>>A[i][j]; } for(i=0;i<=1;i++) {for(j=0;j<=1;j++) if(A[i][j]<min) min=A[i][j];} cout<<"\n min = " <<min;} }
#include //diameter of matrix using namespace std; int main() { int a[3][3]={{5,6,2},{8,7,4},{1,3,9}}; int i,j; for(i=0;i<3;i++) for(j=0;j<3;j++) if(i==j) cout<<a[i][j]<<" "; }