Jagged-Array Using For Each Loop in Java


A jagged array is an array of arrays such that member arrays can be of different row sizes and column sizes. Jagged subarrays may also be null. For instance, the following code declares and populates a two dimensional int array whose first subarray is of four length, second subarray is of three length, and the last subarray is a fours length array:
    Example :
        int [ ] [ ] a = { { 10,20,30,40 } , { 10,20,30 } , { 10,20,30,50 } } ;

This program demonstrates the use of enhanced for loops (also known as "for-each" loops) to iterate through a jagged array in Java. The program creates a jagged array a with three rows, and then uses an enhanced for loop to iterate through each row of the array.

The syntax for an enhanced for loop is for (type var : array), where type is the data type of the array elements, var is a new variable that is declared for each iteration of the loop, and array is the array being iterated through.

In this example, the outer for loop iterates through each row of a, assigning each row to a new integer array k for each iteration. The inner for loop then iterates through each element l of k, printing it to the console with a space separator using the System.out.print() method. After printing all the elements of a row, the program calls System.out.println() to print a newline character, so that each row is printed on a separate line.

Overall, this program demonstrates an alternative way to iterate through a jagged array in Java, using enhanced for loops instead of nested for loops.

Source Code

 
public class jagged_Array_for {
    public static void main(String args[])
    {
 
        //Jagged Array using En hanced For Loop in Java Programming
        int a[][]={
                {10,20,30,40},
                {10,20,30},
                {10,20,30,50}
        };
        for(int k[]:a) {
            for(int l:k)
            {
                System.out.print(" "+l);
            }
            System.out.println("");
        }
 
    }
}
 

Output

 10 20 30 40
 10 20 30
 10 20 30 50
To download raw file Click Here

Basic Programs