0% found this document useful (0 votes)
20 views55 pages

Chapter 3 Control Statments

The document discusses flow control in programming, focusing on conditional statements such as if, if...else, and switch statements. It explains the syntax and usage of these statements, including examples and potential pitfalls like the dangling else problem. Additionally, it introduces looping structures in C++, specifically the while loop, and provides examples of their implementation.

Uploaded by

firehiwot
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views55 pages

Chapter 3 Control Statments

The document discusses flow control in programming, focusing on conditional statements such as if, if...else, and switch statements. It explains the syntax and usage of these statements, including examples and potential pitfalls like the dangling else problem. Additionally, it introduces looping structures in C++, specifically the while loop, and provides examples of their implementation.

Uploaded by

firehiwot
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 55

Flow of Control

 The order in which statements are executed is called flow control


(or control flow).
 This term reflect the fact that currently executing statement has
the control of the CPU, which when completed will be handed
over to another statement.
 Flow control in a program is typically sequential, from one
statement to the next, but may also be diverted to other paths by
branch statements.

Sunday, March 23, 2025 2


1.Conditional statements (if, if…else,
switch)

 It is sometimes desirable to make the execution of a


statement dependent upon a condition being satisfied.
The if statement provides a way of expressing this.

Sunday, March 23, 2025 3


i ) If statements
 An if statement has two forms: one with an else branch and the
other is without else branch.
i) if statement (single selection) A test expression that
evaluates to a boolean value
Syntax: (either true or false)
If(expression or condition)
{
//code/statement(s) A single statement or a
} compound statement, to be
executed if condition
evaluates to true.
 If the condition is true, the statement is executed, otherwise it is
skipped.

Sunday, March 23, 2025 4


Example 1
unsigned short age;
cout<<“Enter your age:”;
cin>>age;
if (age < 17)
cout<<“You are too young!\n”;
cout<<“Thank you.”<<endl;

Note: the if statement in this example executed only


a single statement when the expression is true
Sunday, March 23, 2025 5
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;

Sunday, March 23, 2025 6


ii) if… else statement (double selection)

Syntax:
If condition evaluates
If(expression or condition) to true, this statement
{ will be executed

//code1/statement1
}
else
{ If condition evaluates
to false, this statement
//code2/statement2 will be executed
}
Sunday, March 23, 2025 7
Example 1
Note: the if and else statements executed a single statement if the condition is
true or false

Sunday, March 23, 2025 8


Example 2
In order to execute multiple statements we can use a block

Sunday, March 23, 2025 9


Flowchart equivalents

Sunday, March 23, 2025 10


iii) Nested if …else statements
Syntax:
If(expression/condition)
{
statement1
}
else
{
statement2
}
Note that: statement1and statement 2 can be any
statement including if… else statement
Sunday, March 23, 2025 11
Nested if …else statements
E.g. when statement 2 itself is again another if…else statement

Sunday, March 23, 2025 12


If …else if … else
(multiple selection)
Convenient form for if…else statements
if (condition1)
statement1
else if (condition2)
statement2
...

else if (conditionN-1)
statementN-1
else
statement N
Sunday, March 23, 2025 13
Example :
unsigned short age;
cout<<“Enter your age: “;
cin>>age;
if (age < 17)
cout<<“You are too young!\n”;
else if (age < 40)
cout<<“You are still young!\n”;
else if (age < 70)
cout<<“Young at heart!\n”;
else
cout<<“Are you sure?\n”;

cout<<“Thank you.”<<endl;
Sunday, March 23, 2025 14
//This program illustrates a bug that occurs when independent if/else statements are used to
assign a letter grade to a test score.
#include <iostream>
using namespace std;
int main()
{
int testScore; char grade;
cout << "Enter your test score and I will tell you \n” the letter grade you earned: ";
cin >> testScore;
if (testScore < 60)
grade = 'F'; Program Output with Example Input Shown in
if (testScore < 70) Bold
grade = 'D'; Enter your test score and I will tell you
if (testScore < 80) the letter grade you earned: 40[Enter]
Your grade is A.
grade = 'C';
if (testScore < 90)
grade = 'B';
if (testScore <= 100)
grade = 'A';
cout << "Your grade is " << grade << ".\n";
return 0; Sunday, March 23, 2025 15
}
//It can be corrected like this
#include <iostream>
using namespace std;
int main()
{
int testScore; char grade;
cout << "Enter your test score and I will\n "tell you the letter grade you earned: ";
cin >> testScore;
if (testScore < 60)
grade = 'F'; Program Output with Example Input Shown in
else if (testScore < 70) Bold
grade = 'D'; Enter your test score and I will tell you
else if (testScore < 80) the letter grade you earned: 40[Enter]
grade = 'C'; Your grade is F.
else if (testScore < 90)
grade = 'B';
else (testScore <= 100)
grade = 'A';
cout << "Your grade is " << grade << ".\n";
return 0;
Sunday, March 23, 2025 16
}
Dangling else/ matching else problem

The above program introduces a source of potential ambiguity


called a dangling else problem

Sunday, March 23, 2025 17


Dangling else problem
 Is the else statement in the above program matched
up with the outer or inner if statement?
 The answer is that an else statement is paired up
with the last unmatched if statement in the same
block

Sunday, March 23, 2025 18


Dangling else problem
(The above program can be written without ambiguity like this)

Sunday, March 23, 2025 19


Dangling else problem
 However, if we want the else to attach to the outer if statement, we
can do this explicitly by enclosing the inner if statement in a block

Sunday, March 23, 2025 20


Summary on Dangling else problem

• 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

Sunday, March 23, 2025 21


ii) The Switch Statement
 It is usually very difficult to express our intended logic
using such deeply nested if...else statements.
 As an alternative method of nested if else statement to
choose among a set of mutually exclusive choices, C++
provides the switch statement.

Sunday, March 23, 2025 22


iv) The switch Statement
Syntax: An integer expression, whose value
we want to test
switch (expression)
{ Unique, possible values that we are
case constant1: testing for equality with expression
statements
break;
case constant2:
statements
break;
Statements to be executed when
expression becomes equal to

constantN
case constantN:
statements
break;
Statements to be executed when
default:
expression is not equal to any of
statements
The break statement causes the the N constants
}
Program to exit the switch
Sunday, March 23, 2025 23
statement
The Switch Statement(principles)

 The switch expression is evaluated to produce a value, and

 each case label (constant1,constant2,..)is tested against


this value for equality.
 If a case label matches, the statements after the case label
is executed.
 If no case label matches with the switch expression, the
statement under the default label is executed (if it exists).
Sunday, March 23, 2025 24
Example
// This program demonstrates the use of a switch statement.
// The program simply tells the user what character they entered.
#include <iostream>
using namespace std;
int main()
{
char choice;
cout << "Enter A, B, or C: ";
cin >> choice;
switch (choice)
{
case 'A': cout << "You entered A.\n";
break;
case 'B': cout << "You entered B.\n";
break;
case 'C': cout << "You entered C.\n";
break;
default:
cout << "You did not enter A, B, or C!\n";
}
return
Sunday, 0;2025
March 23, } 25
The switch statement
int x;
cout<<”Enter a number”; • Note that the expressions of
cin>>x;
switch (x) each case statement in the block
{
case 1:cout<<”You Entered 1:”; must be unique.
break;
case 2:cout<<”You Entered 2:”; • That is , you can’t do this
break; Switch(x)
case 3:cout<<”You Entered 3:”;
{
break; case 4:
default: cout<<”Invalid Input:”; …..
break; } case 4://illegal…already used value 4
……
default:
Sunday, March 23, 2025 26
}
Break Statement
 Without the break statements, the program would execute all of the lines from the matching
case statement to the end of the block .
 The break statement causes the program to exit the switch statement
// This program demonstrates how a switch statement works if there are no break statements.
#include <iostream>
using namespace std;
int main()
{
char choice;
cout << "Enter A, B, or C: ";
cin >> choice;
switch (choice) // The ff switch statement is missing its break statements!
{
case 'A': cout << "You entered A.\n";
case 'B': cout << "You entered B.\n";
case 'C': cout << "You entered C.\n";
default : cout << "You did not enter A, B, or C!\n";
}
return 0;
27
} Sunday, March 23, 2025
Break Statement
 When a case label is matched or the default is executed, execution begins at the first
statement following that label and
 continues until one of the following conditions is met:
1) A break statement occurs
2) The end of the switch block is reached
Note that if none of these conditions are met, cases will overflow into other cases! The
program “falls through” all of the statements below the one with matching case expression
E.g.
switch (2)
{ case 1: // Does not match -- skipped
cout << 1 << endl;
case 2: // Match! Execution begins at the next statement
2
cout << 2 << endl; // Execution begins here
3
case 3:
4
cout << 3 << endl; // This is also executed
5
case 4:
cout << 4 << endl; // This is also executed
// Break;
default:
cout << 5 << endl; // This is also executed}
Sunday, March 23, 2025 28
Break Statement

 Sometimes, you may want the program to “fall-through” statements.


 It is possible to have multiple case labels refer to the same statements.
char feedGrade;
cout << "dog food is available in three grades:\n A, B, and C. Which do you want pricing for?";
cin >> feedGrade;
switch(feedGrade)
{
case 'a':
case 'A':
cout << "30 cents per pound.\n";
break;
case 'b':
case 'B': cout << "20 cents per pound.\n";
break;
case 'c':
case 'C': cout << "15 cents per pound.\n";
break;
default :
cout << "That is an invalid choice.\n";
Sunday, March 23, 2025 29
}
2. Looping

 A loop is a control structure that causes a statement or


group of statements to repeat.
 C++ has three looping control structures: the while loop,
the do-while loop, and the for loop.
 The difference between each of these is how they
control the repetition.

Sunday, March 23, 2025 30


i)While Loop
Syntax :
while (expression/condition )
{
statement;
statement;
// Place as many statements here as necessary
}
The While loop repeat statement until the while expression is false,
Each repetition is known as an iteration

Principle:
Condition of while loop is first executed (pretest loop) and if condition is
TRUE, statement is executed .Then ,condition is evaluated again & if
TRUE, statement is repeated. It loops until the condition comes to be
FALSE. when it ‘s FALSE, it leaves the loop.
31
Sunday, March 23, 2025
While Loop Statement

 (If there is only one statement in the loop


body, the braces may be omitted.)
while (expression/condition)
statement;
Sunday, March 23, 2025 32
Example
#include<iostream>
Using namespace std;
Int main()
{
int i = 0;
while(i<10)
{
cout<<i<<” “;
i++;
}
cout<<”done!”;
}

This outputs:
0 1 2 3 4 5 6 7 8 9 done!
Sunday, March 23, 2025 33
While Loop Statement
 An important characteristic of the while loop is that
the loop will never iterate if the test expression is
false.
 It is possible that a while loop statement executes 0
times.
int i = 15;
while(i<10)
{
cout<<i<<” “;
i++;
}
Sunday, March 23, 2025 34
Example
// Loop through every number between 1 and 50
int i= 1;
while (i<= 50)
{

cout << i<< " "; // print the number

if (i% 10 == 0) // if the loop variable is divisible by 10, print a newline

cout << endl;

i++; // increment the loop counter


}
This program produces the result:
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 Sunday,
42 43March
44 45
23,46 47 48 49 50
2025 35
…cont’
// a program that sums numbers //a program to print even numbers
from one up to 10 between 0 and n
#include<iostream> #include<iostream>
using namespace std; using namespace std;
int main() int main()
{ int n;
{
int i=0;
int n=10, sum=0; Cout<<”enter an integer n:”<<endl;
while(n!=0) Cin>>n;
{ While(i<=n)
sum=sum+n; {
n--; if((i%2)==0)
{
}
Cout<<i<<”is even”<<endl;
cout<<”sum=”<<sum<<endl; }
return 0; i++;
} }
Sunday, March 23, 2025
return 0;
36
}
Infinite Loop
 In all but rare cases, loops must contain within themselves a way
to terminate.
 This means that something inside the loop must eventually make
the test expression false.
 If a loop does not have a way of stopping, it is called an infinite
loop.
 If the test expression always evaluates to true, the while loop will
execute forever until the program is interrupted.
• E.g.
int i = 0;
while(i<10)
{
cout<<i<<” “;
}
Sunday, March 23, 2025 37
cout<<”done!”;
This version of the loop will stop after it has executed 10 times:

int i = 0;
while(i<10)
{
cout<<i<<” “;
i++;
}
cout<<”done!”

Sunday, March 23, 2025 38


Infinite Loop
 Another common pitfall with loops is
accidentally using the = operator when you
intend to use the == operator.

while (remainder = 1) // Error: Notice the assignment.


{
cout << "Enter a number: ";
cin >> num;
remainder = num % 2;
}
Sunday, March 23, 2025 39
ii)Do While Loop
 The do-while loop looks similar to a while loop turned upside
down
 Syntax:
Do
{
statement;
statement;
} while (expression);
 Principle: first Action is executed. Then if the condition in the
while loop is TRUE ,action is repeated and it continues until the
condition gets FALSE.
Sunday, March 23, 2025 40
//program that displays list of integer //a program that checks if a number input is even or
odd and after checking, it asks a user whether to try
from 0 to number n, as: 0,1,2,3,4,5, another number to be checked or not
……….,n.(n is inputted from #include<iostream>
Using namespace std;
keyboard) int main()
#include<iostream> {
using namespace std; int n;
char mychar;
int main() do
{ {
int n ,i=0; Cout<<”enter n:”<<endl;
Cin>>n;
cout<<”enter n:”<<endl; if((n%2)==0)
cin>>n; {
Cout<<n<<”is even”<<endl;
do }
{ else
cout<<i<<”,”<<endl; {
Cout<<n<<”is odd”<<endl;
i++; }
} Cout<<”do you want to try again(y/n)?”<<endl;
Cin>>mychar;
while(i<=n); }
return 0; While((mychar==’y’||(mychar==’Y’)));
} Sunday, March 23, 2025 return 0; 41
}
Do While Loop

 The difference between the do-while loop and the while


loop is that do-while is a post-test loop.
 This means do-while always performs at least one
iteration, even if the test expression is false from the
start.
While Do While
• Ex. int x = 1; int x = 1;
while (x < 0) do
cout << x << endl; cout << x << endl;
while (x < 0);
Never executes Executes once because the
expression x<0 is not
evaluated until the end of the
loop
Sunday, March 23, 2025 42
iii)For loop
Syntax:
for (initialization-statement; test expression; update)
{
statement;
statement;
/*Place as many statements
here as necessary.*/
}

Sunday, March 23, 2025 43


For Statements
 The for loop has three expressions inside the parentheses,
separated by semicolons.
 The first expression is the initialization expression.

 It is typically used to initialize a counter or other variable


that must have a starting value. This is the first action
performed by the loop and it is only done once.
 The second expression is the test expression.

 Like the test expression in the while and do-while loops, it

controls the execution of the loop.


Sunday, March 23, 2025 44
For Statements

 As long as this expression is true, the body of the for


loop will repeat.
 The for loop is a pretest loop, so it evaluates the test
expression before each iteration.
 The third expression is the update expression.
 It executes at the end of each iteration.
 Typically, it increments/decrements a counter or other
variable that must be modified in each iteration.
Sunday, March 23, 2025 45
Example
for(int i = 0; i< 10; i++)
cout << i << " ";
Consequently, this program prints the result:
0123456789
 Programmers love for loops because they are a very compact way to do
loops of this nature
 The above program can be un-compacted into its while-statement
equivalent
int i = 0;
while (i < 10)
{
cout << i << " ";
i++;
Sunday, March 23, 2025 46
}
• Example-1
int main()
{
Out put
for(int x=0;x<10;x++) 0
1
{ 2
3
cout<<x; 4
5
cout<<endl; 6
7
} 8
9
return 0;
}
Sunday, March 23, 2025 47
• Example-2
int main()
{
int sum=0;
for (int x=1;x<=5;x++)
{
sum+=x;
}
cout<<sum;
return 0;
}
Sunday, March 23, 2025 48
#include<iostream> #include<iostream>
using namespace std; using namespace std;
int main() int main()
{ {

int i; int i;
for(i=0;i<100;i+=2) for(i=100;i>0;i--)
cout<<i<<endl; cout<<i<<endl;
return 0;
return 0;
}
}
Sunday, March 23, 2025 49
Multiple Declarations
• Sometimes for loops need to work with multiple
variables.
• When this happens, the programmer can make use of the
comma operator in order to initialize or change the value
of multiple variables: E.g.
for (int i=0, j=9; i < 10; i++, j--)
cout << i << " " << j << endl;

Sunday, March 23, 2025 50


Multiple Declarations

• The previous program produces the result

Sunday, March 23, 2025 51


Nested Loops

 It is also possible to nest loops inside of other loops.


 In the following example, the inner loop and outer loops each have their own
counters.
int i=1;
while (i<=5)
{
int j = 1;
while (j <= i)
{
cout << j;
j++;
}
cout << endl;
i++;
}
Note that the loop expression for the inner loop makes use of the outer loop's counter as well
This program prints:
1
12
123
1 2 3Sunday,
4 March 23, 2025 52
12345
3)Jump statements

i) break statement
when executed within for, while, do…while and switch, it causes an
immediate exit from the loop.
Example:
Out put
for(int i=1;i<=10;i++) 1
{ 2
3
if(i==5) 4
break ;
cout<<i<<endl;
}

 The break statement causes a loop to terminate early.


 The for loop in the following program segment appears to execute 10
Sunday, March 23, 2025 53
ii) continue statement
 when executed within for, while and do…while, the next
iteration is done ignoring the rest of the statements.

Example:
for(int i=1;i<=10;i++) Out put
1
{ 2
3
if(i==5) 4
6
continue; 7
8
cout<<i<<endl; 9
} 10

Sunday, March 23, 2025 54


iii) goto statement
Allows to make an absolute jump to another point in the program, the destination point is

identified by label (valid identifier followed by a colon(:) .


Example:
#include<iostream>
int main ( )
{
int n =10;
loop:
cout << n << “ , “;
n--;
if (n>0) goto loop;
cout<<”End”;
return 0;
}
Sunday, March 23, 2025 55
10 ,9 ,8 ,7, 6, 5,4,3,2,1
Thank You!

Sunday, March 23, 2025 56

You might also like