Answer to Question #190661 in C++ for M Kamran

Question #190661

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



1
Expert's answer
2021-05-08T05:01:17-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS