pratik jain
pratik jain

Reputation: 49

How for each loop is working in this rectangular array?

import java.util.Scanner;
public class Recarraysumandmat 
{
    public static void main(String[] args) { 

        Scanner kb=new Scanner(System.in);
        System.out.println("Enter row and column size: ");
        int n=kb.nextInt();
        int m=kb.nextInt();
        int sum=0;
        int [][]arr;
        arr=new int[n][m];
        for (int[] arr1 : arr) {
            for (int j = 0; j < arr1.length; j++) {
                arr1[j] = kb.nextInt();
            }
        }
        for (int[] arr1 : arr) 
        {
            for (int j = 0; j < arr1.length; j++) {
                System.out.print(arr1[j] + " ");
                sum = sum + arr1[j];
            }
            System.out.println();
        }
        System.out.println("The sum is: "+sum);
    }
}

Please tell me how the for-each loop is working here for taking the input in rectangular array and why NetBeans IDE is recommending for each loop over the normal for loop I have studied that for-each loop is only useful for traversing array not for taking input in the array.

Please explain about how for-each loop is working here with rectangular array if you could.

Upvotes: 0

Views: 229

Answers (1)

pratik jain
pratik jain

Reputation: 49

2D-arrays in java are actually not 2D arrays, but an array of arrays, so what happens is the 1D array would contain references to other arrays(rows). When the loop is entered and an array is set for each iteration, it's just following a reference to get that array and then get its size using arr1.length(which is the size of that array which would be the column number of the base array)

Upvotes: 1

Related Questions