Java For loop with Examples

In java, for loop is a type of control statement which iterates the particular portion or part of the program multiple times. for loop contains the initialization, condition, and increment/decrement which make it small and easy to debug.

Syntax

for (initialization expr; test expr; update exp
{
     // body of the loop
     // statements we want to execute
}


Parts of for loop

1. Initialization: Expression which initializes the loop counter.

Example: 
int i = 1;

2. Test: This expression is responsible for the test condition. if the condition is true then we will execute the body of the loop and move to update the expression. else we will exit from the loop. 

Example:
i<=10

3. Update Expression: After executing the loop body, this expression increment/decrement the loop variable.


Flow chart for loop (For Control Flow):

Java For loop with Examples



Example 1: This program will try to print “Hello World” 6 times.

// Java program to illustrate for loop 
class forLoopDemo { 
    public static void main(String args[]) 
    { 
        // Writing a for loop 
        // to print Hello World 5 times 
        for (int i = 1i <= 6i++) 
            System.out.println("Heelo World"); 
    } 


Output

Hello World!

Hello World!

Hello World!

Hello World!

Hello World!

Hello World!


Example 2: The following program prints the sum of x ranging from 1 to 10.

Code


public class sumofnumbers {
    public static void main(String args[]){
        int sum = 0;
        for (int i=1;i<=10;i++){
            sum = sum+i;
        }
        System.out.println("Sum "+sum);

    }
}


Output

Sum 55



Enhanced For Loop or Java For - Each Loop

Another version of for loop introduced n Java 5. Enhanced for loop gives an easy way to iterate through the elements of a collection or array. It is flexible and should be used only with the array.


Syntax


for (T element:Collection obj/array)
{
    // loop body
    // statement(s)
}


Example


public class enhancedforloop {
        public static void main(String args[]) 
        { 
            String array[] = { "Sam""Henry""Kick" }; 
      
            // enhanced for loop 
            for (String x : array) { 
                System.out.println(x); 
            } 
      
            /* for loop for same function  
            for (int i = 0; i < array.length; i++)  
            {  
                System.out.println(array[i]);  
            }  
            */
        } 
    } 


Output


Sam

Henry

Kick


Post a Comment

0 Comments