Extended For Loop

For each loop:
the for-each loop introduced in Java5. It is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable.
Syntax:
for(datatype var : Array)
{
            Statements;
}

Program on for loop using arrays

import java.util.Scanner;
class Arrays
{
public static void main(String args[])
{
int i,n;
int []a=new int[50];
Scanner r=new Scanner(System.in);
System.out.println(“Enter n value”);
n=r.nextInt();
for(i=0;i<n;i++)
{
System.out.println(“Enter no”);
a[i]=r.next();
}
for(int k : a)
{
System.out.println(k);
}
}
}

 

Program on foreach loop in double dimentional array

import java.util.Scanner;
class Array4
{
public static void main(String args[])
{
int a[ ][ ]=new int[20][20];
Scanner r=new Scanner(System.in);
int m,n;
System.out.println(“Etner m ,n Values”);
m=r.nextInt();            
n=r.nextInt();
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
System.out.println(“etner a matrics values”);
a[i][j]=r.nextInt();
}
}
For(int k : a)
{
System.out.println(k);
}
}
}

 

 

For
More Explanation
&
Online Classes

Contact Us: +919885348743