2D-Arrays
2D-Arrays
Programming II
Dr. Zeinab Abd El Haliem
Motivation
• Represent table data / matrices
• Array cells are referenced using two indices
• First index for rows
• Second index for columns
Syntax
• It is a collection of data elements of same data type arranged in rows
and columns (that is, in two dimensions).
• Declaration
• Type name[# of rows][# of columns]
• For example: float grades[3][4] declares a 2D array having 3x4 cells (3
rows and 4 columns)
• Access
• name[i][j] accesses the value at the intersection of row i and column j
• Index numbers start at zero
Traversal
• Traversing a 2D array in order to read or store a value
requires 2 for loops
• One loop iterates over the rows
• The other loop iterates over the columns
• Example : filling a 10x5 array from the keyboard
for(int row = 0; row < 10; row++)
for(int col = 0; col < 5; col++)
cin >> grades[row][col];
2D Arrays & Function
• Function to Read A matrix
void Read(int A[][20], int N, int M)
{
for(int R=0;R<N;R++)
{
for(int C=0;C<M;C++)
{
cin>>A[R][C];
}
}
}
2D Arrays & Function (Cont.)
• Function to Print A matrix
void Print(int A[][20], int N, int M)
{
for(int R=0;R<N;R++)
{
for(int C=0;C<M;C++)
{
cout << A[R][C];
}
}
}
2D Arrays & Function (Cont.)
• Function to Add Two Matrices A & B
void ADD(int A[][20], int B[][20], int Z[][20], int N, int M)
{
for(int R=0;R<N;R++)
{
for(int C=0;C<M;C++)
{
Z[R][C]=A[R][C]+ B [R][C];
}
}
}
2D Arrays & Function (Cont.)
• Function To Multiply Two Matrices.