Menu
Topics Index
...
`


Control Statements > Iteration statements (Loops) >
Siva Nookala - 11 Apr 2016
Java's Iteration statements are for, while and do-while. These statements are commonly called as loops. A loop repeatedly executes the same set of instructions until a termination condition is met.

For example, if we want to print Hello for 10 times, we need to call the print statement 10 times. This could be achieved by explicitly calling print statement 10 times as shown below.
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
Although this approach works, it has the following disadvantages.
  • It is very time consuming, inefficient, error prone and has lots of duplicate code.
  • If we want print Hello World instead of Hello, we have to change all the ten lines.
  • If we want print 100 lines more or 1000 lines more, we have to add so many more lines. It is very time consuming to do it.
  • What if the the number of lines to be printed is given by the user and we do not know the value until the program runs. If user wants 7 lines, we should print 7, if he wants 12 we should print 12.
The alternative approach is to use loops which will take care of all the disadvantages mentioned above.
As discussed earlier for any loop, there is loop body consisting of set of instructions and there is termination condition. As long as the termination condition is true, the loop body is executed. When the condition is false, loop stops.
Since we want to call print 10 times, we want a termination condition which is true for ten times, but false after that. Such termination condition can be defined using a variable counter which is initialized to 1 and the condition is counter <= 10. We will increment the counter by 1 after every execution of loop body. So as long as the counter is less than or equal to 10, i.e. for values 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10, the loop body executes. When the counter becomes 11, the loop is terminated.

Although, the three loops while, do-while and for, work using the above methodology, there are differences in the syntax. The links provided give the exact details of the syntax and how to use them.
  • while Loop In Java is a statement which executes a block of statements as long as the condition is satisfied.
  • do while Loop In Java is executes the block of statements at least once before it checks for the condition.

Dependent Topics : Control Statements In Java 

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.