dcsimg
October 17, 2017
Hot Topics:

Using Different Types of Java Loops: Looping in Java

  • September 18, 2017
  • By Manoj Debnath
  • Send Email »
  • More Articles »

The first stumbling block when we start learning any programming language is the concept of loops. Adding to the confusion, they are of various types. Loops are basically control statements. And, control statements provide the way to maneuver the flow of the program into different directions that are linear otherwise. A loop is a type of control statement which encircles the flow for a while—something like the vortexes in a river stream. This article describes the concept behind looping in Java and the various types of loops.

Looping in Java

Java provides three repetition statements/looping statements that enable programmers to control the flow of execution by repetitively performing a set of statements as long as the continuation condition remains true. These three looping statements are called for, while, and do...while statements. The for and while statements perform the repetition declared in their body zero or more times. If the loop continuation condition is false, it stops execution. The do...while loop is slightly different in the sense that it executes the statements within its body for one or more times.

There is a common structure of all types of loops, such as:

  • There is a control variable, called the loop counter.
  • The control variable must be initialized; in other words, it must have an initial value.
  • The increment/decrement of the control variable, which is modified each time the iteration of the loop occurs.
  • The loop condition that determines if the looping should continue or the program should break from it.

The variation in different types of loop structure is nothing but syntactic variations. We easily can replace one type of loop with another and still get the same result. The differences in them, I believe, are more of a choice when we look at the essence of it. But, when we look deeper, the subtle difference become pronounced, especially when we compare do...while with for and while loops. Let us take them, one by one, into account and investigate their working process.

The Java Loop: while

The while loop allows us to specify that a certain statement is to be executed repetitively until the loop condition is false. Consider a problem to print ten consecutive numbers from 1 to 10. What we do is initialize a control variable outside the while loop construct, state a condition for loop continuation, and then increment the control variable so that at some point of the iteration the condition become false and breaks out of the repetition.

Executing a while loop
Figure 1: Executing a while loop

int counter = 1;   // Control variable initialized

// Condition for loop continuation
while (counter <= 10) {
   System.out.println(counter);
   counter++;     // Increment the control variable
}

At first, the program control finds the variable named counter, initialized to 1. Then, on first encounter with the condition defined in the while loop, it evaluates to true because the value contained in the counter variable is 1, which is certainly less than ten. It than enters into the while body and executes the statement(s) inside the loop body, increments the counter to the next value and rebounds back to the while condition again. This time, the counter has value 2, which again is less than 10. The condition is evaluated to true; therefore, it enters into the while body, executes the statements, increments the counter to its next value, and so on. At some point in the iteration, the value of the counter will be 11, which is definitely greater than 10; the loop condition evaluates to false and breaks out.

The loop repetitively executes the System.out.println(...) statement as long as the condition statement counter<=10 evaluates to a Boolean true value. This means that if we write:

// Never-ending loop or infinite loop
while (true) {   // Condition is always true
   // ... Some statements
}

The loop condition has no reason to stop. Neither has the following code any reason to stop.

int counter = 1;   // Control variable initialized

// Condition always evaluates to true
while (counter <= 10) {
   System.out.println(counter);
   counter--;      // Decrements the control variable
}

These are typical examples of never-ending or infinite loops. It is a programmer's responsibility to ensure that a loop eventually become false so that it stops; otherwise, the loop body will execute forever—or at least till the program is interrupted. Infinite loops are often common mistakes in a program.

Note: If such a situation occurs where a program executes infinitely, use a keyboard interrupt, such as Ctrl+C; this will terminate the running program.

Now, if we start the loop with a false condition:

// The loop body will never execute
while (false) {    // Condition is always false
   System.out.println("This will never print");
}

The statements inside the loop body will not get a chance to execute because the control will never enter the loop.

The Java Loop: for

The working process of a for loop is similar to the while loop, only the structure is different. Unlike the while loop, the layout of the control variable, loop condition, and the increment of the control statement can be stated in a single line of code, such as in the following example.

Executing a for loop
Figure 2: Executing a for loop

// For(<initialization>;<condition>;<increment>
for(int counter = 1; counter <= 10; counter++){
   System.out.println(counter);
}

Some variations in writing using a for loop are as follows:

int counter;
for( counter = 1; counter <= 10; counter++){
   //... Statements
}

int counter = 1;
for(; counter <= 10; counter++){
   //... Statements
}

int counter = 1;
for(; counter <= 10;){
   //... Statements
   counter++;
}

// Infinite loop
for(;true;);

Observe that, in some of the for loop structures, the initialization expression is declared outside the header and in some it is declared inside the for header. The difference is that if the control variable is declared inside the initialization section of the for loop, that variable is scoped within the for loop only. It will not exist outside it. However, when the control variable is declared outside for loop header it is scoped both inside and outside the for loop block.

Comparing Java Loops: for and while

Both the for and while loops are entry controlled; in other words, they first check the truth value of the condition and then only enter into the loop. There is certain point of dissimilarities in them, such as this:

// Infinite loop
for(;;);

This statement is completely valid and means an infinite loop, whereas

// Syntax error
while();

is a syntax error. Having said all this, there is no reason to favour or disfavour while for the for or for for the while in programming. Perhaps the problem of choice may be solved by choosing one. But, if one is really looking for a loop that does not check any sort of validity at its entry, the construct described next is for your consideration.

The Java Loop: do...while

This is an exit controlled looping structure which is different from, yet somewhat similar to, the while statement in the sense that the structure of the loop described, such as initialization of the control variable, is declared outside the loop header, the increment/decrement is written within the body of the loop like any other statements.

Executing a do...while loop
Figure 3: Executing a do...while loop

int counter = 1;   // Control variable initialized

do{
   System.out.println(counter);
   counter--;   // Decrements the control variable
}while(counter <= 10);   // Condition statement

The significant difference that sets the do...while loop apart from both while and for loop is that the for and while loops are meant to execute zero or more times. This means there is a chance that the loop may not execute at all if the condition is false. The do...while loop, on the other hand, executes at least once or, in other words, one or more times because it never checks any condition during its entry; rather, it evaluates the loop continuation condition statement only at the exit. This makes the body of the loop execute at least once.

Comparing Java Loops: while and do...while

It is not compulsory to use braces with the do...while loop statement if there is only one statement in the body. Similar is the case with the while loop. However, it is recommended to use braces with the do...while statement to avoid confusion with the while statement. For example,

while(counter++ <= 10);

or

while(counter <= 10)
   counter++;

This is a completely valid statement. The same can be written with a do...while loop.

do System.out.print("");
   while(counter++ <= 10);

or

do counter++; while(counter <= 10);

Now, observe the while part of both the while loop and do...while loop. They look the same. This may confuse the reader and cause them to misinterpret it. Therefore, it is recommended that the do...while statement be written with braces even if there is only one statement in the body.

do {
   counter++;
}while(counter <= 10);

This leverages the readability of the code and eliminates ambiguity between the while and do...while statements when they a contain single statement in the body.

Conclusion

This concludes the story of loops, By the way, there is another variation of the for loop introduced in Java which is not covered here. The idea is that once the three basic types of loops are understood, the rest is a cakewalk. Things get a little messy when we go into nested loops, meaning one loop declared inside another. They make a hierarchy or tree structure when elaborated on a piece of paper. Maybe we'll cover that concept later.






Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Thanks for your registration, follow us on our social networks to keep up-to-date
Rocket Fuel