Lesson 2 - Repetition: Goal(s)
Lesson 2 - Repetition: Goal(s)
Lesson 2 – Repetition
Goal(s):
To write loops for the guessing number problem
To follow the loop design strategy to develop loops
To control a loop with the user confirmation or a sentinel value
Minds On…
Action …
Key Point
A while loop executes statements repeatedly while the condition is true. Problem
Write a program that randomly generates an integer between 0 and 100, inclusive.
The program prompts the user to enter a number continuously until the number
matches the randomly generated number. For each user input, the program tells the
user whether the input is too low or too high, so the user can make the next guess
intelligently. Here is a sample run:
1
Introduction to Computer Science 11
5. If the user guess = magic number, display ‘Yes, You got it’
1
Introduction to Computer Science 11
Assessment
1. How many times will the following code print "Welcome to C++"?
Introduction to Computer Science 11
1
Programming Exercises
4. (Simulation: Even or Odd) Write a program that generates a random integer
one
hundred thousand times (100 000) and displays the number of even and odd
integers.
5. (Occurrence of max numbers) Write a program that reads integers, finds the
largest
of them, and counts its occurrences. Assume that the input ends with number
0. Suppose that you entered 3 5 2 5 5 5 0; the program finds that the largest is
5 and the occurrence count for 5 is 4.
1
Introduction to Computer Science 11
(Hint : Maintain two variables, max and count. max stores the current max
number, and count stores its occurrences. Initially, assign the first number to max
and 1 to count. Compare each subsequent number with max. If the number is
greater than max, assign it to max and reset count to 1. If the number is equal to
max, increment count by 1.)
6. (Simulation: clock countdown) Write a program that prompts the user to enter
the
number of seconds, displays a message at every second, and
terminates when the
time expires. Here is a sample run: