for loop in Java

General syntax

for(initialization;condition;increment/decrement){

//body or statements to be executed

}


Steps by step procedure of for loop execution are

  • Intialization of variable.
  • Then checks condition given in for loop.
  • If condition is satisfied, it comes inside the loop and executes the body of the loop.
    • When the body got executed, the control will shift to increment/decrement part.
    • Then again the condition check is done with new incremental/decremental value.
    • If condition gets satisfied again, it comes inside the loop and executes the body of the loop.
    • The above gets repeated until the condition returns false.
  • If the condition is not satisfied the loop terminates or stops running.

Example

Imagine you as a money lender. You have got today some amount of interest from various people.

You want to add the interest. What you will do this with the help of programming?

Assume interest_money from number of people as a array variable.

public class ForloopTest {

public static void main(String args[]) {

int interest[]={105,110,1200,3456,1234},sum=0;

for(int i=0;i<5;i++){

sum=sum+interest[i];

}

System.out.println("Total interest is "+sum);

}

}

Try In Editor

Output

Total interest is 6105


Intialization, condition and increment are not compulsory to be given in for loop but semicolons(;;) should be given, if not throws error.


Example for infinite for loop

public class ForloopTest {

public static void main(String args[]) {

for(;;){

System.out.println("1");

}

}

}

Try In Editor