Вы находитесь на странице: 1из 63

Flow of Control

Unless specified otherwise, the order of statement

execution through a method is linear: one statement
after another in sequence
Some programming statements allow us to:
decide whether or not to execute a particular statement
execute a statement over and over, repetitively

These decisions are based on boolean expressions (or

conditions) that evaluate to true or false
The order of statement execution is called the flow of
control
Conditional Statements
A conditional statement lets us choose which
statement will be executed next
Therefore they are sometimes called selection
statements
Conditional statements give us the power to make
basic decisions
The conditional statements are :
if statement
if-else statement
switch statement
The if Statement
The if statement has the following syntax:
The condition must be a
boolean expression. It must
if is a evaluate to either true or false.
reserved word

if ( condition )
statement;

If condition is true: statement is executed.

If condition is false: statement is skipped.
Logic of an if statement

condition
evaluated

true
false
statement
The if Statement
An example of an if statement:
if (sum > MAX)
delta = sum - MAX;
cout<<The sum is << sum;

First the condition is evaluated -- the value of sum

is either greater than the value of MAX, or it is not

If the condition is true, the assignment statement

is executed -- if it isnt, it is skipped.
if ( a > 10 && b > 20 && c < 10 )

if ( a == 10 || b < 20 )
The if Statement
What do the following statements do?
if (top >= MAXIMUM)
top = 0;
Sets top to zero if the current value of top is greater
than or equal to the value of MAXIMUM

if (total != stock + warehouse)

inventoryError = true;

Sets a flag to true if the value of total is not equal to

the sum of stock and warehouse

The precedence of the arithmetic operators is

higher than the precedence of the equality and
relational operators
The if-else Statement
An else clause can be added to an if
statement to make an if-else statement
if ( condition )
statement1;
else
statement2;

If the condition is true, statement1 is executed;

if the condition is false, statement2 is executed
Logic of an if-else statement

condition
evaluated

true false

statement1 statement2
Block Statements
Several statements can be grouped together
into a block statement delimited by braces

if (total > MAX)

{
printf("Error!!");
errorCount++;
}
Block Statements
In an if-else statement, the if portion, or the
else portion, or both, could be block statements
if (total > MAX)
{
printf ("Error!!");
errorCount++;
}
else
{
printf ("Total: " + total);
current = total*2;
}
Nested if Statements
The statement executed as a result of an if
statement or else clause could be another if
statement
These are called nested if statements
An else clause is matched to the last unmatched
if (no matter what the indentation implies)
Braces can be used to specify the if statement to
which an else clause belongs
The switch Statement
The switch statement provides another way to
decide which statement to execute next
The switch statement evaluates an expression,
then attempts to match the result to one of
several possible cases
Each case contains one value (a constant) and a
list of statements
The flow of control transfers to statement
associated with the first case value that matches
The switch Statement
The general syntax of a switch statement is:
switch switch ( expression )
and {
case case value1 :
are statement-list1
reserved case value2 :
words statement-list2
case value3 :
statement-list3 If expression
case ... matches value2,
control jumps
} to here
The switch Statement
Often a break statement is used as the last
statement in each case's statement list
A break statement causes control to transfer to
the end of the switch statement
If a break statement is not used, the flow of
control will continue into the next case
Sometimes this may be appropriate, but often we
want to execute only the statements associated
with one case
The switch Statement
An example of a switch statement:
switch (option)
{
case 'A':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
}
The switch Statement
A switch statement can have an optional
default case
The default case has no associated value and
simply uses the reserved word default
If the default case is present, control will transfer
to it if no other case value matches
If there is no default case, and no other value
matches, control falls through to the statement
after the switch
The switch Statement
The expression of a switch statement must
result in an integral type, meaning an integer
(short, int, long) or a char
It cannot be a boolean value or a floating point
value (float or double)
The implicit boolean condition in a switch
statement is equality
You cannot perform relational checks with a
switch statement
#include<iostream>
using namespace std;
int main() {
int A; cin >> A;
if ( A == 10 )
cout << "is equal" << '\n';
}
if ( A != 10 )
{
cout << "Hello" << '\n';
cout << "Hello" << '\n';
}
#include<iostream>
using namespace std; int main() {
int A; cin >> A;
if ( A == 10 )
{
cout << "is equal" << '\n';
cout << "closing program" << '\n';
}
else
{
cout << "not equal" << '\n';
cout << "closing program" << '\n';
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int a; cin >> a;
if ( a <= 10 )
{
cout << "Below 10" << '\n'; }
else
{
if ( a < 60 )
{
cout << "Below 60" << '\n'; } } return 0; }
#include<iostream>
using namespace std;
int main()
{
char myinput;
cin >> myinput;
switch (myinput)
{
case 'a': cout << "Run program 1\n"; break;
case 'b':
{
cout << "Run program 2\n";
cout << "Please Wait\n"; break; }
default: cout << "Invalid choice\n";
break; }
return 0;
}
if (total_test_score >=0 && total_test_score < 50)
cout << "You are a failure - you must study much harder.\n";
else
if (total_test_score < 60)
cout << "You have just scraped through the test.\n";
Else
if (total_test_score < 80)
cout << "You have done quite well.\n";
else
if (total_test_score <= 100)
cout << "Your score is excellent - well done.\n";
else
cout << "Incorrect score - must be between 0 and 100.\n";
score_out_of_ten = total_test_score / 10;
switch (score_out_of_ten)
{
case 0: case 1: case 2: case 3: case 4:
cout << "You are a failure - you ";
cout << "must study much harder.\n"; break;
case 5: cout << "You have just scraped through the test.\n";
break;
case 6: case 7:
cout << "You have done quite well.\n"; break;
case 8: case 9: case 10: cout << "Your score is excellent - well
done.\n"; break;
default: cout << "Incorrect score - must be between ";
cout << "0 and 100.\n"; } ...
Looping (Repetition) Statements
Repetition statements allow us to execute a statement
multiple times
Often they are referred to as loops
Like conditional statements, they are controlled by boolean
expressions
three kinds of repetition statements:
the while loop
the do loop
the for loop
The programmer should choose the right kind of loop for
the situation
The while Statement
A while statement has the following syntax:
while ( condition )
statement;

executed

Then the condition is evaluated again, and if it is

still true, the statement is executed again

The statement is executed repeatedly until the

condition becomes false
Logic of a while Loop

condition
evaluated

true false

statement
The while Statement
An example of a while statement:
int count = 1;
while (count <= 5)
{
cout<<count;
count++;
}

If the condition of a while loop is false initially, the

statement is never executed
Therefore, the body of a while loop will execute
zero or more times
The while Statement
Let's look at some examples of loop processing
A loop can be used to maintain a running sum
A sentinel value is a special input value that
represents the end of input
A loop can also be used for input validation,
making a program more robust
Infinite Loops
The body of a while loop eventually must make
the condition false
If not, it is called an infinite loop, which will
execute until the user interrupts the program
This is a common logical error
You should always double check the logic of a
program to ensure that your loops will terminate
normally
Infinite Loops
An example of an infinite loop:
int count = 1;
while (count <= 25)
{
cout<<count;
count = count - 1;
}

This loop will continue executing until interrupted

(Control-C) or until an underflow error occurs
Nested Loops
Similar to nested if statements, loops can be
nested as well

loop

For each iteration of the outer loop, the inner

loop iterates completely
Nested Loops
How many times will the string "Here" be printed?
count1 = 1;
while (count1 <= 10)
{
count2 = 1;
while (count2 <= 20)
{
cout<<"Here";
count2++;
}
count1++;
}
10 * 20 = 200
Nested Loops
Nested loops consist of an outer loop with one or
more inner loops.
e.g.,
for (i=1;i<=100;i++){
Outer loop
for(j=1;j<=50;j++){

} Inner loop
}
The above loop will run for 100*50 iterations.
int x;
main()
{ for (x=3;x>0;x--)
{ cout<<x; }
} ...
outputs:
x=3 x=2 x=1 ...to the screen
following are legal for statements in C++.
for (x=0;((x>3) && (x<9)); x++)
for (x=0,y=4;((x>3) && (y<9)); x++,y+=2)
for (x=0,y=4,z=4000;z; z/=10)
The second example shows that multiple
expressions can be separated a ,.
In the third example the loop will continue to
iterate until z becomes 0;
the while loop can accept expressions, not just
conditions,
the following are all legal:-
while (x-);
while (x=x+1);
while (x+=5);
Using this type of expression, only when the result
of x-, x=x+1, or x+=5, evaluates to 0 will
the while condition fail and the loop be exited.
int x=3;
main()
{
do
{
cout<<x--;
} while (x>0);
}
..outputs:-
x=3 x=2 x=1

NOTE: The postfix x- operator which uses the current

value of x while printing and then decrements x.
The do while Statement
A do statement has the following syntax:
do
{
statement;
}
while ( condition );

The statement is executed once initially, and then

the condition is evaluated

The statement is executed repeatedly until the

condition becomes false
Logic of a do Loop

statement

true

condition
evaluated

false
The do while Statement
An example of a do loop:
int count = 0;
do
{
count++;
cout<<count;
} while (count < 5);

The body of a do while loop executes at least once

Comparing while and do
The while Loop The do While Loop

statement
condition
evaluated
true

condition
true false
evaluated

statement
false
The for Statement
A for statement has the following syntax:
The initialization The statement is
is executed once executed until the
before the loop begins condition becomes false

statement;

The increment portion is executed at

the end of each iteration
Logic of a for loop
initialization

condition
evaluated

true false

statement

increment
The for Statement
A for loop is functionally equivalent to the
following while loop structure:
initialization;
while ( condition )
{
statement;
increment;
}
The for Statement
An example of a for loop:
for (int count=1; count <= 5; count++)
cout<<count;

variable

Like a while loop, the condition of a for loop is

tested prior to executing the loop body

Therefore, the body of a for loop will execute zero

or more times
The for Statement
The increment section can perform any
calculation
for (int num=100; num > 0; num -= 5)
cout<< num;

A for loop is well suited for executing statements

a specific number of times that can be calculated
or determined in advance
The for Statement
Each expression in the header of a for loop is
optional
If the initialization is left out, no initialization is
performed
If the condition is left out, it is always considered
to be true, and therefore creates an infinite loop
If the increment is left out, no increment
operation is performed
Omitting the logical expression in a for statement means
that the for statement executes as an infinite loop.

for(i=1; ;i=i+1)
{
#include <iostream>
using namespace std;
int main() {
int number; char character;
for (number = 32 ; number <= 126 ; number = number + 1)
{
character = number;
cout << "The character '" << character;
cout << "' is represented as the number ";
cout << number << " in the computer.\n";
} return 0;
}
#include <iostream>
using namespace std;
int main()
{ int number; char character;
number = 32;
while (number <= 126)
{
character = number;
cout << "The character '" << character; cout << "' is
represented as the number ";
cout << number << " in the computer.\n"; number++; }
return 0;
}
do
{ cout << "Enter the candidate's score: ";
cin >> candidate_score;
if (candidate_score > 100 || candidate_score < 0)
cout << "Score must be between 0 and 100.\n";
}
while (candidate_score > 100 || candidate_score < 0);
cout << "Enter the candidate's score: ";
cin >> candidate_score;
while (candidate_score > 100 || candidate_score < 0)
{
cout << "Score must be between 0 and 100.\n";
cout << "Enter the candidate's score: ";
cin >> candidate_score;
}
C provides two commands to control how we
loop:
break -- exit form loop or switch.
continue -- skip 1 iteration of loop.
The break and continue Statements
The break statement causes an exit from the
innermost enclosing loop or switch statement.
The continue statement causes the current iteration
of a loop to stop and the next iteration to begin
immediately.
Example Using a break Statement

while (1) {
cin>>x;
if (x < 0.0)
break;
cout<<sqrt(x);
}

/* break causes jump to next statement */

/* after the while loop. */
Example Using a continue Statement

while (cnt < n) {

cin>>x;
if (x > -0.01 && x < +0.01)
continue; /* disregard small values */
++cnt;
sum += x;
/* continue transfers control to */
/* here to immediately begin the */
/* next iteration. */
}
Comparison of Loop Choices (1/2)
Kind When to Use C Structure
Counting loop We know how many loop while, for
repetitions will be needed
Sentinel- Input of a list of data ended while, for
controlled loop by a special value
Endfile- Input of a list of data from while, for
controlled loop a data file
Comparison of Loop Choices (2/2)
Kind When to Use C Structure
Input validation Repeated interactive input do-while
loop of a value until a desired
value is entered.
General Repeated processing of while, for
conditional data until a desired
loop condition is met.
The goto Statement
goto causes an unconditional jump to a
labeled statement somewhere in the current
function.
Form of a labeled statement.
label: statement
Where label is an identifier.
Example of goto and label
Cin>>x;
while (x== 1) {
if (x < 0.0)
cout<<x<< sqrt(x)<< sqrt(2 * x));
Cin>>x;
}
if (x < 0.0)
cout<<(Negative value encountered!\n);
#include <iostream>
using namespace std;
int integer1 = 1;
int integer2 = 2;
int integer3 = 3;
int main()
{
int integer1 = -1;
int integer2 = -2;
{
int integer1 = 10;
cout << "integer1 == " << integer1 << "\n";
cout << "integer2 == " << integer2 << "\n";
cout << "integer3 == " << integer3 << "\n";
}
cout << "integer1 == " << integer1 << "\n";
cout << "integer2 == " << integer2 << "\n";
cout << "integer3 == " << integer3 << "\n"; return 0;
}
#include <iostream>
using namespace std;
int main()
{
int number;
for (number = 1 ; number <= 10 ; number++)
{
int multiplier;
for (multiplier = 1 ; multiplier <= 10 ; multiplier++)
{
cout << number << " x " << multiplier << " = ";
cout << number * multiplier << "\n";
}
cout << "\n";
}