CITP 3310 XXXXXXXXXXSurvey of Programming Languages XXXXXXXXXXLab 8
Lab 8 – while Loops
In this lab, you will practice using while loops to perform repetitive tasks. There are many different types
of while loops you can write, so in this lab you will write two programs that each demonstrate a
different type of loop.
Example Program
The example program here is a simple little game where the user has to try to guess the number that
the computer has randomly chosen. The user has an unlimited number of tries, until eventually they get
the answer co
ect.
Download Guess_the_Number.cs and create a project for it in Visual C#. Read and understand the code
and run the program.
Your Program #1
The Guess Number example above is a bit boring because the user gets an unlimited number of
attempts to find the answer. You will make it more interesting by only allowing the user to guess up to 5
times.
You will need to use a complex condition for the while loop. One part of the complex condition is
whether the user has guessed the number (similar to how it is done in the example), and the other part
is a counter that only lets the user have 5 guesses. Complex conditions with while loops are similar to
those with if statements, and you separate the conditions with a boolean operator (&& or ||)
Your output should look similar to the sample output below for Program #1. Turn in your completed
program.
Your Program #2
For your second program, you will need to modify lab number 5, the Magic 8-Ball. You should now use a
loop to let the user ask additional questions. After giving the user their random answer, ask them a
simple yes or no question about whether they would like to continue. This is similar to the questions you
asked in labs 6 or 7, and we will assume that the user still enters co
ect information.
If the user answers ‘y’ for yes, then your loop should allow them to ask another question and give them
another answer. If they answer ‘n’, then your loop should terminate.
Turn in your completed program.
CHALLENGE
In this week’s challenge component, you should start to look at the other types of loop structures that
we have in C#. Rewrite Program #1 from this lab (the Number Guessing one) using a for loop instead of a
while. Because for loops are predominantly counter-controlled loops, this will require you to use a
eak
statement to exit the loop early if the co
ect answer is chosen.
CITP 3310 XXXXXXXXXXSurvey of Programming Languages XXXXXXXXXXLab 8
SAMPLE OUTPUT for Program #1