Chapter 5 Loops
The while loop
while (condition) statement;
while (condition)
{
block of
statements
}
- local variables and scope
- Using a while loop to validate user input
- Using a counter in a while loop
Some easy examples
- count to 10
- count from 10 to 20
- count from 10 to 1
- count by 2s
- print a list of squares and square roots
- fibonacci numbers
The do-while loop
do statement while (condition);
do
{
block of statements
} while (condition);
Progam
5-7 - Page 248
Example
Roll the dice until ...
The for loop
for (initialization ; condition ; statement(s) to be executed at
end of loop )
statement;
for (initialization ; condition ; statement(s) to be executed at
end of loop )
{
block of statements
}
Examples
Program
5-9 - Page 253
Program
5-10 - Page 256
Program
5-12 - Page 262
Sentinels
Program
5-13 - Page 264
Averaging
Program
5-14 - Page 267
- Roll the dice 10 times
- factorial
More Exampleswhile loop
keep rolling the (two) dice
until you roll a hundred points
flush the input
buffer
do-while loop
keep
rolling the (two) dice until you roll a hundred points
read words until quit
is entered
for loop
The
Clock
What is the average of 1000000 rolls of the (two) dice?How many times do
you roll doubles in 1000000 rolls?What percent of
your 1000000 rolls are doubles?What's the sum of
this series: 4/1
- 4/3 + 4/5 - 4/7 + 4/9 - 4/11 ... ?
Videos
while
Loops
Simple Program Using a Loop
Sentinel
Controlled Program |
while
condition
evaluate
block
scope
break
do while loop
for loop
validate user input
counter variable
sentinel |