Programs with Repetition Logic
In this chapter, we will explain the following:
• How to use the while construct to perform “looping” in a program
• How to find the sum and average of an arbitrary set of numbers
• How to get a program to “count”
• How to find the largest and smallest of an arbitrary set of numbers
• How to read data from a file
• How to write output to a file
• How to use the for construct to perform “looping” in a program
• How to produce tables using for
and so on. We want to let the user enter as many numbers as he wishes. Since we can have no idea how many that will be, and the amount could vary from one run of the program to the next, we must let the user “tell” us when he wishes to stop entering numbers.
How does he “tell” us? Well, the only time the user “talks” to the program is when he types a number in response to the prompt. If he wishes to stop entering numbers, he can enter some
“agreed-upon” value; when the program reads this value, it will know that the user wishes to stop.
In this example, we can use 0 as the value that tells the program that the user wishes to stop.
When a value is used this way, it is referred to as a sentinel or end-of-data value. It is sometimes called a rogue value—the value is not to be taken as one of the actual data values.
What can we use as a sentinel value? Any value that cannot be confused with an actual data value would be okay. For example, if the data values are all positive numbers, we can use 0 or −1 as the sentinel value. When we prompt the user, it is a good idea to remind him what value to use as the sentinel value.
Assume we want the program to run as follows:
Enter a number (0 to end): 24 Enter a number (0 to end): 13 Enter a number (0 to end): 55 Enter a number (0 to end): 32 Enter a number (0 to end): 19 Enter a number (0 to end): 0 The sum is 143
How do we get the program to run like that? We want to be able to express the following logic in a form the computer could understand:
As long as the user does not enter 0, keep prompting him for another number and add it to the sum
It seems obvious that we must, at least, prompt him for the first number. If this number is 0, we must print the sum (which, of course, would be 0 at this time). If the number is not 0, we must add it to the sum and prompt for another number. If this number is 0, we must print the sum. If this number is not 0, we must add it to the sum and prompt for another number. If this number is 0..., and so on.
The process will come to an end when the user enters 0.
This logic is expressed quite neatly using a while construct (also called a while statement or while loop):
//Algorithm for finding sum set sum to 0
get a number, num while num is not 0 do add num to sum
get another number, num endwhile
print sum
Note, particularly, that we get a number before we enter the while loop. This is to ensure that the while condition makes sense the first time. (It would not make sense if num had no value.)
To find the sum, we need to:
• Choose a variable to hold the sum; we will use sum.
• Initialize sum to 0 (before the while loop).
• Add a number to sum (inside the while loop). One number is added each time through the loop.
On exit from the loop, sum contains the sum of all the numbers entered.
The while construct lets us execute one or more statements repeatedly as long as some condition is true. Here, the two statements
add num to sum
get another number, num
are executed repeatedly as long as the condition num is not 0 is true.
In pseudocode, the while construct is usually written as follows:
while <condition> do
statements to be executed repeatedly endwhile
The statements to be executed repeatedly are called the body of the while construct (or, simply, the body of the loop). The construct is executed as follows:
1. <condition> is tested.
2. If true, the body is executed and we go back to step 1; if false, we continue with the statement, if any, after endwhile.
We now show how the algorithm is executed using the sample data entered above. For easy reference, the data was entered in the following order:
24 13 55 32 19 0
Initially, num is undefined and sum is 0. We show this as follows:
sum 0
num
24 is entered and stored in num;
num is not 0 so we enter the while loop;
num (24) is added to sum (0), giving:
num 24 sum 24
13 is entered and stored in num;
num is not 0 so we enter the while loop;
num (13) is added to sum (24), giving:
num 13 sum 37
55 is entered and stored in num;
num is not 0 so we enter the while loop;
num (55) is added to sum (37), giving:
num 55 sum 92
32 is entered and stored in num;
num is not 0 so we enter the while loop;
num (32) is added to sum (92), giving:
num 32 sum 124
19 is entered and stored in num;
num is not 0 so we enter the while loop;
num (19) is added to sum (124), giving:
num 19 sum 143
0 is entered and stored in num;
num is 0 so we exit the while loop and go to print sum with
num 0 sum 143
sum is now 143 so the algorithm prints 143.
When a while construct is being executed, we say the program is looping or the while loop is being executed.
It remains to show how to express this algorithm in C. Program P5.1 shows how.
Program P5.1
//print the sum of several numbers entered by a user
#include <stdio.h>
int main() {
int num, sum = 0;
printf("Enter a number (0 to end): ");
scanf("%d", &num);
while (num != 0) { sum = sum + num;
printf("Enter a number (0 to end): ");
scanf("%d", &num);
}
printf("\nThe sum is %d\n", sum);
}
Of particular interest is the while statement. The pseudocode while num is not 0 do
add num to sum
get another number, num endwhile
is expressed in C as while (num != 0) { sum = sum + num;
printf("Enter a number (0 to end): ");
scanf("%d", &num);
}
When the program is run, what would happen if the very first number entered was 0? Since num is 0, the while condition is immediately false so we drop out of the while loop and continue with the printf statement. The program will print the correct answer:
The sum is 0
In general, if the while condition is false the first time it is tested, the body is not executed at all.
Formally, the while construct in C is defined as follows:
while (<condition>) <statement>
The word while and the brackets are required. You must supply <condition> and
<statement>. <statement> must be a single statement or a block—one or more statements enclosed by { and }. First, <condition> is tested; if true, <statement> is executed and
<condition> is tested again. This is repeated until <condition> becomes false; when this
happens, execution continues with the statement, if any, after <statement>. If <condition> is false the first time, <statement> is not executed and execution continues with the following statement, if any.
In Program P5.1, <condition> is num != 0 and <statement> is the block {
sum = sum + num;
printf("Enter a number (0 to end): ");
scanf("%d", &num);
}
Whenever we want to execute several statements if <condition> is true, we must enclose the statements by { and }. Effectively, this makes them into one statement, a compound statement, satisfying C’s syntax rule that requires one statement as the body.
5.2.1 Highest Common Factor
Let us write a program to find the highest common factor, HCF (also called the greatest common divisor, GCD), of two numbers. The program will run as follows:
Enter two numbers: 42 24 Their HCF is 6
We will use Euclid’s algorithm for finding the HCF of two integers, m and n. The algorithm is as follows:
1. if n is 0, the HCF is m and stop
2. set r to the remainder when m is divided by n 3. set m to n
4. set n to r 5. go to step 1
Using m as 42 and n as 24, step through the algorithm and verify that it gives the correct answer, 6.
Steps 2, 3, and 4 are executed as long as n is not 0. Hence, this algorithm can be expressed using a while loop as follows:
while n is not 0 do set r to m % n set m to n set n to r endwhile HCF is m
We can now write Program P5.2, which finds the HCF of two numbers entered.
Program P5.2
//find the HCF of two numbers entered by a user
#include <stdio.h>
int main() { int m, n, r;
printf("Enter two numbers: ");
scanf("%d %d", &m, &n);
while (n != 0) { r = m % n;
m = n;
n = r;
}
printf("\nTheir HCF is %d\n", m);
}
Note that the while condition is n != 0 and the while body is the block {
r = m % n;
m = n;
n = r;
}
The algorithm and, hence, the program, works whether m is bigger than n or not. Using the example above, if m is 24 and n is 42, when the loop is executed the first time, it will set m to 42 and n to 24. In general, if m is smaller than n, the first thing the algorithm does is swap their values.