Home > Using loop constructs > Using loop constructs in Java

Using loop constructs in Java

 

Module 2: Using loop constructs:

 

Objectives:

  • Create while loops.
  • Develop for loops.
  • Create do / while loops.

 

 

1. Create while loops:

The while loop is used to execute a set of code for multiple times as long as a condition is true. Once the condition becomes false, the code block is no longer executed and the control exits the while loop and continues with the execution of rest of the program.

 

 Create while loops

We can see the syntax for the while loop in the syntax figure above. We begin with the keyword while, and then we put a boolean expression inside a set of paranthesis. If this boolean expression is true, we execute the code block between the left and the right curly braces. If the boolean expression is false, then we do not execute the code block and we leave the while loop. This code block will be executed as many number of times as long as the boolean expression continues to be true.

This is illustrated in a flow chart to the right. The boolean expression is tested for true / false. If true, then we execute the code block, and you can also see that we return back to again test the boolean expression after executing the code block, and again the expression will be tested for true / false. As long as the boolean expression continues to be true, the flow will be the same. Once the expression evaluates to false, the code block will no longer be executed and the control leaves the while loop.

 

While loop example:

Let’s take a look at an example of while loop. As you can see from the figure below, we have a while loop that is checking if the variable i is less than 5. If it is, we will enter the code block, and we will print out “Hello Thomas” to the command prompt / console. And then we are incrementing the i variable by 1. We will then again go back to the while loop condition and check if the i variable is still less than 5. As long as it is, we will continue to print to the console and continue to increment i and continue back to the while loop condition. Once its not, we will leave the while loop and continue with the rest of the program. Let’s see this for 2 different values of i.

 

For i = 0: 

 While loop example

 

When i = 0, the while condition is true for the first time, and we enter the loop and print “Hello Thomas” to the console, increment i by 1 because of which it becomes 1, and again go back to the while loop condition and check it again. Here i is 1 and still less than 5 so the whole loop is repeated for 5 times until i < 5 and “Hello Thomas” is printed 5 times to the console. Once i is 5, i < 5 will be false so it will exit the while loop and continue with the execution of the rest of the program.

 

For i = 5:

 While loop example 1

 

 

When i = 5, we check the while loop condition first, which is i < 5, as we have i as 5, we get this condition to be false. Hence we wont enter the code block, hence not printing anything to the console and continue with the execution of rest of the program.

 

Nested while loops:

Just like you can have nested if – else statements, similarly you can have nested while loops. In this example we will print a rectangle of “@” symbols to the command prompt.

 

 Nested while loops

 

Here in this example, the outer while loop controls the row, which can be specified by using a variable height, we have another while loop nested inside, and apart from that we have a system.out.println() line which justs ends the row and takes to the next line, we then increment the variable rowCount which we use for controlling the outer while loop. The inner while loop is responsible for printing out the “@” character one at a time. So it prints out “@” for each row for specified number of times by the width variable.

We can see that as and when we are entering the code block, apart from executing the logic that we want to, we are also incrementing a variable which we are using in the while loop condition. This incrementing / decrementing based on the need, is necessary to loop the code block for a required number of times.

 

 

2. Develop for loops: 

The for loop is used when you know how many times you want to execute the code block. For instance, if you want to execute a code block 10 times. The for loop is used at places where while loop cant be used. A while loop can be used when you are unsure of how many times you want to execute the loop for,  but have a flag to end the loop. For instance, if you query a database you might not know how many records of data will be returned to you but you want to loop through all of them. So a while loop is used for such situations.

 

Develop for loops

 

We use the keyword for, and then we have 3 pieces of information that we give to the for loop. First is our initialization, this is where we can declare a counter variable and initialize it. This is the variable that will keep track of how many times we have executed the loop. The next information is a boolean expression which will decide whether we have to execute the for loop or leave it. If the boolean expression evaluates to true, then the code block is executed else the code block is not executed. The last piece of information is the update statement which updates the counter variable. And then finally in the curly braces we give the code block that we want to be executed multiple times.

The for loop is also illustrated in the flow chart to the right. As you can see the first thing we do is initialize our variables, that is declaring the counter variable and intialize it a starting value. The next thing we do is test the boolean expression, if the boolean expression is true we will execute the code block, and then we will issue the update statement that will update the counter variable. We then go back again to the boolean expression to see if it is still true. If it is, we repeat the same steps as above. This will continue until the boolean expression evaluates to false. And then we will leave the loop and continue with the execution of rest of the program.

 

For loop example:

Now that we know about the for loop, its syntax and the situations it can be used in, let’s take a look at an example. We have taken the same while loop example and converted into for loop. First we use the keyword for, and then in the paranthesis we declare and intialize our counter variable, and then give the boolean expression that will decide to continue to loop or not to, and an update statement to update the counter variable, and a pair of  curly braces containing the code block that needs to be looped. Let’s consider this for 2 values of the counter variable.

 

For i = 0:

 

 For loop example

 

Here, our i variable will be keeping the count and is starting at 0. We then have our boolean expression i < 5, and as i is 0, the loop will continue to execute until i becomes 5. Once its not we will leave the loop. And the last thing is the update statement,  which is incrementing  the i variable by 1. So each time through the loop, this update statement here is incrementing i by 1. Here the update statement can be any update to the counter variable, either increment, or decrement or a more sophisticated statement such as i = i+ 2 or any equation. Then we have the code block in the curly braces which in our case wants to print “Hello Thomas” to the console 5 times. This flow is also illustrated in the flow chart.

 

For i = 5:

 

  For loop example 1

Here, our i variable will be keeping the count and is starting at 5. We then have our boolean expression i < 5, and as i is 5, the loop will not execute as the boolean expression returns false. So we will leave the for loop and not execute anything in the code block and hence we dont get anything printed to the command window. This flow is also illustrated in the flow chart.

 

Nested for loops:

You can nest one looping statement in an another looping statement. We have seen this wtih while loop. And we will consider the same nested while loop example and convert it to nested for loop. Just like with the while loop, the outer for loop here control the rows, it moves us from one row to the next, by using system.out.println() by just appending an end of line character at the end of each row. The inner for loop is responsible for printing “@” symbol one at a time for specified number of times.

 

  Nested for loops

 

   

 

 

3. Create do / while loops:

Another looping construct in Java is the do / while loop. This is very similar to the while loop. But with the while loop you are not guaranteed that the code block in your while loop will execute atleast one time. With the do / while you are guaranteed that it will execute atleast once. This is because in the do / while loop, the test for the boolean expression is done at the end of the loop, and not at the beginning. Let’s take a look at the syntax.

 

 Create do - while loops 

 

We start with a keyword do, and then we have our left and right curly braces with the code block in it, this is the code that will be executed atleast once or multiple number of times. After the code block, we have our while statement, and in the paranthesis we have the boolean expression which will be tested. And lastly we have a semicolon (;). If the boolean expression evaluates to true, we will loop again through the code block, if false we will exit the do / while loop and continue the execution with the rest of the program.

This is illustrated in the flow chart below. As we can see, there is no testing the boolean expression first as with while loop, but the code block is executed and then test the boolean expression for true or false. If true, we again execute the code block and again test the expression, this will continue as long as the boolean expression is true, else exit the do / while  loop. Certain situations do need the code block to be executed atleast once before looping, in such situations do / while loop is used. In situations when the code block has to be executed only when the condition is satisfied, is when the while loop is used.

 

Nested do / while loops:

Just like with the for loops and the while loops, even the do / while loops can be nested. Once again we have taken the same example from before, and converted it to use do / while nested loops. As with before, the outer do / while loop controls the row, it moves us from one row to the next, and the inner do / while loop as before prints “@” symbol one at a time across the row for specified number of times.

  Nested do - while loops

 

 You have to know, that each time the outer loop executes, the inner loop completes its looping and only when it exits is when the outer loop continues with other statements in the code block.

 

Comparing looping constructs:

Let’s review the looping constructs that we have learnt in this module and when its best to use them.

 

Comparing looping constructs

 

while loop:

  • The while loop is best used when you want zero or more iterations of the code block and the total iterations are unknown.
  • The boolean expression is tested first, if it evaluates to true the code block is executed, and then the boolean expression is re-tested. Once the boolean expression evaluates to false, the while loop exits.

do / while loop:

  • The do / while loop is best used when you need atleast one iteration of your code block and also when the total iterations are unknown.
  • The code block is executed immediately and then the boolean expression is evaluated. If it evaluates to true, the code block is executed again, and the boolean expression is re-tested. Once the boolean expression evaluates to false, the do / while loop exits.

for loop:

  • The for loop can be used with any number of iterations, zero one or many, and best used when the total iterations are known.
  • The counter variables are first initialized, then the boolean expression is tested, if it evaluates to true the code block is executed and the counter variables are updated. The boolean expression is re-tested, and if it evaluates to false, the for loop is exited.

 

 

 

Note:

 

Source: Sun Microsystems Educational Services Course – Using Decision and Looping Constructs with the Java Programming Language WJ-1103A.

 

 

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: