Lab 8: While Loops, page 3 of 9
Department of Computerand
Mathematical Sciences / CS 1410
Intro to Computer Science with
C++ / 8
Lab 8: While Loops
Objectives:
The objective of this lab is to help understand the various categories of WHILE-LOOPS available in C++.
One aspect of programming that quickly becomes apparent to the beginner is the need to repeatedly execute the same set of instructions in a program, for a fixed number of times or even an indefinite number of times. For example, we may wish to allow the user of a program to repeat the same task as many times as he or she desires. Recall the operating system program FORMAT that we used in the first lab to format a disk. After formatting a disk, each time the program asks the user if he or she wants to format another disk. If the user answers "yes", then the program executes the same set of instructions to format the next disk. Or suppose we are faced with the problem of writing a program to process large quantities of information. Consider, for instance, a program that must generate the payroll checks for all employees in a large company. This program must repeatedly process the same type of information in the same way, namely, the pay rate, hours worked, etc. for each employee. To solve this problem efficiently, the same set of instructions must be executed for each employee RECORD (a record is a small collection of related data values). A mechanism in a programming language that allows the same set of instructions to execute multiple times is called a LOOP. C++ has many types of statements that implement loops, but the most basic and powerful of these statements is the WHILE-LOOP. The syntax for a WHILE-LOOP is as follows:
while (boolean expression)
one statement;
The reserved word in this statement is "while". When a WHILE-LOOP executes, the Boolean expression within the parentheses is evaluated. This expression is called the LOOP CONDITION. If it is TRUE, the statement within the loop executes. Otherwise, execution proceeds to the next statement in the program. Note that this is quite similar to an IF-ELSE statement. The big difference is this: After the statement within the loop executes, then the Boolean expression is evaluated again. If it is TRUE, the statement within the loop executes another time, then the Boolean expression is evaluated again, and so forth. Therefore this looping process continues until the Boolean expression finally evaluates as FALSE. Usually, it is necessary to include more than one statement in the body of a loop. This can be done by using a compound statement, called the LOOP BODY, as shown below:
while ( loop condition )
{
list of statements
}
Therefore, the entire list of statements within the body of this loop will execute over and over again, until the loop condition becomes FALSE.
Task 1: WHILE-LOOP statements
The purpose of this task is to illustrate SENTINEL-CONTROLLED, FLAG-CONTROLLED, and COUNT-CONTROLLED while-loops.
In practice, when loops are used in programs, the following general pattern of statements often appears:
Statements to initialize loop process
Statements to initialize loop condition
while ( loop condition )
{
Statements to perform loop process
Statements to update loop condition
}
The LOOP PROCESS is the key set of steps or instructions that the WHILE-LOOP is designed to repeat. Of course, the statements necessary to carry out this process will be contained within the body of the loop. Many times, it is necessary to place certain statements before the loop to prepare or initialize this process. Likewise, statements are usually needed before the loop to initialize the loop condition to TRUE. If the loop condition is not initialized to TRUE before the WHILE-LOOP is encountered, the statements within the body of the loop may never execute even one time. At the same time, statements must be placed within the body of the loop to update the loop condition. If the loop condition is initially TRUE and is never updated, then it will remain TRUE and the loop will continue executing indefinitely - it will never terminate. This is called an ENDLESS or INFINITE LOOP.
The style of the loop condition can be used to categorize WHILE-LOOPs. There are several categories of loops, including FLAG-CONTROLLED, SENTINEL-CONTROLLED, and COUNT-CONTROLLED loops. A SENTINEL-CONTROLLED loop continues executing until a special data value is input that signals all information has been processed and it's time to terminate (this special data value is called a SENTINEL). On the other hand, a FLAG-CONTROLLED loop is controlled by a special Boolean variable called a FLAG, which is initialized to TRUE before the loop begins executing. This type of loop continues executing until something happens within the loop body that causes the flag variable to become FALSE. A very common type of loop is a COUNT-COUNTROLLED loop. For this type of loop, the loop body executes a fixed number of times. Usually in a count-controlled loop, an integer variable called a COUNTER is used to keep track of how many times the loop body has executed. When the value stored in the counter reaches the fixed number of times the loop is supposed to execute, then the loop terminates.
Statement of the Problem: Create a C++ program called HiLo that will create a guessing game. The program will generate a random number between 1 and 100 for the user to guess. Then ask the user for a number as a guessing number. The program will determine the user’s guessing number as follows:
· If the guessing number is equal to the random number, output the message that the guessing number is correct and quit the game.
· If the guessing number is less than the random number, output a message “Too low.”, and ask if the user want to continue. If yes, ask the user for another guess.
· If the guessing number is greater than the random number, output a message “Too high.”, and ask if the user want to continue. If yes, ask the user for another guess.
Output a goodbye message.
After analyzing the above given problem, the steps of the algorithm can be designed as follows:
1. Generate a random number.
2. Prompt the user for an input as a guessing number.
3. Determine if the guessing number is
a. Equal to the random number: If it is, output a message that says the guessing is correct and quit the game.
b. Less than the random number: If it is,
i. Output a message “Too low,”
ii. Ask if the user wants to continue the game. If yes, ask for another guessing number; otherwise quit the game.
c. Greater than the random number: If it is,
i. Output a message “Too high,”
ii. Ask if the user wants to continue the game. If yes, ask for another guessing number; otherwise quit the game.
4. Output a goodbye message.
Activity 1.1: Use Visual Logic software to convert the above algorithm to a programming flowchart. Then verify your programming flowchart for correct results. Note that in Visual Logic, the fuction Random(100) generates a random number between 1 and 100.
Activity 1.2: Each step of the above algorithm and the programming flowchart in Activity 1.1 can be converted to C++ code as follows.
1. Generate a random number.
/*****These statements generate a random integer from 0 to 100*****/
srand ( time(NULL) );
Number = rand()%100+1;
/******************************************************************/
2. Prompt the user for an input as a guessing number.
cout<"I am thinking of an integer from 1 to 100."<endl;
cout<"Can you guess it?"<endl;
Response = 'y';
notDone = true;
while ( Response == 'y' )
{
cout<endl;
cout<"Make a guess-->";
cin>Guess;
cout<endl;
3. Determine if the guessing number is
a. Equal to the random number: If it is, output a message that says the guessing is correct and quit the game.
if (Guess == Number)
{
cout<"Lucky guess! Did you cheat?"<endl;
notDone = false;
}
b. Less than the random number: If it is,
i. Output a message “Too low,”
ii. Ask if the user wants to continue the game. If yes, ask for another guessing number; otherwise quit the game.
c. Greater than the random number: If it is,
i. Output a message “Too high,”
ii. Ask if the user wants to continue the game. If yes, ask for another guessing number; otherwise quit the game.
else
if (Guess > Number)
cout<"Too high!"<endl;
else
cout<"Too low!"<endl;
if (notDone) //notDone == true
{
cout<endl;
cout<"Do you want to guess again?(y/n)-->";
cin>Response;
cout<endl;
}
else
Response = 'n';
} // while Response
Output a goodbye message.
cout<endl;
cout<"******GOOD BYE******";
Activity 1.3: Start MS Visual Studio and create a C++ project called Lab8 and add a new cpp file called HiLo to the project. Then add the code in Activity 1.2 to complete the program. Then run the program.
Activity 1.4: The while-loop contained in the program HiLo falls into two of the different categories of while-loops. One is easy to see and the other is more subtle. State the two categories and explain why these two categories apply. Then use the constant MaxTries and the variable Tries to modify the program so the user is limited to at most four guesses. (HINT: Modify the while-loop condition.) Run the program to check for correctness. After this modification, the while-loop in the program will also fall into what category?
Original categories: / Additional category:Activity 1.6: Modify the program in Activity 1.3 so that the user is limited to at most 7 guesses. Run and test the modified program.
Task 2: While-Loop
The purpose of this task is to illustrate a possible problem with while-loops.
As mentioned in the previous task, it is possible to design a loop that is INFINITE, that is to say, it will never terminate and continues endlessly executing the loop body. This happens when the loop condition is written in such a way that it never evaluates as FALSE. Believe it or not, creating an infinite loop is a surprisingly easy mistake to make. What type of error is this - syntax or semantics?
Activity 2.1: Study the following program carefully.
Activity 2.2: Predict the output from the program TaskTwo in Activity 2.1.
Activity 2.3: Delete the file HiLo.cpp from the Lab8 project under Source folder in Task 1 in the Solution Explorer window. Then press Delete key. This will remove the file HiLo.cpp Next add a file called Lab8tsk2.cpp to the project by choosing the Add New Items... command from the Project menu. Then copy the source code from Activity 2.1 to Lab8tsk2.cpp file. Run the program and observe the output. You may terminate execution of the program by clicking the Close Window "×" button on the upper right-hand corner of the program output window. Explain any discrepancies with your predicted output and note any errors observed in the program.
Predicted Output: / Observed Output:Activity 2.4: Modify the program TaskTwo to correct the error observed in Activity 2.3. The program should give one line of output: LOOP. After testing your program for correctness, print and turn in the modified program.
Task 3: While-Loops
The purpose of this task is to demonstrate an application of while-loops.
As mentioned earlier, one important application of while-loops is processing large quantities of data values, each of which must be processed in the same way. The program in this task demonstrates this concept, by using a while-loop to process a collection of floating-point data values that are stored in a file. While working through this task, ask yourself: What category of loop is used in this program? What statements initialize the loop condition? What statements update the loop condition?
Statement of the Problem: Create a C++ program called Extrema that will find a minimum and maximum numbers from a given list of data in a text file. The first data in the text file indicates the number of data in the list.
After analyzing the above given problem, the steps of the algorithm can be designed as follows:
1. Open the given text file.
2. Read the first data and set it as the size of the list.
3. Read the next data and set it as minimum and maximum.
4. Read the next data
5. Compare to the minimum: if it is less than the minimum, set the current data as minimum. Otherwise, do nothing.
6. Compare to the maximum: if it is greater than the maximum, set the current data as maximum. Otherwise, do nothing.
7. Repeat steps 4-6 if there some more data to be read.
8. Output the minimum to be the minimum number and the maximum to be the maximum number and close the file.
Activity 3.1: Use Visual Logic software to convert the above algorithm to a programming flowchart. Then verify your programming flowchart for correct results.
Activity 3.2: Each step of the above algorithm and the programming flowchart in Activity 1.1 can be converted to C++ code as follows.
1. Open the given text file.