Professional Documents
Culture Documents
Fundamentals of Programming I: Control Statements
Fundamentals of Programming I: Control Statements
Fundamentals of Programming I: Control Statements
Control Statements
Abraham H.
1
Outline
Introduction
Conditional structure
If and else
The Selective Structure: Switch
Iteration structures (loops)
The while loop
The do-while loop
The for loop
Jump statements
The break statement
The continue statement
2
Introduction
3
Branching Mechanisms
if-else statements
Choice of two alternate statements based on condition
expression
Example:
if (hrs > 40)
grossPay = rate*40 + 1.5*rate*(hrs-40);
else
grossPay = rate*hrs;
if-else Statement 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 {}
4
Compound/Block Statement
6
Nested Statements
7
Multiway if-else: Display
8
Multiway if-else Example: Display
9
The switch Statement
10
The switch Statement : Example
11
The switch: multiple case labels
12
switch Pitfalls/Tip
13
switch and If-Else
14
Iteration Structures (Loops)
15
while Loops Syntax
16
do-while Loop Syntax
17
While vs. do-while
18
for Loop Syntax
19
Converting Between For and While Loops
int i = 1;
while (i < 1024) {
cout << i << endl;
i *= 2;
}
20
Loop Pitfalls: Misplaced ;
21
Loop Pitfalls: Infinite Loops
22
JUMP Statements -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
Only used when absolutely necessary!
23
JUMP Statements -The break and continue Statements
24
JUMP Statements -The break and continue Statements
25
Nested Loops
26
Thank You
27