Row Sum of Matrix
This program calculates the sum of each row in a matrix.
Problem Statement
Write a Java program to calculate the sum of each row in a 3x3 matrix.
Source Code
| 1 | public class MatrixRowSum { |
| 2 | public static void main(String[] args) { |
| 3 | int[][] A = {{1,2,3},{4,5,6},{7,8,9}}; |
| 4 | for(int i=0;i<3;i++){ |
| 5 | int sum=0; |
| 6 | for(int j=0;j<3;j++){ |
| 7 | sum+=A[i][j]; |
| 8 | } |
| 9 | System.out.println("Sum of row "+i+": "+sum); |
| 10 | } |
| 11 | } |
| 12 | } |
Program Output
Sum of row 0: 6 Sum of row 1: 15 Sum of row 2: 24
Explanation
The outer loop iterates through rows and the inner loop adds all elements of each row into a local sum, which is printed per row, demonstrating how multidimensional arrays can be processed row by row.