Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CPP Lec4-Loop

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 25

Lecture 4: Control Statements

(part 2)
Lecture Overview
 Iterative Control Statements
 While loops
 Do-While loops
 For loops
 Break
 Continue
 Nested Loop
While Loop Operation

 First, the boolean expression is evaluated


 If false, the program skips to the line following the
while loop
 If true, the body of the loop is executed
 During execution, some item from the boolean expression
is changed
 After executing the loop body, the boolean
expression is checked again repeating the
process until the expression becomes false
 A while loop might not execute at all if the
boolean expression is false on the first check
The while Repetition Structure

 Flowchart of while
loop

true
product <= 1000 product = 2 * product

false
Formulating Algorithms (Counter- Controlled
Repetition)
 Counter-controlled repetition
 Loop repeated until counter reaches a certain
value.
 Definite repetition
 Number of repetitions is known
 Example
A class of four students took a quiz. The grades
(integers in the range 0 to 100) for this quiz are
available to you. Determine the class average on
the quiz.
Assignment Operators
 Assignment expression abbreviations
c = c + 3; can be abbreviated as c += 3; using
the addition assignment operator
 Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
 Examples of other assignment operators
include:
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
Increment and Decrement Operators
 Increment operator (++) - can be used instead of c += 1
 Decrement operator (--) - can be used instead of c -= 1
 Preincrement
 When the operator is used before the variable (++c or --c)
 Variable is changed, then the expression it is in is evaluated.
 Posincrement
 When the operator is used after the variable (c++ or c--)
 Expression the variable is in executes, then the variable is changed.
 If c = 5, then
 cout << ++c; prints out 6 (c is changed before cout is
executed)
 cout << c++; prints out 5 (cout is executed before the
increment. c now has the value of 6)
Increment and Decrement Operators
 When Variable is not in an expression
 Preincrementing and postincrementing have
the same effect.
++c;
cout << c;
and
c++;
cout << c;
have the same effect.
Essentials of Counter-Controlled Repetition
 Counter-controlled repetition requires:
 The name of a control variable (or loop counter).
 The initial value of the control variable.
 The condition that tests for the final value of the control
variable
(i.e., whether looping should continue).
 The increment (or decrement) by which the control variable
is modified each time through the loop.
 Example:
int counter =1; //initialization
while (counter <= 10){ //repetition condition
cout << counter << endl;
counter++; //
increment
}
Computing an Average

int listSize = 4;
int numberProcessed = 0;
double sum = 0;
while (numberProcessed < listSize) {
double value;
cin >> value;
sum += value;
+
+numberProces
sed;
}
double average
= sum /
Sentinel-Controlled Repetition
 Suppose the problem becomes:
Develop a class-averaging program that will
process an arbitrary number of grades each time
the program is run.
 Unknown number of students - how will the
program know to end?
 Sentinel value
 Indicates “end of data entry”
 Loop ends when sentinel inputted
 Sentinel value chosen so it cannot be
confused
with a regular input (such as -1 in this
Even Better Way of Averaging
int numberProcessed = 0;
double sum = 0;
double value;
Cin >> value;

while ( value!=-1 ) {
sum += value;
numberProcessed++;
Cin >> value;
}
if ( numberProcessed >
0 ) {
double average = sum / numberProcessed ;
cout << "Average: " << average <<
endl;
}
else {
cout << "No list to average" << endl;
The For Statement
 Syntax
for (ForInit ; ForExpression;
PostExpression)
Action

 Example
for (int i = 0; i < 3; ++i) {
cout << "i is " << i <<
endl;
}
Evaluated once
at the beginning
of the for
statements's ForInit
The ForExpr is
execution evaluated at the
start of each
iteration of the
loop
If ForExpr is ForExpr
true, Action is
executed true false

After the Action If ForExpr is


has completed, Action
false, program
the execution
PostExpression continues with
is next
evaluated statement
PostExpr

After evaluating the


PostExpression, the next
iteration of the loop starts
The break and continue Statements

 Break
 Causes immediate exit from a while, for,
do/while or switch structure
 Program execution continues with the first
statement after the structure
 Common uses of the break statement:
 Escape early from a loop
 Skip the remainder of a switch structure
The break and continue Statements

 Continue
 Skips the remaining statements in the body of a
while, for or do/while structure and
proceeds with the next iteration of the loop
 In while and do/while, the loop-continuation
test is evaluated immediately after the continue
statement is executed
 In the for structure, the increment expression
is executed, then the loop-continuation test is
evaluated
The Do-While loop

 A variation of the while loop.


 A do-while loop is always executed at least once
 The body of the loop is first executed
 The boolean expression is checked after the body
has been executed
 Syntax: do
{
statements to repeat

} while
(boolean_expression);
Syntax of the do-while statement
A do-while example
Loop Issues

 Loop’s condition expression can be


ANY boolean expression
 Examples:
 while (count<3 && done!=0)
{
// Do something
}
 for (index=0;index<10 && entry!=-99)
{
// Do something
}
Loop Pitfalls: Infinite Loops

 Loop condition must evaluate to false at


some iteration through loop
 If not  infinite loop.
 Example:
while (1)
{
cou
t
<<
“He
llo
“;
}
 A
The break and continue Statements

 Flow of Control
 Recall how loops provide ‘graceful’ and
clear flow of control in and out
 In RARE instances, can alter natural
flow
 break;
 Forces loop to exit immediately.
 continue;
 Skips rest of loop body
 These statements violate natural
flow
Nested Loops

 Recall: ANY valid C++ statements can be inside body of


loop
 This includes additional loop statements!
 Called ‘nested loops’
 Requires careful indenting:
• for (outer=0; outer<5; outer++)
for (inner=7; inner>2; inner--)
• cout << outer << inner;
 Notice no { } since each body is
one statement
 Good style dictates we use { }
anyway
Summary
 do-while loops
 Always execute their loop body at least once
 for-loop
 A natural ‘counting’ loop
 Loops can be exited early
 break statement
 continue statement

You might also like