Java | Loops

05 min read

Enhanced 'for' loop or for each loop:

  • Eliminates the need to establish a loop counter, to specify the starting and ending values and to manually index the array.
  • This loop is designed to cycle through a collection of objects like an array, in a strictly sequential fashion, from start to finish (not only for arrays but for any collection of objects like vectors.
  • Cannot be substituted for a 'for' loop without collections (example: the 'for' loop used while finding the factorial).

Syntax:

for(type itr_var : Collection)
{
.......
}
must be compatible with the elements stored in the collection ie., type of the array, if array is being used.

 

Example 1: Program using for-each loop to print all the array elements.

int[ ] a ={1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

for(int x : a) -> 'x', the iteration variable is of the same type as that of the array

System.out.println(x);  --> O/P: 1 2 3 4 5 6 7 8 9 10

 

Example 2: Find the sum of all the following float array elements using for-each loop. float f={2.4, 3.6, 3.9, 12.8, 10.5};

float sum = 0; // to assign 0.0, the statement should float sunz=0.01' for(float i :

sum += i;

System.out.println(sum);

 

for-each loop:

A 'for-each' loop is used to iterate through the whole array.

In the previous example, if the sum of only the first 3 elements has to be found, it can be modified as follows:

float[ ] f={2.4, 3.6, 3.9, 12.8, 10.5);
float sum = 0;                                                                                              
int count=0;
for(float i : f)
{
sum += i;                                                
if(++count >= 3)
}
System.out.println(sum);

As the array elements are float, the iteration variable should also be a float.

 

Example 2: The previous 'minmax_array' program with for-each loop

for(int i= 1 ;i< 1 0; i++)
a[i]=sc.nextInt( );
max=min=0;
for(int x : a)
{
if(x > max)
max=x;
if(x < min)
min=x;
}

Note: Here, the for-each loop cannot be used for the reason that a for-each loop processes the values in the array, not the elements (ie., the memory locations).

 

Invalid:

int[ ] a = new int[ 1 0];
for(int x : a) 
x = 10;  --> The array elements will still have their default values '0'.

The iteration variable is 'read-only', and hence an assignment to the iteration variable has no effect on the underlying array. ie., The array contents cannot be changed by assigning the iteration variable, a new value.

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error