In: Computer Science
Write a function declaration for a function that sums each row of a 2D array, where each row size is 10. The function does not return a result. Need it in 10 minutes, please.
Program:
import java.util.*;
class RowsSumDemo
{
public static void sumOfEachRow(int M[][])
{
//calculating the sum of each row
int sum=0;
int sumRow[]=new int[10];
for(int r=0;r<=9;r++)
{
sum=0;
for(int c=0;c<=9;c++)
{
sum=sum+M[r][c];
}
sumRow[r]=sum;
}
//Displaying each row with its sum
System.out.println("\n\nElements of the Array & sum of each
row: \n");
for(int r=0;r<=9;r++)
{
for(int c=0;c<=9;c++)
{
System.out.print(M[r][c]+" ");
}
System.out.println(" = "+sumRow[r]);
}
}
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int N;
//Assume there are 10 rows and 10 columns
int M[][]=new int[10][10];
//Accepting values from user
System.out.println("\nEnter elements: \n");
for(int r=0;r<=9;r++)
{
for(int c=0;c<=9;c++)
{
M[r][c]=sc.nextInt();
}
}
//calling the function
sumOfEachRow(M);
System.out.println("\n");
}
}
Output: