In this post we will understand another category of control flow statements which are used to execute some part of your code multiple times until the condition is met.

for loop

To understand the for loop, let's understand its syntax.

for(initialisation; termination ;increment){
    statement(s);
}

- initialisation is executed once on starting of the loop.
- termination is the condition given to the loop. Loop executes till the termination condition becomes false.
- increment statement is executed on each loop iteration.

Let's understand this though a real java code

for(int i =0; i < 10; i++){
  System.out.println("Current iteration value is "+i);
}

- initialisation i.e. int i = 10 will be executed once on the start of the loop.
- code will be executed until termination i.e. i < 10 gives true.
- increment statement i.e. (i++) will run on every iteration.

If you run the above code you should see the following output.

Current iteration value is 0
Current iteration value is 1
Current iteration value is 2
Current iteration value is 3
Current iteration value is 4
Current iteration value is 5
Current iteration value is 6
Current iteration value is 7
Current iteration value is 8
Current iteration value is 9

while loop

while statement continuously executes the statement(s) until the condition is true. See syntax below.

while(expression){
    statement(s);
}

while loops are preferred when your loop condition is changed inside the loop. 

int count = 0;
while(count < 10){
    System.out.println("Count is now "+count);
    count++;
}

The above code will give the similar output as of the for loop.

do-while loop

do-while loop is similar to the while loop. The only change is that the condition is checked after the loop is executed. This makes sure that the loop will be executed at-least once even if the condition given in while is false.

do{
    statement(s);
}while(expression);

do-while loop are preferred when you have to execute the statement(s) at-least once.

Example

int count = 0;
do{
  System.out.println("Current Count is "+count);
  count++;
}while(count < 10);

Exercise Questions
1. Using for loop, print all the prime numbers till 100. [Solution]
2. Using while loop print the Fibonacci series till 100.

Comments