Loops in Java - while, do-while, for, for-each

 Loops in Java is used to execute a single or a block of statements repeatedly until a given condition is true.

There are the following loops used in Java:

  •     while
  •     do-while
  •     for
  •     for-each
1. while loop: 
           The while loop execute a block of statements as long as a specified condition is true. 
            Syntax:
                    while(condition){
                            //statements
                    }

            For Example:

                    int i = 0;
                    while(i<5){
                            System.out.print(i +  " ");
                            i++;
                    }

            Output: 0 1 2 3 4 

Note: If the condition is always true, in that case the above loop will be an infinite-loop.

2. do-while loop:
            This loop will execute the block of code atleast once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.
              Syntax:  
                    do{
                            //statements
                    }while(condition);

             For Example:
                
                    int i=1;
                    do{
                        System.out.print(i + " ");
                        i++;
                    }while(i<1);

            Output: 1

3. for loop:
            When you know exactly how many times you want to loop through a block of statements then use for loop instead of while loop.
            Syntax:
                    for(initialization; condition; increment or decrement){
                            //statements
                    }

            For Example:
                
                    for(int i=0; i<5; i++){
                               System.out.print(i + " ");
                    }

            Output: 0 1 2 3 4 

4. for-each loop:
             To loop through an array of elements, we can use for-each loop.
              Syntax:
                    for(type variableName : arrayName){
                            //statements
                    }

               Example:

                    int[] arr = {1, 2, 3, 4, 5};
                    for(int num: arr){
                            System.out.print(num + " ");
                    }

                Output: 1, 2, 3, 4, 5            





Comments

Popular Posts