A loop is a concept where something continues endlessly until it is asked to stop. Just like the sun rises in the east and sets in the west is a loop that continues endlessly.
In java we can use the loop concept to print a block of code multiple times.
There are three ways by which we can define a loop in java :
1. while loop
2. for loop
3. do - while loop
Do you remember when your teacher asked you to tell the numbers from 1 to 10, how you have done that?
You would have simply memorized it. But java won't do that.
We would be using a concept of loops to let java print 1 to 10.
So, we are teaching java to print the numbers from 1 to 10. Firstly, we are asking java to store the number '1' to a variable 'num'.
Then we are using the while() loop.
The above condition says, continue to be in the loop until the value of 'num' is less than or equal to 10 (i.e. 'num <=10').
And inside the loop, we will increase the value of 'num' by 1 every time it enters the loop.
It is same as, you put 1 cup of water in a container until it gets overflowed.
1. The initial value of num is 1.
2. When it comes to 'while(num <=10)' line, it finds 1 is less than 10.
3. So, it gets inside the loop,
4. And finds the line 'System.out.println(num);'. So, it prints 1.
5. In the next line we are adding '1' to 'num'.
So the new value of 'num' is '2'.
6. Again it goes to the condition and checks if 'num <=10'.
7. Off course '2' is less than 10. So it gets into the loop again. Comes to 'System.out.println(num);' which prints '2' again.
8. Then it comes in the next line
So the current value of 'num' becomes '3'.
9. And the same thing continues again and again until the value of num is less than or equal to 100.
10. So, when the value of 'num' is 11, it comes out of the loop.
We are rewriting the same example using 'for' loop.
Now, if we break the contents of 'for' loop, we get :
Initialization part : It is run before the loop starts.
Conditional part : It states the condition for running the loop.
And the increment part : It is run each time after the loop.
All together forms the 'for' loop.
So, 'for' loop is quite better compared to 'while' loop. As the lines of codes gets reduced.
The do - while loop is just like the while loop with a little difference.
This loop will execute the code block at least once, because it gets into the loop first, executes the block inside the loop. Then it checks for the conditional part i.e. while(num <=10 ).
In 'do' - 'while' loop there is no conditional statement in 'do'. So it gets into the code block.
Finally, after executing the block inside the loop, it comes to the conditional part of the loop.