Loop statements
IV. Nested Statements
We have already seen examples where one conditional statement is nested inside another. In this section, we will consider more examples of nested statements. Two of the most common examples are nested for statements and conditional statements nested inside while loops. Other combinations of nested statements also arise in practice, but if you master the two we consider here, you will be able to deal with whatever life throws at you!
A. Nested for Loops
Nested for loops occur in processing multidimensional arrays. The typical structure of such loops is shown below. If you trace this code, you will get a good idea of how nested loops work. We have deliberately kept things simple. The inner loop's body has just one statement (the output statement), and the only statement in the body of the outer loop is the inner for statement. No braces are therefore necessary in the body of either loop.
For i = 0 step 1 to 4 //outer(i)loop For j = 1 step 2 to 6 //inner(j)loop Output i, j End for //inner(j)loop End for //outer(i)loop
Trace through the code in the following example to see how nested for loops are executed.
Points to note:
· The inner loop will be executed completely (i.e., as many iterations as required) for each single iteration of the outer loop. In the example above, the inner loop executes three times ( j = 1, 3, 5). The values taken by i in the outer loop are 0, 1, 2, 3, and 4. But for each of these values of i, the inner loop executes three times. Thus the total number of lines in the output will be
5 * 3 = 15
The sequence of numbers that are output will show the values of i and j at each step.
· It is necessary to ensure that the two loops use different loop indices. What would happen if the inner loop also used i as the index ?
Here is a somewhat more complicated example that illustrates the use of nested for loops. Suppose you are asked to write a program that prints the following output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
How would you do this task? Naturally, we reject the obvious solution , which does not use any loops! You should stop here and try to do this problem on your own (give yourself plenty of time) before reading further. Then look at our solution to the problem using nested for loops .
Exercise: Before you go on, do this code analysis exercise involving nested for loops .
B. Nested Conditional Inside Loop
As an example of synthesizing code that will have a conditional statement inside a while loop, we will write a program that mimics tie breakers in tennis. If both players have won six games apiece in a set, a tie-breaker set may be played. The first player to score seven or more points, while also leading by two or more points, wins the tie-breaker set.
We will assume that the players are called A and B. Because a program can't play real tennis (yet!), you, the user, will simply tell the program who won the next point.
We solve this problem by talking our way through to the solution. Click on the Next button in the example below to see how we arrive at the final solution in a sequence of logical steps where each step builds on work done in the previous step. What we write in the first few steps is not proper pseudocode—we are slowly feeling our way to the final solution, and it is okay to be imprecise during the intermediate steps—but the final product should be precise!
https://umuc.equella.ecollege.com/file/6ceaae77-7100-45ad-bb64-de4d87f024da/1/CMIS102-1302.zip/Modules/M3-Module_3/resources/3-17%282%29/images/code1.png
https://umuc.equella.ecollege.com/file/6ceaae77-7100-45ad-bb64-de4d87f024da/1/CMIS102-1302.zip/Modules/M3-Module_3/resources/3-17%282%29/images/expl1.png
Check out the code by supplying various sequences of points won by A and B in the interactive example below. As the saying goes, the proof of the pudding is in the eating…
Exercise: Before you go on, do this code analysis exercise involving the while loop
III. Loop Statements
In programming (and in cooking!), we must often repeat certain actions until a desired condition is achieved ("stir the mixture until a smooth consistency is obtained"). To address this need, "looping statements" were created. The name arises from the flow charts of these statements, which show a loop indicating that one must go back and perform the same sequence of operations until something happens that allows one to stop.
We have one loop statement (the for statement) when the number of iterations is known in advance ("rinse your hair with water three times"). The other (the while statement) is used when this number is not known in advance ("stir until smooth").
Mastering the hows and whys of the while and for loops is an absolute necessity for all students of programming.
A. The while Loop
The diagram below will help you to understand the different components of a while loop. Be sure to trace through both the true and false paths to see how it is executed.
Points to note:
· If the loop test fails at the very beginning, none of the statements in the loop body will ever be executed. Thus, we can say that a while loop executes 0 or more times.
· The only way to break out of the loop is if the Boolean expression evaluates to false.
The while loop shown above will be written in C++ or Java as follows (we assume the Boolean expression is i <= 10):
while ( i <= 10 ) { ... }
Note that there is no End while marker, and that there is no semicolon after the closing parenthesis.
We will use Euclid's Algorithm for the greatest common divisor (GCD) of two positive integers to showcase a while loop. Of course, Euclid did not state his algorithm in exactly the terms we use below—his algorithm was couched in terms of lengths of line segments. His algorithm appears in Book 7, proposition 2 of The Elements.
The algorithm is mathematically sophisticated, and it is not obvious how or why it works, but at this level you do not have to understand the algorithm. However, you should be able to trace through it.
Notice how we have used blocks inside the if-then and the while statements. Also notice that if x is >= y initially, the if-then statement will not execute.
Now trace through the algorithm in the following example, using the values we suggest. Then try some input values of your own.
Infinite Loops
Recall that the only way to break out of a while loop is if the Boolean expression evaluates to false. If the expression never evaluates to false, then one is stuck in an infinite (i.e., never-ending) loop!
There are an infinite number of ways in which to create infinite loops using the while statement. Look at each of the following examples of infinite loops and try to understand why the loop will not terminate. Then look at our answer to confirm if your reasoning was correct.
While (true) { … anything here… } End while
i = 0 j = 0 While (i == 0) j = j + i End while
i = 0 j = 0 While (i == 0) j = i i = i + 1 i = j End while
Answer
Answer
Answer
Code Synthesis Using the while Statement
To demonstrate your mastery of the while statement, we invite you to write pseudocode to solve the problem described in detail under the "Description" tab in the interactive activity below. The problem involves determining the number of males and number of females indicated in an input string of symbols.
As in previous interactive programs, you will develop your algorithm, using pseudocode, in five phases. The tabs on the top of the interactive diagram will carefully guide you through these five phases.
Description
Test Plan
Code
Execute
Answer
The program must accept a sequence of characters typed by the user. The characters can be m, M, f, F, 0. The first two stand for "male," while the next two stand for "female" (we allow bot upper and lower case). The user types 0 in order to stop the input process. After the user has finished input (by typing 0), the program must determine the number of females and the number of males. The value '0' that was used to terminate input is called a sentinel value for obvious reasons.
B. The for Loop (a counter-controlled loop)
Study the diagram in the example below to understand all the components of a for loop and trace both the true and false paths to see how it is executed. It will help to remember that the words for, step, and to are all keywords, whereas counter is a variable. initial_value, increment, and limit_value can be either plain integers or even arithmetic expressions (involving variables) that evaluate to integers.
The for loop is used when we know in advance the number of iterations. A typical use of for loops is to process arrays whose dimensions are known in advance (we will study arrays in module 5).
Points to note:
· If the test condition fails initially, all the statements in the loop are skipped (study the flow chart).
· The variable counter used in the loop is sometimes called a loop index. It is usually a variable of type int.
· The index variable is incremented by the same amount each time.
· If the initial value is larger than the final value and a negative increment is used, the loop works as a "down counter."
· It is extremely important to realize that the action of updating the value of the index variable (just before the next iteration) is not a part of the actual loop body!! It is an automatic action that the compiler attends to. The programmer should not be writing any code to update the value of the counter (we discuss this concept below).
· Do not change any of the components—the loop index, the initial value, the increment, or the limit_value—of the for loop within the loop body.
Here is a simple example of a for loop that reads in an input number n and evaluates the sum of the first n numbers: 1 + 2 + 3 + … + n.
/* Pseudocode to sum 1 + 2 + ... + n */
Input n
Set sum = 0
//no braces used since the loop body is just 1 statement For i = 1 step 1 to n Set sum = sum + i End for
Output sum
Here, the loop index variable is called i, initial_value is 0, the increment is 1, and limit_value is n. Note that the loop body contains a statement of the form sum = sum + i (i.e., add the current value of i to the current value of sum, and place the result in sum). It is important to ensure that the variable sum is initialized correctly, so that the additions are performed correctly.
The for statement shown above would be written in C++ or Java as follows:
for (i = 1 ; i <= n ; i = i + 1) sum = sum + i ;
You should trace through the code in the following example using the values of n we suggest: 1, 4, and the special case of 0.
Points to note:
· In pseudocode, the initial, increment, and final values are simply stated as values, whereas in C++ or Java, they are written as complete expressions separated by semicolons.
· Note the semicolon at the end of the entire for statement.
· In pseudocode, the limit value is written last, whereas in C++ or Java, the expression that increments the counter appears last.
· In C++ or Java, i++ is a shorthand for i = i + 1, and the shorthand notation is widely used.
Test your skills in using for loops on the following pseudocode programming problem described in detail under the "Description" tab in the interactive activity below. Your task is to write a program that finds the sum of a sequence of numbers (floats). The user will first specify a number (integer) that specifies how many floats will be given, and the remaining inputs will specify the floats that need to be added together.
While doing this exercise, note that the loop body has more than one statement, which is why we have used braces.
You will develop your algorithm, using pseudocode, in five phases. The tabs on the top of the interactive diagram will carefully guide you through these five phases.
Description
Test Plan
Code
Execute
Answer
Test your skills in using for loops on the following psuedocode programming problem. Your task is to write a program that finds the sum of a sequence of numbers (floats). You will first specify a number (integer >= 0) that specifies how many floats will be given, and the remaining inputs will specify the floats (positive or negative) that need to be added together.