chapter 3 flow control
chapter 3 flow control
CHAPTER 3
Lecture 1
Flow of Control
As we already have seen in the discussion on
algorithms, programs, like humans, decide what to
do in response to changing circumstances.
11/13/09
If statements
An if statement has two forms: one with an else
branch and one without
If(expression)
statement
Or
If(expression)
statement1
else
statement2
If statement
A test expression that
The if statement evaluates to a Boolean
value (either true or false)
Syntax:
A single statement or a
if (condition) compound statement, to
be executed if
statement condition evaluates to
true.
If the condition is true, the statement is executed,
otherwise it is skipped.
Example 1
#include<iostream>
Using namespace std;
Int main()
{
unsigned short age;
cout<<“Enter your age: “;
cin>>age;
if (age < 17)
cout<<“You are too young!\n”;
cout<<“Thank you.”<<endl;
return 0;
}
Note: the if statement in this example, executed only a single
statement when the expression is true
11/13/09
Example 2
In order to execute multiple statements, we can use a block
e.g.
int val;
cout<<“Enter an integer value: “;
cin>>val;
if (val%2 == 0)
{
int quotient = val/2;
cout<<val<<“ is divisible by 2.”<<endl;
cout<<“The quotient is ”<<quotient<<endl;
cout<<“Thank you.”<<endl;
}
return 0;
}
The else clause
Syntax: If condition evaluates
to true, this statement
if (condition) will be executed
statement1
else
If condition evaluates
statement2 to false, this statement
will be executed
Note: the if and else statements executed a single statement if the condition is true or false
Example 2
statement 1
else
statement 2
else if (conditionN-1)
statementN-1
else
statementN
Nested if …else statements
E.G. When a statement (in the definition of If…Else)
is it self another If……Else statement
11/13/09
Dangling else problem…Summary
The use of a block tells the compiler that the else
statement should attach to the if statement before the
block
Without the block, the else statement would attach to
the nearest unmatched if statement, which would be
the inner if statement
If statements can be used for error checking
The Conditional Operator
A short-hand method of expressing if…else
statements
syntax:
condition ? expression1 : expression2;
An Expression to Expression to
expressio execute if execute if
n that condition condition
evaluates evaluates to evaluates to
to a true. false.
boolean.
Example 1
(x < y) ? x = 10 : y = 10;
if (x < y)
x = 10;
else
y = 10;