For Loop (Part 3)
For Loop
When you know exactly how many times you want to loop through a block of code, we use the
for
loop. The block of code runs until the conditions of for loop are satisfied , as soon as block of code fails the condition , it exits the loop.The for loop is also called as an entry controlled loop , as before executing condition is checked.
Syntax:-
for (initialization ; condition ; increment/decrement operator)
{
//block of code
}
Flowchart:-
public class MyClass {
public static void main(String args[]) {
int num = 5;
for (int i=1;i<=5;i++)
{
System.out.println("The block has run " +i+" times.");
}
}
}
Output:-
The block has run 1 times.
The block has run 2 times.
The block has run 3 times.
The block has run 4 times.
The block has run 5 times.