
Define a class to accept values into a 4 x 4 integer array. Calculate and print the NORM of the array. NORM is the square root of sum of squares of all elements. 1 2 1 3 5 2 1 6 3 6 1 2 3 4 6 3 Sum of squares of elements = 1 + 4 + 1 + 9 + 25 + 4 + 1 + 36 + 9 + 36 + 1 + 4 + 9 + 16 + 36 + 9 = 201 NORM = square root of 201 = 14.177446878757825
Topic: Two-dimensional array — NORM
Answer
import java.util.Scanner;
class Norm { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int a[][] = new int[4][4]; int sum = 0; double norm;
System.out.println("Enter 16 elements of the 4 x 4 array :"); for(int i = 0; i < 4; i++) for(int j = 0; j < 4; j++) a[i][j] = sc.nextInt();
for(int i = 0; i < 4; i++) for(int j = 0; j < 4; j++) sum = sum + a[i][j] * a[i][j];
norm = Math.sqrt(sum);
System.out.println("The array is :"); for(int i = 0; i < 4; i++) { for(int j = 0; j < 4; j++) System.out.print(a[i][j] + "\t"); System.out.println(); } System.out.println("Sum of squares of elements = " + sum); System.out.println("NORM of the array = " + norm); } }
Every 2-D array question is built from the same skeleton: an outer loop over rows and an inner loop over columns. Get that pattern automatic and only the middle line changes from question to question.
Here three separate traversals are used — one to read, one to total the squares, one to display. You may combine the first two into a single pass, but keeping them apart makes the logic clearer and costs no marks.
The squaring is done as a[i][j] * a[i][j] rather than with Math.pow(), because pow() returns a double and would force an unnecessary cast. sum stays an int; only norm is a double, since Math.sqrt() always returns a double.
Verify with the sample: the squares total 201 and Math.sqrt(201) gives 14.177446878757825, exactly the figure printed in the question. When a question supplies a worked example, always trace your logic through it before writing — it is free confirmation that your formula is right.
a[][] int[4][4] - stores the 16 elements entered by the user sum int - running total of the squares of all elements norm double - square root of sum, the NORM of the array i, j int - loop variables for rows and columns sc Scanner - object used to read input from the keyboard