Dremendo Tag Line

Input numbers in 2d array and check sum of each row is same or not in C++

Two Dimensional Array - Question 8

In this question, we will see how to input numbers in a 3X3 integer matrix (2d array) and check whether the sum of each row is same or not in C++ programming. To know more about two dimensional array click on the two dimensional array lesson.

Q8) Write a program in C++ to input numbers in a 3X3 integer matrix (2d array) and check whether the sum of each row is same or not.

Program

#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
    int a[3][3], r,c,rs,frs,x=0;

    cout<<"Enter 9 numbers\n";
    for(r=0; r<3; r++)
    {
        for(c=0; c<3; c++)
        {
            cin>>a[r][c];
        }
    }

    for(r=0; r<3; r++)
    {
        rs=0;
        for(c=0; c<3; c++)
        {
            cout<<a[r][c]<<" ";
            rs=rs+a[r][c];
        }
        cout<<"  Row sum = "<<rs<<endl;
        if(r==0)
        {
            frs=rs;		// store the first row sum in frs variable
        }
        else if(frs!=rs)
        {
            x=1;
        }
    }

    if(x==0)
    {
        cout<<"Sum of each row is same";
    }
    else
    {
        cout<<"Sum of each row is not same";
    }
    return 0;
}

Output

Enter 9 numbers
5
5
5
5
5
5
5
5
5
5 5 5   Row sum = 15
5 5 5   Row sum = 15
5 5 5   Row sum = 15
Sum of each row is same
video-poster