2d Arrays
2d Arrays
2d Arrays
TWO-DIMENSIONAL ARRAYS
C++ also allows an array to have more than one dimension.
The declaration must specify the number of rows and the number of columns,
and both must be constants.
PROCESSING A 2-D ARRAY
A one-dimensional array is usually processed via a for loop. Similarly, a two-
dimensional array may be processed with a nested for loop:
Each pass through the inner for loop will initialize all the elements of the current
row to 0.
The outer for loop drives the inner loop to process each of the array's rows.
INITIALIZING IN DECLARATIONS
int Array1[2][3] = { {1, 2, 3} , {4, 5, 6} };
int Array2[2][3] = { 1, 2, 3, 4, 5 };
int Array3[2][3] = { {1, 2} , {4 } };
Rows of Array1:
1 2 3 for (int row = 0; row < 2; row++) {
4 5 6 for (int col = 0; col < 3; col++) {
cout << setw(3)
Rows of Array2:
1 2 3 << Array1[row][col];
4 5 0
}
But now the number of columns in the array parameter must be specified.
This is because arrays are stored in row-major order, and the number of
columns must be known in order to calculate the location at which each row
begins in memory:
#include <iostream>
#include <iomanip>
using namespace std;
cout<<endl;
for(int C=0;C<M;C++)
cout<<setw(10) <<A[R][C]+B[R][C];
}
}
FUNCTION TO FIND & DISPLAY SUM OF ROWS & SUM
OF COLS. OF A 2D ARRAY A
for(int R=0;R<M;R++)
{
int SumC=0;
for(int C=0;C<N;C++)
SumC+=A[C][R];
cout<<"Column("<<R<<")="<<SumC<<endl;
}
}