![]() |
![]() |
Java if statement | |
Java if-else statement | |
Java nested if-else | |
Java else-if ladder | |
Java Switch case statement | |
Java Nested Switch Case | |
Java Ternary/Conditional operator |
Java while loop | |
Java do-while loop | |
Java for loop | |
Java Enhanced loop/for each loop | |
Java Labelled for loop | |
Java Nesting of loops | |
Java Break and Continue |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
The for is a entry-controlled loop that provides a more short loop control structure that other loops.
For loop is the most popular looping instruction due to it's simple instruction.
for (initialization; test-condition; increment/decrement) { // body of for loop .... .... .... }
The execution of the for statement is performed based on following 3 steps.
class ForLoopEx { public static void main(String args[]) { int i=0,num=5; for(i=1;i<=10;i++) { System.out.println(i * num); } } }
We can write for loop without writting initialization statement. But semicolon is necessary in the condition.
Loop will execute just like above example.
int i=0,num=5; for( ; i<=10; i++) { System.out.println(i * num); }
Output: table of 5
We can also write the for loop without using Initialization and Increment/Decrement statement.But semicolon is necessary in both the conditions.
We can provide Increment/Decrement inside the body of the loop.
int i=0,num=5; for( ; i<=10; ) { System.out.println(i * num); i++; }
Output: table of 5
We can also write the for loop without using any statement out of 3. This for loop will cause an infinite loop.
int i=0,num=5; for( ; ; ) { System.out.println(i * num); i++; }
Output: table of 5 to Inifinite numbers
We can write more than one initializers inside the for loop.
int i=0,num=0; for( i=1,num=5; i<=10 ;i++ ) { System.out.println(i * num); }
Output: table of 5
We can also write more than one initializations and Increments inside the for loop.
int i=0,num=0,result=0; for( i=1,num=5,result=num ; i<=10 ; i++,result=i*num) { System.out.println(result); }
Output: table of 5