In: Computer Science
Which row has the largest sum? Write a method that takes a 2D int array and prints: of
The index of the row that has the largest sum
The sum of elements in that row
java
The required method is given below:
//method to return the row number having the largest sum
public static void largestSum(int arr[][])
{
//variable declaration and initialization
int sum = 0, largSum=0;
int idx = 0;
//find the index of largest sum row
for(int i = 0; i < arr.length; i++)
{
sum = 0;
for(int j = 0; j < arr[0].length; j++)
{
sum = sum + arr[i][j];
}
if(sum>largSum)
{
largSum = sum;
idx = i;
}
}
//display the result
System.out.println("The index of the row that has the largest sum:
"+idx);
System.out.println("The sum of elements in that row:
"+largSum);
}
The complete program source code including the above method for testing is given below:
public class Main
{
//method to return the row number having the largest sum
public static void largestSum(int arr[][])
{
//variable declaration and initialization
int sum = 0, largSum=0;
int idx = 0;
//find the index of largest sum row
for(int i = 0; i < arr.length; i++)
{
sum = 0;
for(int j = 0; j < arr[0].length; j++)
{
sum = sum + arr[i][j];
}
if(sum>largSum)
{
largSum = sum;
idx = i;
}
}
//display the result
System.out.println("The index of the row that has the largest sum:
"+idx);
System.out.println("The sum of elements in that row:
"+largSum);
}
public static void main(String[] args)
{
//array declaration and initialization
int arr[][] = {{1, 2, 3}, {4, 5,
6}, {2, 1, 3}};
//method calling
largestSum(arr);
}
}
OUTPUT:
The index of the row that has the largest sum: 1
The sum of elements in that row: 15