Fundamentals of Programming I: Control Statements

You might also like

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

Fundamentals of Programming I

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

 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.

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

 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
if (myScore > yourScore)
{
cout << "I win!\n";
Sum= Sum + 100;
}
else
{
cout << "I wish these were golf scores.\n";
Sum= 0;
}
5
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

6
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!

7
Multiway if-else: Display

 Not new, just different indenting


 Avoids "excessive" indenting
 Syntax:

8
Multiway if-else Example: Display

9
The switch Statement

 A new statement for controlling multiple branches


 Uses controlling expression which returns bool data type (T or
F)
 Syntax:

10
The switch Statement : Example

11
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"

12
switch Pitfalls/Tip

 Forgetting the break;


 No compiler error
 Execution simply "falls thru" other cases until break;
 Biggest use: MENUs
 Provides clearer "big-picture" view
 Shows menu structure effectively
 Each branch is one menu choice

13
switch and If-Else

switch example if-else equivalent


switch(x) if(x == 1)
{ {
case 1: cout<<"x is 1";
cout<<"x is 1"; }
break; else if(x == 2)
case 2: {
cout<<"x is 2"; cout<<"x is 2";
break; }
default: else
cout<<"value of x unknown"; {
} cout<<"value of x unknown";
}

14
Iteration Structures (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

15
while Loops Syntax

// custom countdown using while Output:


#include<iostream.h>
void main() Enter the starting number: 8
{
int n; 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
cout<<"Enter the starting number:";
cin>>n;
while(n>0)
{
cout<<n<<", ";
--n;
}
cout<<"FIRE!\n";
}

16
do-while Loop Syntax

//number echoer Output:


#include <iostream.h> Enter number (0 to end): 12345
void main() You entered: 12345
{
long n; Enter number (0 to end): 160277
do{ You entered: 160277
cout<<"Enter number (0 to end): "; Enter number (0 to end): 0
cin>>n; You entered: 0
cout<<"You entered: " << n << "\n";
}while(n != 0);
}

17
While vs. do-while

 Very similar, but…


 One important difference
 Issue is "WHEN" boolean expression is checked
 while: checks BEFORE body is executed
 do-while: checked AFTER body is executed
 After this difference, they’re essentially identical!
 while is more common, due to it’s ultimate "flexibility"

18
for Loop Syntax

for (Init_Action; Bool_Exp; Update_Action)


Body_Statement
 Like if-else, Body_Statement can be a block statement
 Much more typical
// countdown using a for loop Output:
#include <iostream.h> 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, FIRE!
void main ()
{
for(int n=10; n>0; n--)
{
cout<< n << ", ";
}
cout<< "FIRE!\n";
}

19
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;
}

20
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!

21
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!

 Infinite loops can be desirable


 e.g., "Embedded Systems"

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

 Break loop Example


// break loop example Output:
#include<iostream.h> 10, 9, 8, 7, 6, 5, 4, 3, countdown aborted!
void main()
{
int n;
for(n=10; n>0; n--)
{
cout<<n<<", ";
if(n==3)
{
cout<<"countdown aborted!";
break;
}
}
}

24
JUMP Statements -The break and continue Statements

 Continue loop Example


// continue loop example Output:
#include<iostream.h> 10, 9, 8, 7, 6, 4, 3, 2, 1, FIRE!
void main ()
{
for(int n=10; n>0; n--)
{
if(n==5)
continue;
cout<<n<<", ";
}
cout<<"FIRE!\n";
}

25
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

26
Thank You

27

You might also like