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>
using namespace std;
int main(){
int arr[5][5];
//initialize the array with random numbers between 1 and 10
for (int i = 0; i <5; i++){
for(int j = 0; j < 5; j++){
arr[i][j] = rand()%10;
cout<<arr[i][j]<<"\t";
}
cout<<endl;
}
//get the sum of all the elements of the 2d array
int sum=0;
for (int i = 0; i <5; i++){
for(int j = 0; j < 5; j++){
sum=sum+arr[i][j];
}
}
cout<<"\nSum of all elements: "<<sum<<endl;
//sum elements of individual row
int arr2[5];
int sum_row=0;
for (int i = 0; i <5; i++){
for(int j = 0; j < 5; j++){
sum_row=sum_row+arr[i][j];
}
//reset the sum
arr2[i]=sum_row;
sum_row=0;
}
cout<<"Sum of Individual rows: ";
for (int i=0;i<5;i++){
cout<<arr2[i]<<"\t";
}
return 0;
}
Comments
Leave a comment