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


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