Dremendo Tag Line

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

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 Java programming. To know more about two dimensional array click on the two dimensional array lesson.

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

Program

import java.util.Scanner;

public class Q8
{
    public static void main(String args[])
    {
        int a[][]=new int[3][3], r,c,rs,frs=0,x=0;
        Scanner sc=new Scanner(System.in);

        System.out.println("Enter 9 numbers");
        for(r=0; r<3; r++)
        {
            for(c=0; c<3; c++)
            {
                a[r][c]=sc.nextInt();
            }
        }

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

        if(x==0)
        {
            System.out.println("Sum of each row is same");
        }
        else
        {
            System.out.println("Sum of each row is not same");
        }
    }
}

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