foreach loop in JAVA

Posted By on September 12, 2014


Download PDF
loops in java
JAVA ASSIGNMENT 1

For each (or foreach) is a looping method to traverse  all the elements of collection.

Foreach is usually used in place of a standard for statement.

Unlike other for loop constructs, however, foreach loops  usually maintain no explicit counter: they essentially say “do this to everything in this set”, rather than “do this x times”.

This avoids potential off-by-one errors ( logical errors )and makes code simpler to read. In object-oriented languages an iterator, even if implicit, is often used as the means of traversal.

 

The syntax for foreach loop is::

for(type  variable: array_name)

{

// operations on aray //

}

 

example::

package foreach;
import java.util.Scanner;
class Foreach

{
public static void main(String[] args) {

int i;
int a[] = new int[5];
Scanner s = new Scanner(System.in);

System.out.println(“Enter the array:”);

for(i=0; i<5; i++)
{
a[i]=s.nextInt();
}

// The array displaying using foreach loop. //

System.out.println(“The array displaying using foreach loop.”);

for(int j: a)
{
System.out.println(j);
}

}

}

 

#output::

Enter the array:

10

20

30

40

50

The array displaying using foreach loop:

10

20

30

40

50

loops in java
JAVA ASSIGNMENT 1

Download PDF

Posted by Akash Kurup

Founder and C.E.O, World4Engineers Educationist and Entrepreneur by passion. Orator and blogger by hobby

Website: http://world4engineers.com