Professional Documents
Culture Documents
Lesson 3 – Repetition
Goal(s):
To write loops using do-while statements
Minds On
What is the output of the following code?
int count = 0;
while (count < 10 )
{
count << “Happy Problem-Solving”<<endl;
count += 4;
}
Action …
The do-while Loop
Key Point
A do-while loop is the same as a while loop except that it executes the loop body first and then
checks the loop continuation condition.
The do-while loop is a variation of the while loop. Its syntax is as follows:
Example Write a do-while loop that will prompt the user to input and integer. The program will
calculate the sum of all integers input by the user. The loop exits when the user inputs 0.
Here is a sample run:
2
Introduction to Computer Science 11
Tip
Use the do-while loop if you have statements inside the loop that must be executed at least once,
as in the case of the do-while loop in the preceding TestDoWhile program. These statements
must appear before the loop as well as inside it if you use while loop.
Assessment
1. Suppose the input is 2 3 4 5 0. What is the output of the following code?
max is 5
number 0
2. What are the differences between a while loop and a do-while loop? Convert the
following while loop into a do-while loop. While loop check conditions and run if the
condition is true, do loop run it then check the condition.
int sum=0;
int number=0;
do
{
sum+=number;
cin>>number;
} while (number!=0);
2
Introduction to Computer Science 11
2 times
6. What is count after the loop is finished?
7
2
Introduction to Computer Science 11
7. How many times will the following code print "Welcome to C++"?