while Loops

Problem:  The weather service has contracted you to write the program that will convert their daily Fahrenheit temperature readings into Celsius readings.   Readings are taken every four hours.  At the end of each day, the average daily temperature is calculated.  Print the results of each conversion and the daily average.

#include <iostream>

using namespace std;

int

main()

{

float temp;

float averagetempsum = 0, averagedaily;

float celsius;

cout << "Please enter a temperature: ";

cin >> temp;

averagetempsum += temp;

celsius = 5.0/9.0*(temp - 32);

cout << temp << " degrees fahrenheit is "

<< celsius << " degrees celsius." << endl << endl;

cout << "Please enter a temperature: ";

cin >> temp;

averagetempsum += temp;

celsius = 5.0/9.0*(temp - 32);

cout << temp << " degrees fahrenheit is "

<< celsius << " degrees celsius." << endl << endl;

cout << "Please enter a temperature: ";

cin >> temp;

averagetempsum += temp;

celsius = 5.0/9.0*(temp - 32);

cout << temp << " degrees fahrenheit is "

<< celsius << " degrees celsius." << endl << endl;

cout << "Please enter a temperature: ";

cin >> temp;

averagetempsum += temp;

celsius = 5.0/9.0*(temp - 32);

cout << temp << " degrees fahrenheit is "

<< celsius << " degrees celsius." << endl << endl;

cout << "Please enter a temperature: ";

cin >> temp;

averagetempsum += temp;

celsius = 5.0/9.0*(temp - 32);

cout << temp << " degrees fahrenheit is "

<< celsius << " degrees celsius." << endl << endl;

cout << "Please enter a temperature: ";

cin >> temp;

averagetempsum += temp;

celsius = 5.0/9.0*(temp - 32);

cout << temp << " degrees fahrenheit is "

<< celsius << " degrees celsius." << endl << endl;

averagedaily = averagetempsum / 6;

cout << "The average daily temperature is:  " << averagedaily << endl;

return 0;

}

New Problem:  The weather service was so pleased with the way that you handled the previous problem, they want you to write a program that will handle the yearly average temperatures.   Temperature readings are still done every 4 hours.

This would mean we would have to copy our code, 6 X 365 or 2,190 times!!  There has got to be a better way.

Repetition statements allow us to repeat a statement or set of statements multiple times.  There are several types of repetition statements which are sometimes known as loops.

while Loop:

while (condition)

statement;

while (condidition)

{

stmt1;

stmt2;

stmt3;

.

.

stmstn;

}

The statement or statements are repeated as long as the condition remains true.  The condition is tested before each execution of loop statements.

The type of while loop which is best suited for our problem is a counter controlled loop.  A counter controlled loop uses a variable to keep track of the number of times the loop executes.  This variable is called the loop control variable.

#include <iostream>

using namespace std;

int

main()

{

float temp;

float averagetempsum = 0, averagedaily;

float celsius;

int count;

count = 0;

while (count < 6)

{

cout << "Please enter a temperature: ";

cin >> temp;

averagetempsum += temp;

celsius = 5.0/9.0*(temp - 32);

cout << temp << " degrees fahrenheit is "

<< celsius << " degrees celsius." << endl << endl;

count ++;

}

averagedaily = averagetempsum / 6;

cout << "The average daily temperature is:  " << averagedaily << endl;

return 0;

}

Here count is the loop control variable.

Loop control variable is a variable whose value determines whether the loop body is executed.  The loop body consists of all the statements within the curly brackets of a loop.   An iteration is a single loop repetition.

More examples of counter controlled loops.

#include <iostream>

#include <iomanip>

using namespace std;

int

main()

{

int n, count;

count = 0;

n = 7;

while (count < 4)

{

cout << setw(n) << "* * * *" << endl <<endl;

++n;

++count;

}

return 0;

}

* * * *

* * * *

* * * *

* * * *

Press any key to continue

#include <iostream>

#include <iomanip>

using namespace std;

int

main()

{

int n, count;

count = 0;

n = 1;

while (count <= 9)

{

cout << setw(n) << n -1 << endl;

++n;

++count;

}

return 0;

}

0

1

2

3

4

5

6

7

8

9

Press any key to continue

Fixed step loop (step controlled loop) - loop control variable takes values in increment or decrement step order.  The exit condition is based on this variable attaining a certain value.

Problem:  Write a code fragment that prints all the even numbers between 0 and a given positive number, inclusive.  We also wish to sum these numbers.

cout << "Please enter a positive number:  ";

cin >> num;

count = 0;

sum = 0;

while (count <= num)

{

cout << count << endl;

sum += count;

count += 2;

}

cout << "The sum of the numbers is:  " << sum << endl;

A careless CSC126 student (from one of the other sections) typed in the following, never updating count.  What happens upon execution?

cout << "Please enter a positive number:  ";

cin >> num;

count = 0;

sum = 0;

while (count <= num)

{

cout << count << endl;

sum += count;

}

cout << "The sum of the numbers is:  " << sum << endl;

This is known as an infinite loop.

cout << "Please enter a positive number:  ";

cin >> num;

count = 0;

sum = 0;

while (count <= num)

{

sum += count;

}

cout << "The sum of the numbers is:  " << sum << endl;

You would only see the cursor blinking.  This is a silent infinite loop.

Interactive while Loop

Temperature revisited:

Keep converting from Fahrenheit to Celsius until user tells you to stop.

#include <iostream.h>

int

main()

{

int fah, cels;

char ans;

ans = 'y';

while (ans == 'y' || ans == 'Y')

{

cout << "Please enter a Fahrenheit temperature: ";

cin >> fah;

cels = 5.0 * ( fah - 32) / 9.0;

cout << fah << " in Celsius is " << cels << endl;

cout << "Would you like to enter another number? y/n ";

cin >> ans;

}

return 0;

}

Please enter a Fahrenheit temperature: 212

212 in Celsius is 100

Would you like to enter another number? y/n y

Please enter a Fahrenheit temperature: 32

32 in Celsius is 0

Would you like to enter another number? y/n y

Please enter a Fahrenheit temperature: 78

78 in Celsius is 25

Would you like to enter another number? y/n  y

Please enter a Fahrenheit temperature: 23

23 in Celsius is -5

Would you like to enter another number? y/n n

Press any key to continue

Conditional while loop – uses a boolean variable called a flag for loop control.  Loop repetition depends on some criteria being met.  The flag variable is used to exit the loop early.

Problem:  A user is prompted for an integer value.  Write a C++ program that  prints a statement saying whether or not the number is prime.

Brute force approach – A number is prime if it is divisible by 1 and itself.  If the number is divisible by any number between 2 and the number – 1, the number is not prime.

#include <iostream>

using namespace std;

int

main()

{

int divisor = 2, num;

bool flag = false;

cout << "Please enter the number you wish to be tested: ";

cin >> num;

while (!flag)

{

if ((num % divisor) == 0) flag = true;

divisor = divisor + 1;

if (divisor == num) flag = true;

}

if (divisor == num) cout << "Prime!" << endl;

else cout << "Not prime!!" << endl;

return 0;

}

Sentinel Controlled while Loop

Problem:  We wish to be able to calculate the average grade for an exam.  One never knows how many grades there are to process (students are absent, drop the class, etc.).

We could use an interactive while loop to solve this problem.  The problem is that answering the yes/no question can be inefficient.  It’s much easier to just list and process the grades.

To do this efficiently, we can use a sentinel variable to control loop execution.

A sentinel is a value upon which execution is dependent.

A sentinel’s value should never be a valid data value.

#include <iostream>

using namespace std;

int

main()

{

int count = 0;

<< "Enter a value of -1 when finished.\n";

{

count ++;

}

cout << "The average grade was " << average/count << endl;

return 0;

}

75

85

95

95

65

-1

Press any key to continue

Basic structure of a sentinel controlled loop: