Advertisements
Advertisements
Question
Write a program to accept a double dimensional array as a parameter and find the sum of the elements of each row.
Code Writing
Advertisements
Solution
import java.util.*;
public class DDA2
{
public void main()
{
Scanner sc = new Scanner(System.in);
int ar[ ][ ] = new int[3][4];
int r, c;
System.out.println("Fill the array: ");
for(r = 0; r < 3; r++)
{
for(c = 0; c < 4; c++)
{
System.out.print("Cell[" + r + "][" + c + "]: ");
ar[r][c] = sc.nextInt();
}
}
System.out.println("The array is : ");
for(r = 0; r < 3; r++)
{
for(c = 0; c < 4; c++)
{
System.out.print(ar[r][c] + " ");
}
System.out.println();
}
System.out.println("The Sum of elements of rows : ");
for(r = 0; r < 3; r++)
{
int sum = 0;
for(c = 0; c < 4; c++)
{
sum = sum + ar[r][c];
}
System.out.println("Row " + r + " = " + sum);
}
}
}
Output:
Fill the array:
Cell[0][0] : 10
Cell[0][1] : 20
Cell[0][2] : 30
Cell[0][3] :15
Cell[1][0] : 11
Cell[1][1] : 22
Cell[1][2] : 44
Cell[1][3] : 66
Cell[2][0] : 50
Cell[2][1] : 52
Cell[2][2] : 54
Cell[2][3] : 56
The array is :
10 20 30 15
11 22 44 66
50 52 54 56
The Sum of elements of rows:
Row 0 = 75
Row 1 = 143
Row 2 = 212
shaalaa.com
Is there an error in this question or solution?
