Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 40

Chapter Four

Control Flow Statements


(Selection and Repetition Statements)
Introduction
 C++ provides different forms of statements for different purposes
 Declaration statements
 Assignment-like statements
 etc
 The order in which statements are executed is called flow control
 Branching statements:
 Specify alternate paths of execution, depending on the outcome of a
logical condition
 Loop statements:
 specify computations, which need to be repeated until a certain
logical condition is satisfied.
if-else Statement Syntax
 Formal syntax:
if (<boolean_expression>)
<yes_statement>
else
<no_statement>
 Note each alternative is only ONE statement!
 To have multiple statements execute in either branch 
use compound statement
Compound/Block Statement
 Only "get" one statement per branch
 Must use compound statement { } for multiples
 Also called a "block" statement
 Each block should have block statement
 Even if just one statement
 Enhances readability
Compound Statement in Action
 Note indenting in this example:
if (myScore > yourScore)
{
cout << "I win!\n";
wager = wager + 100;
}
else
{
cout << "I wish these were golf scores.\n";
wager = 0;
}
The Optional else
 else clause is optional
 If, in the false branch (else), you want "nothing" to happen, leave
it out
 Example:
if (sales >= minimum)
salary = salary + bonus;
cout << "Salary = %" << salary;
 Note: nothing to do for false condition, so there is no else clause!
 Execution continues with cout statement
 Example2, when dividing two values, we may want to check that
the denominator is nonzero
Nested Statements
 if-else statements contain smaller statements
 Compound or simple statements (we’ve seen)
 Can also contain any statement at all, including another if-
else stmt!
 Example:
if (speed > 55)
if (speed > 80)
cout << "You’re really speeding!";
else
cout << "You’re speeding.";
 Note proper indenting!
Multi way if-else: Display Statements
Multi way if-else Example:
Display
 Write Program to find number is Even or Odd using if-else
statement
 Write a program that accepts a character from the user and:
 If the char is number print “the character is a number”
 If the char is capital letter print “the character is capital letter”
 If the char is small letter print “the character is small letter”
 Else “the character is special character”;
 to the screen.
The switch Statement
 A new statement for controlling multiple branches
 Uses controlling expression which returns bool data type (true
or false)
 Syntax:
 next slide
The switch Statement
The switch Statement in Action
The switch Statement in Action
switch(1) {
case 1 : cout << '1';
case 2 : cout << '2';
}
switch(1) {
case 1 : cout << '1';
break;
case 2 : cout << '2';
break;
} congratulation
The switch: multiple case labels
 Execution "falls thru" until break
 switch provides a "point of entry"
 Example:
case "A":
case "a":
cout << "Excellent: you got an "A"!\n";
break;
case "B":
case "b":
cout << "Good: you got a "B"!\n";
break;
 Note multiple labels provide same "entry"
Equivalent to if statement
 switch (expr) {
case c1:
statements // do these if expr == c1
break;
case c2:
statements // do these if expr == c2
break;
case c2: // multiple values can share same statements
case c3:
case c4:
statements // do these if expr == any of c2, c3, or c4
break;
default:
statements // do these if expr != any above}
Equivalent to if statement
 if (expr==c1) {
statements
} else if (expr==c2) {
statements
} else if (expr==c2 || expr==c3 || expr==c4) {
Statements
} else {
Statements
}
Loops
 A loop is a way of repeating a series of instructions several
times
 Two Parts to Repetition
 a Body
 what needs to be repeated
 must be marked off in some fashion like {}
 a Control expression
 some way to make the repetition stop when desired
 Infinite loops not wanted!
Loops
 3 Types of loops in C++
– while
 Most flexible
 No "restrictions"

– do -while
 Least flexible
 Always executes loop body at least once

– for
 Natural "counting" loop
while Loops Syntax
 The while statement (also called the while loop) provides a
way of repeating a statement while a condition holds.
while Loops

 First expression (called the loop condition) is evaluated

 If the outcome is nonzero then statement (called the loop body)

is executed and the whole process is repeated


 Otherwise, the loop is terminated
while Loops Example

 Consider:
count = 0; // Initialization
while (count < 3) // Loop Condition
{
cout << "Hi "; // Loop Body
count++; // Update expression
}
– Loop body executes how many times?
while Loops Example2
void main()
{
int sum =0,i=1,n;
cout<<"Enter the maximum number"<<endl;
cin>>n;
while (i <= n)
sum += i++;
cout<<"the sum of numbers from 1 to <<n<<"is
=:"<<sum;
}
do-while Loop Syntax
 The do statement (also called do loop) is similar to the while
statement, except that its body is executed first and then the
loop condition is examined.
do-while Loop
 First statement is executed and then expression is evaluated.

 If the outcome of the latter is nonzero then the whole

process is repeated.
 Otherwise, the loop is terminated.

 The do loop is less frequently used than the while loop.

 It is useful for situations where we need the loop body to be

executed at least once, regardless of the loop condition.


do-while Loop Example

count = 0; // Initialization
do
{
cout << "Hi "; // Loop Body
count++; // Update expression
} while (count < 3); // Loop Condition
Loop body executes how many times?

do-while loops always execute body at least once!


do-while Loop Example2

void main ()
{
char ch;
do
{
cout<<"Hello!\n";
cout<<"Do you want to display more Hello's (Y/N) ";
cin >>ch;
} while (ch != 'N');
}
for Loop Syntax

 This is the simplest and straight-forward looping construct

that has the following general look:

for(expression1;expression2;expression3)
 First expression1 is evaluated. Each time round the loop,

expression2 is evaluated. If the outcome is nonzero then


statement is executed and expression3 is evaluated.
Otherwise, the loop is terminated.
For Loop Example

 for (count=0;count<3;count++)

{
cout << "Hi "; // Loop Body
}
 How many times does loop body execute?
For Loop Example

void main ()
{
int x, limit, sum;
cout << "Please enter a number bigger than 1 : ";
cin >> limit;
sum = 0;
for (x = 1; x <= limit; x++) {
cout << "I am adding " << x << endl;
sum = sum + x;
}
cout << endl;
cout << "The sum of all the numbers from 1 to ";
cout << limit << " is " << sum;
return;
}
Converting Between For and While Loops

for (int i = 1; i < 1024; i *= 2) {


cout << i << endl;
}

int i = 1;
while (i < 1024) {
cout << i << endl;
i *= 2;
}
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: Misplaced ;

Watch the misplaced ; (semicolon)


Example:
while (response != 0) ;
{
cout << "Enter val: ";
cin >> response;
}
Notice the ";" after the while condition!
Result here: INFINITE LOOP!
Loop Pitfalls: Infinite Loops

 Loop condition must evaluate to false at some iteration


through loop
 If not  infinite loop.
Example:
while (1)
{
cout << "Hello ";
}
 A perfectly legal C++ loop  always infinite!
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
Nested Loops Exercise
 Write a program which produces a simple
multiplication table of the following format for integers
in the range 1 to 9:
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 break and continue Statements
 Causes an immediate jump to the loop test
int next = 0;
while (true){
cin >> next;
if (next < 0)
break;
if (next % 2!=0) //odd number, don’t print
continue;
cout << next << endl;
}
cout << “negative num so here we are!” << endl;
End of 4th chapter

40

You might also like