Dremendo Tag Line

Input numbers in 2d array and find the sum of each row in Java

Two Dimensional Array - Question 5

In this question, we will see how to input numbers in a 3X3 integer matrix (2d array) and find the sum of each row separately in Java programming. To know more about two dimensional array click on the two dimensional array lesson.

Q5) Write a program in Java to input numbers in a 3X3 integer matrix (2d array) and find the sum of each row separately.

Program

import java.util.Scanner;

public class Q5
{
    public static void main(String args[])
    {
        int a[][]=new int[3][3], r,c,rs;
        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);
        }
    }
}

Output

Enter 9 numbers
5
74
3
2
63
21
7
19
24
5 74 3   Row Sum = 82
2 63 21   Row Sum = 86
7 19 24   Row Sum = 50
video-poster