Take an array of size 5x5 and initialize it with random numbers of range 1 to 10, now add all the elements of the 2D array and display sum.
Modify part a in such a way that you have to find individual sum of each row of the 2D array and store corresponding result in 1D array i.e. sum of all the elements of row 0 should be stored in 1st element of 1D array, similarly sum of all elements of the second row of 2D array should be stored at the second
index of 1D array. Display the final sum array (i.e. 1D array). Think about the size of 1D array yourself.
Example:
Array:
2 3 5 3 1
4 5 1 2 1
4 7 3 2 0
2 1 1 5 1
1 7 8 9 0
Sum array:
14 13 16 10 25
Perform sum of all the elements of the arrays whose row number and column number both are odd. Display the final sum.
Array:
2 3 5 3 1
4 5 1 2 1
4 7 3 2 0
2 1 1 5 1
1 7 8 9 0
Sum: 13
#include <iostream>
#include <ctime>
#include <stdlib.h>
#include <iomanip>
using namespace std;
int main() {
const int line = 5;
const int col = 5;
int array[line][col] = {};
int i,j;
int sum=0;
srand(time(NULL));
for( i=0; i<line; ++i)
for( j=0; j<col; ++j)
array[i][j] = rand()%10 + 1; // Random int range from 1 to 10
cout<<endl<<"array:"<<endl;
for( i=0; i<line; ++i) {
for( j=0; j<col; ++j) {
cout<<setw(3)<<array[i][j]<<' ';
sum=sum+array[i][j];
}
cout<<endl;
}
cout<<"\nsum: "<<sum<<endl;
int arrSum[line]={0,0,0,0,0};
for( i=0; i<line; ++i) {
for( j=0; j<col; ++j) {
arrSum[i]=arrSum[i]+array[i][j];
}
}
for(i=0; i<line; i++)
cout<<arrSum[i]<<" ";
cout<<endl;
cout<<endl<<"Sum of all the elements of the arrays \n"
<<"whose row number and column number both are odd:"<<endl;
sum=0;
for( i=0; i<line; ++i) {
for( j=0; j<col; ++j) {
if(j%2!=0 && i%2!=0)
sum=sum+array[i][j];
}
}
cout<<sum;
cout<<endl;
return 0;
}
Comments
Leave a comment