This is a Clilstore unit. You can .
The format of the two-dimensional array description in the language C++:
type_of element sname_of the array [number of rows][number of columns];
For example: int A[2][3];
floatX[3][5];
Elements of arrayА: A[0][0], A[0][1], A[0][2],
A[1][0], A[1][1], A[1][2].
The two-dimensional array can also be defined in the description section.
int A[][]={7, 5, 2,
3, 9, 1};
Input of the elements of array a[2][3] in the computer's memory is carried out by entry:
for (i=0; i<2; i++)
for (j=0; j<3; j++)
cin>> a[i][j];
To display the array in the form of matrix on the screen, the following entry shall be used:
for (i=0; i<2; i++)
for (j=0; j<3; j++)
{cout<< a[i][j]<<” “;
cout<<”\n”;}
Example 34. Count the number of even and odd elements in the matrix.
main()
{ const int n=3, m=2;
int a[n][m]; int i, j, k=0, t=0; // k-even, t-odd
for (i=0; i<n; i++)
for (j=0; j<m; j++)
{cin>> a[i][j];
if (a[i][j]%2==0) k++; else t++; }
cout<<”number of even elements =”<<k<<”number of odd elements =”<<t;
}
Example 35. Find the sum of rows in elements of matrix X(3x4) filled with random integers in the range [10,50].
main()
{ int X[3][4]; int i, j, S;
srand(time(0));
for (i=0; i<3; i++)
for (j=0; j<4; j++)
X[i][j]=rand()%41+10;
for (i=0; i<3; i++) {
for (j=0; j<4; j++)
cout<<X[i][j]<<" "; cout<<"\n";}
for (i=0; i<3; i++)
{S=0;
for (j=0; j<4; j++)
S=S+X[i][j];
cout<<"\nS["<<i<<"]="<<S;}
getch();
Example 36. In a square matrix (matrix, where the number of rows equals to the number of columns) find the product of negative elements of the main diagonal and the number of odd elements of the secondary diagonal.
main()
{ int a[5][5]; int i, j, k=0, P=1;
for (i=0; i<5; i++)
for (j=0; j<5; j++)
{cin>>a[i][j];
if (i==j && a[i][j] <0) P=P*a[i][j];
if (i+j ==4 && a [i][j] % 2==1) k++;}
cout<<"\n P="<<P<<" k="<<k;
}
Short url: https://clilstore.eu/cs/6251