Lecture 4 – loops
while Loop
Simplest loop
Two parts: test expression and loop body
Pre-tested loop
– Execute loop body if test true
– Bypass loop body if test false
Lesson 6.1
For Loop
Lesson 6.4
General Syntax
for (initialize lcv; test lcv; update lcv)
{
statement;
statement;
}
Lesson 6.4
for Loop (cont.)
Example:
for (int i = 0; i < 10; i++)
cout << i;
Initialization, testing and updating in same
statement
Semicolons required
Braces optional if only one statement
Lesson 6.4
Example:
int finalValue;
cin >> finalValue; False
True
True
for (int counter = 0; counter < finalValue; counter++)
cout << "*";
3 3 0321
*** finalValue counter
Display Screen
Lesson 6.4
For Loop Examples
float sum = 0;
for (float x = 0.5; x < 20.1; x += 0.5)
sum += sqrt (x);
Lesson 6.4
int finalvalue; Comparison:
cin >> finalValue;
for (int counter = 0; counter < finalValue; counter++)
cout << "*";
int finalvalue; int counter, finalValue;
cin >> finalValue; counter = 0;
for (int counter = 0; cin >> finalValue;
counter < finalValue; while (counter < finalValue)
counter ++) { cout << "*";
cout << "*"; counter++;}
Lesson 6.4
Write program that print the
numbers from 5 to 19
int main()
{
for ( int x=5 ; x<=19 ; x++ )
cout << x ;
return 0;
}
Write program that print the odd
numbers from 5 to 19
int main()
{
for ( int x=5 ; x<=19 ; x+=2 )
cout << x ;
return 0;
}
Debugging and Testing
Off by one errors
– Check loops to ensure you are executing the
correct number of times
– x < 10 or x <= 10
Check loop boundaries
– Can create infinite loop
Does answer make sense
Lesson 6.4
Summary
Learned how to:
Create while loops
Create for loops
Trace and debug loops
Use loops to solve problems
Chapter 6