Lesson 7 - While Loops
7.1 While loop
// ex7-1.cpp - While loop
#include <iostream>
using namespace std;
int main()
{
cout << "Enter a number : ";
int ival;
cin >> ival;
while (ival > 0) {
cout << ival << "/2=" << ival/2 << endl;
ival = ival/2;
}
return(0);
}
|
ex7-1
Enter a number : 10
10/2=5
5/2=2
2/2=1
|
Example ex7-1 introduces a C++ facility for repetitive execution
of statements. The 'while' statement accepts a condition and a block
of statements and repetitively executes the block of statements for as
long as the condition evaluates as true. The syntax of the while
statement is:
while (condition) {
statement;
statement;
...
}
The 'condition' is a conditional expression as was seen in
the 'if' statement. It consists of test on the contents of variables
with comparison operators, combining operators, negation, and parentheses.
In the example, the while statement controls two statements: the first
prints out the value of 'ival' and 'ival/2', while the second reduces the
size of ival by 2. The condition part on the while
loop tests to see if the contents of ival is greater than zero. Thus
the two controlled statements will be executed over and over again until
such time as ival becomes less or equal to zero. When the value 10
is entered, the contents of ival are set to 10, and since this is greater
than zero, the while statement executes the two controlled statements.
The result of this is that ival is reduced by 2 to the value 5; since this
value is still greater than zero, the statements are executed again.
This time different values are printed and ival is reduced to 2.
The while loop runs again so that ival becomes 1, then finally ival is
set to half of 1, which is zero because we are dealing with integer variables.
The condition is no longer true, the while loop stops, and the statement
after the end of the while loop is executed next.
Note the danger of while loops: if the condition never becomes false
then the program executes indefinitely. We say that the program is
'hanging'. To stop a hung program, we need to type [ctrl/break],
or select option 'Stop execution' in the Scite editor. |
7.2 While loop with prompt
// ex7-2.cpp - While loop with prompt
#include <iostream>
using namespace std;
int main()
{
cout << "Enter a number (0 to end) : ";
int ival;
cin >> ival;
int sum=0;
while (ival != 0) {
sum = sum + ival;
cout << "Enter a number (0 to end) : ";
cin >> ival;
}
cout << "Sum=" << sum << endl;
return(0);
}
|
ex7-2
Enter a number (0 to end) : 5
Enter a number (0 to end) : 7
Enter a number (0 to end) : 3
Enter a number (0 to end) : 0
Sum=15
|
Example ex7-2 shows how a while loop can be used to read a series of values
from the keyboard, where the number of values is not known in advance.
The trick is to specify a particular value as a terminating value, or 'sentinel'
value. In this example, it is the value 0. Since the point
of the program is to sum a series of numbers, it isn't likely or useful
for users to want to enter the number 0 as part of a sum. Thus 0
makes a good terminating value in this case. The program asks the
user to enter a number, reminding them that 0 will end the input.
The first number is then input into the variable ival. Then the while
statement tests the value of ival, and executes a block of statements while
ival is not equal to zero. The block of statements updates
a variable 'sum' with the value input, prompts the user for
another number, and reads the next value into ival. |
7.3 While loop processing a string
// ex7-3.cpp - While loop processing a string
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Enter a string of words : ";
string sval;
getline(cin,sval);
int cnt=1;
int nsep = sval.find(" ");
while (nsep > 0) {
cout << "Word " << cnt << "="
<< sval.substr(0,nsep) << endl;
cnt = cnt + 1;
sval = sval.substr(nsep+1);
nsep = sval.find(" ");
}
cout << "Word " << cnt << "=" << sval << endl;
return(0);
}
|
ex7-3
Enter a string of words : Once upon a time.
Word 1=Once
Word 2=upon
Word 3=a
Word 4=time.
|
Example ex7-3 is a further demonstration of a while loop. In this
example we use a loop to process each of the individual words in a string
of characters. The example uses the getline() function to input into
the variable 'sval' a string consisting of all characters entered up to
the end-of-line key. To split the string up into words, we use the
'find()' method of the string object type to search for the first occurrence
of a space character, storing this index into the variable 'nsep'.
If find() finds a space, then the first word is printed out and then removed
from the beginning of the string with the substr() method. When
find() fails to find a match it returns -1.
The loop continues until it fails to find a word of at least one character:
the condition (nsep >0) will be false if the first character of the string
is a space, or if no space is found. Note that for a four word sentence,
only three spaces are found. To process the last word, an additional,
final print statement is required. |
7.4 Exercises
a. Write a program (average.cpp)
that inputs a series of values and outputs their average. Use the
value -1 as a terminating value, as in:
average
Enter value (-1 to stop) : 3
Enter value (-1 to stop) : 5
Enter value (-1 to stop) : 1
Enter value (-1 to stop) : 1
Enter value (-1 to stop) : -1
Average=2.5
Test that your program can calculate the average of an empty list of numbers!
b. Write a program (minmax.cpp) that inputs
a series of values and reports the largest and the smallest. Use
the value -1 as a terminating value, as in:
minmax
Enter value (-1 to stop) : 13
Enter value (-1 to stop) : 25
Enter value (-1 to stop) : 10
Enter value (-1 to stop) : 14
Enter value (-1 to stop) : -1
Smallest=10, Largest=25
|