Free Response Practice Question (with solution)- Square Function Matrix
<-- Back to 2D Alphabet Matrix | Next to Point 2D Array --> |
Square Function Matrix
A function f(X) over a square matrix (X) is defined as follows:
Write a program to read a 3 X 3 matrix of positive integers and computes the f(X) for this matrix.
Example 1: Consider X =
Then f(X) = 3
Example 2: Consider X =
Then f(X) = 36/2 = 18
Solution:
View SolutionSquareFunction.java
import java.util.InputMismatchException; import java.util.Scanner; public class SquareFunction { 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 max = Integer.MIN_VALUE; int sumSquares =0; for (int k=0; k < ROW; k++) { for (int j=0; j < COL; j++) { System.out.print(intArr[k][j]+ " "); if (max< intArr[k][j]) max = intArr[k][j]; sumSquares = sumSquares + (intArr[k][j] * intArr[k][j]); } System.out.println(); } System.out.print("The value of the function f(x): "+ sumSquares/max); } catch (InputMismatchException e) { System.out.println("Error reading input"); } }// end of main }
Sample Output:
View OutputExample 1:
Example 2:
Java project files (with Runner code):
<-- Back to 2D Alphabet Matrix | Next to Point 2D Array --> |