ECE151 - Lecture 5
ECE151 - Lecture 5
Programming
The Increment and Decrement
Operators
Continued…
Increment and Decrement
Operators in Program 5-1
Prefix vs. Postfix
while (expression)
statement;
● statement; can also be a block of statements enclosed in { }
The while Loop – How It Works
while (expression)
statement;
● expression is evaluated
int number = 6;
while (number <= 5)
{
cout << "Hello\n";
number++;
}
Watch Out for Infinite Loops
int number = 1;
while (number <= 5)
{
cout << "Hello\n";
}
Using the while Loop for Input Validation
● Input validation is the process of inspecting data that is given to the program
as input and determining whether it is valid.
● The while loop can be used to create input routines that reject invalid data,
and repeat until valid data is entered.
Using the while Loop for Input Validation
Continued…
A Counter Variable Controls the Loop in
Program 5-6
The do-while Loop
int x = 1;
do
{
cout << x << endl;
} while(x < 0);
Continued…
A do-while Loop in Program 5-7
do-while Loop Notes
● General Format:
statement; // or block in { }
statement; // or block in { }
1) Perform initialization
2) Evaluate test expression
○ If true, execute statement
int count;
Continued…
A for Loop in Program 5-9
A Closer Look at Lines 15 through 16 in
Program 5-9
Flowchart for Lines 15 through 16 in Program
5-9
When to Use the for Loop
○ an initialization
● The for loop tests its test expression before each iteration, so it is a pretest
loop.
● The following loop will never iterate:
int x, y;
for (x=1, y=1; x <= 5; x++)
{
cout << x << " plus " << y
<< " equals " << (x+y)
<< endl;
}
for Loop - Modifications
int x, y;
for (x=1, y=1; x <= 5; x++, y++)
{
cout << x << " plus " << y
<< " equals " << (x+y)
<< endl;
}
for Loop - Modifications
int sum = 0;
sum += num;
Continued…
A Running Total in Program 5-12
Sentinels
● Special value that cannot be confused with a valid value, e.g., -999 for a test
score
● Used to terminate input when user may not know how many values will be
entered
A Sentinel in Program 5-13
Continued…
A Sentinel in Program 5-13
Deciding Which Loop to Use
○ Validating input
○ Repeating a menu
Inner Loop
Outer Loop
Nested Loops - Notes
● Inner loop goes through all repetitions for each repetition of outer loop
● When used in an inner loop, terminates that loop only and goes back to outer
loop
The continue Statement
● Can use continue to go to end of loop and prepare for next repetition
○ for loop: perform update step, then test, then repeat loop if test passes
● Use sparingly – like break, can make program logic hard to follow
Thank You