Java – for each loop

Previous
Next

for-each loop:

  • It is also called enhanced for loop.
  • It is introduced in JDK 1.5
  • It is used to process array elements easily.
  • For each loop iterate all elements of array without taking bounds(lower and upper).

Syntax :

for(datatype  var :  arr)
{
	working with var.
}
  • In the above syntax, element by element from specified array collect into variable var.
  • We can process the value of var from the definition.
import java.util.Scanner;
class Demo 
{
	public static void main(String[] args) 
	{
		int n;
		Scanner scan = new Scanner(System.in);
		System.out.print("Ente size of array : ");
		n = scan.nextInt();

		int arr[ ] = new int[n];

		System.out.println("Enter " + n + " elements into array :");
		for (int i=0 ; i<n ; i++)
		{
			arr[i] = scan.nextInt();
		}

		System.out.println("Array elements are : " );
		for (int ele : arr)
		{
			System.out.println(ele);
		}
	}
}
Previous
Next

Add Comment

Courses Enquiry Form