Transcript Click here

Arrays of Two-Dimensions
Syntax ( in Algorithm ):
Syntax ( in C++ ):
Array aname [nrows] [ncolumns] of atype
atype aname [nrows] [ncolumns] ;
Example:
Example:
//declaring array B of 2 rows and 3 columns
Array B [2] [3] of type integer
int B [2] [3] ;
Array in diagram:
1
Arrays of Two-Dimensions
• Reading array of two-dimensions:
2
Syntax ( in Algorithm ):
Syntax ( in C++ ):
Array B [2] [3] of type integer
for ( i  1 to 2 by 1 ) do
for ( j  1 to 3 by 1 ) do
input B[i][j]
End for
End for
int B [2] [3] ;
int i , j ;
for ( i = 0 ; i < 2 ; i++ )
for ( j = 0 ; j < 3 ; j++ )
cin >> B[ i ] [ j ] ;
Example1
Write algorithm and a C++ program that reads array A of size (2 x 3) and finds
the sum of the elements in each column.
Algorithm sum_columns
begin
Array B[2][3] of type integer
output "Enter 6 array elements: "
for ( i 1 to 2 by 1 ) do
for ( j1 to 3 by 1)do
input B[i][j]
End for
End for
// Process the array now
for ( j1 to 3 by 1)do
for ( i 1 to 2 by 1 ) do
clmsum  clmsum + B[i][j]
End for
output " sum of column no. " , j , " is " , clmsum
clmsum  0
End for
End sum_columns
3
Example1
#include <iostream>
using namespace std;
void main ( )
{ int i, j , clmsum = 0 ;
int B[2][3];
cout << "Enter 6 array elements: " ;
for ( i = 0 ; i < 2 ; i++ )
for ( j = 0 ; j < 3 ; j++)
cin >> B[i][j] ;
// Process the array now
for ( j = 0 ; j < 3 ; j++)
{
for ( i = 0 ; i < 2 ; i++ )
clmsum = clmsum + B[i][j] ;
cout << " sum of column no. " << j << " is " << clmsum<<endl;
clmsum = 0;
}
}
4
Example2 of Two-Dimensional Array
• Write algorithm and a C++ program that reads an array of size
(3 x 3) and finds the product of the diagonal elements.
5
Example2(Algorithm)
Algorith Product_D_E
Begin
Array B[3][3] of type integer
product  1
output "Enter the 9 array elements: "
for ( i  1 to 3 by 1 ) do
for ( j  1 to 3 by 1 ) do
input B[i][j]
End for
End for
// Process the array now
for ( i  1 to 3 by 1 ) do
for ( j  1 to 3 by 1 ) do
if ( i = j ) then
product  product * B[i][j]
End if
End for
End for
output " The product of the diagonal elements = " , product
End Product_D_E
6
Example2(C++)
#include <iostream>
Using namespace std;
void main ( )
{ int i, j , product = 1 ;
int B[3][3];
cout << "Enter the 9 array elements: " ;
for ( i = 0 ; i <3 ; i++ )
for ( j = 0 ; j < 3 ; j++)
cin >> B[i][j] ;
// Process the array now
for ( i = 0 ; i < 3 ; i++)
for ( j = 0 ; j < 3 ; j++ )
if ( i == j )
product = product * B[i][j] ;
cout << " The product of the diagonal elements = " << product << endl;
}
7