Free Response Practice Question (with solution)- 2D Balanced Matrix Array
| <-- Back to AP CSA Exam Solutions | Next to 2D Alphabet Matrix --> |
2D Balanced Matrix Array
Write a Java program that reads a 3 X 3 array of integers (positive, negative or zeros) and calculates and prints if it is a balanced matrix or not.
A matrix is defined as balanced, if all the following conditions are met:
- the sum of the elements in the first row is zero.
- the sum of the elements in the first column is zero.
- the sum of the elements in the major diagonal is zero.
For example, consider the matrix a shown in the example:
For this matrix, sumFirstRow= sumFirstCol=sumDia=0

Hence it is a balanced matrix.
Solution:
View SolutionBalancedMatrix.java
import java.util.InputMismatchException;
import java.util.Scanner;
public class BalancedMatrix {
public static void main(String args[])
{
int ROW = 3;
int COL = 3;
int[][] intArr = new int[ROW][COL];
try (Scanner input = new Scanner(System.in)) {
System.out.println("Enter positive integer for "+ ROW + " X " + COL +" matrix: ");
for (int i=0; i< ROW ; i++)
{
for (int j=0; j < COL; j++)
{
System.out.print("Enter the ["+ i +"] ["+j+"] value: ");
intArr[i][j] = input.nextInt();
}
}
System.out.println("Integers in the matrix are: ");
int sumFirstRow =0;
int sumFirstCol=0;
int sumDia=0;
for (int k=0; k < ROW; k++)
{
for (int j=0; j < COL; j++)
{
System.out.print(intArr[k][j]+ " ");
if (k == 0) sumFirstRow= sumFirstRow + intArr[k][j]; // first row
if (j == 0) sumFirstCol= sumFirstCol + intArr[k][j]; // first column
if (k == j) sumDia = sumDia + intArr[k][j]; // diagonal element
}
System.out.println();
}
System.out.println("The sum of first row elements is: "+ sumFirstRow);
System.out.println("The sum of first col elements is: "+ sumFirstCol);
System.out.println("The sum of major diagonal elements is: "+ sumDia);
if ((sumFirstRow == 0) && (sumFirstCol == 0) && (sumDia == 0))
System.out.print("It is a Balanced Matrix");
else
System.out.print("It is NOT a Balanced Matrix");
} catch (InputMismatchException e)
{
System.out.println("Error reading input");
}
}// end of main
}
Sample Output:
View Output
Java project files (with Runner code):
| <-- Back to AP CSA Exam Solutions | Next to 2D Alphabet Matrix --> |