Sunday, 29 January 2017

FOR-EACH LOOP IN JAVA

It is also known as enhanced for loop. It is the specially designed loop to iterate the elements of arrays and collections. For-each loop is the most comfortable loop for retrieving the elements of arrays and collection but its limitation is, that it isn’t a general purpose loop. We can’t write equivalent for each loop directly.

Example –
public class Loop9 {
          public static void main(String[] args) {
                   int num[] ={1,2,4,8,9};
                   for(int num1:num)
                   {
                             System.out.print(num1+" ");
                   }
          }
}

Output –
1 2 4 8 9

Note – In the above example as it is a one dimensional array so in the foreach loop we take one variable num1 of type int which holds the value of num. After each iteration in the num array num1 holds its value and we print the values.

Example –
import java.util.Scanner;
public class Loop10 {

          public static void main(String[] args) {
                   Scanner sc = new Scanner(System.in);
                   System.out.print("Enter number of rows : ");
                   int row = sc.nextInt();
                   System.out.print("Enter number of columns : ");
                   int col = sc.nextInt();
                   int num[][]=new int[row][col];
                   System.out.println("Enter values in 2D array");
                   // assigning values to 2D array
                   for(int i=0;i<num.length;i++)
                   {
                             for(int j=0;j<num.length;j++)
                             {
                                      num[i][j]=sc.nextInt();
                             }
                   }
                   //fetching the values
                   System.out.println("Fetched records are");
                   for(int i[]:num)
                   {
                             for(int j:i)
                             {
                                      System.out.print(j+" ");
                             }
                             System.out.println();
                   }
          }
}

Output –
Enter number of rows : 3
Enter number of columns : 3
Enter values in 2D array
1
2
3
4
5
6
7
8
9
Fetched records are
1 2 3
4 5 6
7 8 9


Note – In the above example as it is a 2D array, so we have to iterate 2 times in an array. So for the first time when it iterates it stores the into i as an array for the first row and then in the inner loop it prints the value by storing it into j.

No comments:

Post a Comment