DEV Community

Cover image for For Loop & For-Each Loop
ROHIT KUMAR
ROHIT KUMAR

Posted on

For Loop & For-Each Loop

What is LOOP

Loops in JAVA are used to automate some particular task which is repeated for no.s of times.
Suppose that, you’re creating a program that print the fist five natural number its very easy to just write print statement five time,

BUT

What if you want to print the first 1000 natural number .
Its not feasible to just write 1000 lines of code which just do similar task here you will use a loop to automate the task
That will also reduces the line of code and increase readbility.

Java provides different types of loops,
Here we will see about For loop and For-each loop, with reference to a few examples and Java programs.

1️⃣.FOR LOOP

It is used to iterate a part of the program several times if the number of iteration is fixed.

SYNTAX:-

for (initialization;condition;updation)
{
     // body of the loop;
}
Enter fullscreen mode Exit fullscreen mode
  • Initialization is used to initialize a variable that keeps track of how many times the loop has executed.
  • Condition is a boolean expression whose condition is either true or false
    1. If its true then executes the body of the loop.
    2. If its false then its exit the loop.
  • Body of the loop Its the main code which needs to be repeated written inside the curly bracket which is called block of loop.
  • Updation is executed after the body of the loop and updates the initialization variable.

FLOWCHART:-

for loop

EXAMPLE 1:-

You need to print the first 10000 natural nos

class For{
  public static void main (String[]args){
    for(Int i =1;i<=10000;i++){
      System.out.print(i);
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

1
2
3
4
5
...so on

EXAMPLE 2:-

You are given the Array of students mark you need to find the maximum mark obtained using for loop

class Foreg 
{
    public static void main(String[] args)
    {
            int[] marks = { 400, 790, 600, 895 ,790 ,450, 670, 200,890  };

            int max=-1;
            // for each loop
            for (int i=0;i<marks.length();i++)
            {
            if (marks[i] > max)
             {
                max = marks[i];
             }
            }
            System.out.println("The Maximum mark is: " + max) ;
    }
}

Enter fullscreen mode Exit fullscreen mode

OUTPUT:

The Maximum marks is: 895


2️⃣.FOR EACH LOOP

  • Java for-each loop or enhanced for loop introduced in Java 5.
  • Its more simpler way to iterate through the elements of a collection or array.
  • Its used when we dont need know the index of the current array and its iterate through the elements in sequentail order

Note:

SYNTAX:-

for (dataType item : collection obj/array) {
    // Body of the loop
}
Enter fullscreen mode Exit fullscreen mode
  • DataType is the type of data our item uses.
  • Item is a variable which stores each value of the Collection as we iterate through the loop.
  • Collection is an array or collection variable through which the for loop will iterate.

HOW ITS WORK:-

  • WE declare the variable(item) which is of same type as the base type of array/collection, followed by a colon, which is then followed by the array/collection name.
  • Now we use the our item variable instead of indexed variable of array to loop traverses the array until the last element one by one in increasing order.
  • It stores each item in the item variable, then executes the code stored within the loop body.

FLOWCHART:-

Image

ADVANTAGE:-

  • It makes the code more readable.
  • It reduces the possibilty of bug.

DRAWBACK:-

  • You cant modify the array element because the object/variable is immutable when enhanced for loop is used.
  • It can only move single steps forward.
  • Do not keep track of index. So we can not obtain array index using For-Each loop
  • It cant traverse in the reverse order

EXAMPLE 1:-

You are given the Array of students mark you need to find the maximum mark obtained by using Enhanced For Loop

class ForEacheg 
{
    public static void main(String[] arg)
    {
            int[] marks = { 400, 790, 600, 895 ,790 ,450, 670, 200,890  };

            int max=-1;
            // for each loop
            for (int num : marks)
            {
            if (num > max)
             {
                max = num;
             }
            }
            System.out.println("The Maximum mark is: " + max);
    }
}

Enter fullscreen mode Exit fullscreen mode

OUTPUT:

The Maximum marks is: 895

EXAMPLE 2:-

You are need to print the all the menu item of coffee shop stored in the ArrayList


public class ForEach_Collection {

    public static void main(String[] args) {

        ArrayList<String> menu = new ArrayList<String>();

        menu.add("Cafe latte");
        menu.add("Cold Coffee");
        menu.add("Cappuccino");
        menu.add("Espresso")
        menu.add("Macchiato")

        // for-each loop
        for (String item : menu) {
        System.out.println(item);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

OUTPUT

Cafe latte
Cold Coffee
Cappuccino
Espresso
Macchiato


REFERENCE 1,2

IMAGE SOURCE 1,2

Thank You! 😊

You can follow me on
Linkedin
Twitter

Top comments (0)