0% found this document useful (0 votes)
15 views61 pages

Chapter 3 Controls & Decisions3

It's a course module for freshman students , computer programming mainly c++ for chapter four notes and examples.

Uploaded by

bamnetesfaye
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)
15 views61 pages

Chapter 3 Controls & Decisions3

It's a course module for freshman students , computer programming mainly c++ for chapter four notes and examples.

Uploaded by

bamnetesfaye
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/ 61

Chapter 3

Controls & Decisions

Tuesday, May 20, 2025 1


So Far…
The C++ programs we have been writing so
far have been executing sequentially

Statement 1 int n, temp, ans;

Statement 2 cout<<“Enter number: “;


. .
. .
. .
Statement n-1 cout<<“The answer is “<<ans;

Statement n return 0;
Tuesday, May 20, 2025 2
Flow of Control
• A program is usually not limited to a linear
sequence of instructions. During its process it
may repeat code (Looping) or take
decisions/select (selection . For that purpose,
C++ provides control structures that serve to
specify what and how have to perform our
program.

Tuesday, May 20, 2025 3


1.Decisions/ Selection (if, if…else, switch)

• Using decision or selection statement, we


select one block of code based on certain
conditions.

Tuesday, May 20, 2025 4


i ) If statements
• An if statement has two forms: one with an else branch and one
without
A test expression that
i) if statement (single selection) evaluates to a boolean value
Syntax: (either true or false)

If(expression or condition)
{ A single statement or a
//code/statement(s) compound statement, to be
} executed if condition
evaluates to true.

If the condition is true, the statement is executed, otherwise it is


skipped.

Tuesday, May 20, 2025 5


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
Tuesday, May 20, 2025 6
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;
Tuesday, May 20, 2025 7
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
}
Tuesday, May 20, 2025 8
Example 1
Note: the if and else statements executed a single statement if the condition is
true or false

Tuesday, May 20, 2025 9


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

Tuesday, May 20, 2025 10


Flowchart equivalents

Tuesday, May 20, 2025 11


The Conditional Operator
• Is another short-hand method of expressing
if…else statements.
Syntax:
condition ? expression1 : expression2;

An expression Expression to Expression to


that evaluates execute if condition execute if condition
to a boolean. evaluates to true. evaluates to false.

Tuesday, May 20, 2025 12


Example
(x < y) ? x = 10 : y = 10;

//this is the same as


if (x < y)
x = 10;
else
y = 5;

Tuesday, May 20, 2025 13


iii) Nested if …else statements
If(expression)
statement1
else
statement2
Note that: statement1 and statement 2 can be
any statement including if… else statement

Tuesday, May 20, 2025 14


Nested if …else statements
E.g. when statement 2 itself is again another if…else statement

Tuesday, May 20, 2025 15


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

else if (conditionN-1)
statementN-1
else
statementN
Tuesday, May 20, 2025 16
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;
Tuesday, May 20, 2025 17
//This program illustrates a bug that occurs when independent if/else statements are used to
assign a letter grade to a numeric test score.
#include <iostream>
using namespace std;
int main()
{
int testScore; char grade;
cout << "Enter your numeric test score and I will\n "tell you the letter grade you earned:
";
cin >> testScore;
if (testScore < 60)
Program Output with Example Input Shown in
grade = 'F'; Bold
if (testScore < 70) Enter your numeric test score and I will tell you
grade = 'D'; the letter grade you earned: 40[Enter]
if (testScore < 80) Your grade is A.
grade = 'C';
if (testScore < 90)
grade = 'B';
if (testScore <= 100)
grade = 'A';
cout << "Your grade is " << grade << ".\n";
Tuesday, May 20, 2025
return 0; 18
}
//It can be corrected like this
#include <iostream>
using namespace std;
int main()
{
int testScore; char grade;
cout << "Enter your numeric 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
Bold
else if (testScore < 70)
Enter your numeric test score and I will tell you
grade = 'D';
the letter grade you earned: 40[Enter]
else if (testScore < 80) Your grade is F.
grade = 'C';
else if (testScore < 90)
grade = 'B';
else if (testScore <= 100)
grade = 'A';
cout << "Your grade is " << grade << ".\n";
return 0; 20, 2025
Tuesday, May 19
Dangling else/ matching else problem

The above program introduces a source of potential ambiguity


called a dangling else problem

Tuesday, May 20, 2025 20


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

Tuesday, May 20, 2025 21


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

Tuesday, May 20, 2025 22


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

Tuesday, May 20, 2025 23


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

Tuesday, May 20, 2025 24


6. Write an if-else statement that outputs
the word High if the value of the variable
score is greater than 100 and Low if the
value of score is at most 100. The variable
score is of type int.

Tuesday, May 20, 2025 25


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 choosing among a
set of mutually exclusive choices, C++provides
the switch statement.

Tuesday, May 20, 2025 26


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
Tuesday, May 20, 2025 27
statement
The Switch Statement
• The switch expression is evaluated to produce a
value,
• and each case label is tested against this value
for equality.
• If a case label matches, the statements after
the case label are executed.
• If no case label matches the switch expression,
the code under the default label is executed (if
it exists).
Tuesday, May 20, 2025 28
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 0; }

Tuesday, May 20, 2025 29


The switch statement
int x; • Note that the expressions
cout<<”Enter a number”; of each case statement in
cin>>x; the block must be unique.
switch (x)
{
• That is , you can’t do this
case 1:cout<<”You Entered 1:”; Switch(x)
break; {
case 2:cout<<”You Entered 2:”;
case 4:
break;
…..
case 3:cout<<”You Entered 3:”;
case 4://illegal…already used
break;
value 4
default: cout<<”Invalid Input:”;
……
break; }
default:
}
Tuesday, May 20, 2025 30
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 or break statement. 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;
31
} Tuesday, May 20, 2025
Break Statement
• When a case 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 true:
1) The end of the switch block is reached
2) A break statement occurs
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
cout << 2 << endl; // Execution begins here 2
case 3: 3
cout << 3 << endl; // This is also executed 4
case 4: 5
cout << 4 << endl; // This is also executed
// Break;
default:
cout << 5 << endl; // This is also executed
}
Tuesday, May 20, 2025 32
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.
• E.g.

char feedGrade;
cout << "Our 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 :
Tuesday, May 20, <<
cout 2025
"That is an invalid choice.\n"; 33
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.

Tuesday, May 20, 2025 34


i)While Loop
• Syntax :
while (expression/condition )
{
statement;
statement;
// Place as many statements here as necessary
}
and its function is simply to repeat statement while expression is true, 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. 35
Tuesday, May 20, 2025
While Loop Statement

• (If there is only one statement in the loop


body, the braces may be omitted.)
while (expression)
statement;
Tuesday, May 20, 2025 36
Example
int i = 0;
while(i<10)
{
cout<<i<<” “;
i++;
}
cout<<”done!”;
This outputs:
0 1 2 3 4 5 6 7 8 9 done!
Tuesday, May 20, 2025 37
While Loop Statement
 An important characteristic of the while loop is that the
loop will never iterate if the test expression is false to
start with.
• It is possible that a while statement executes 0 times.
int i = 15;
while(i<10)
{
cout<<i<<” “;
i++;
}
Tuesday, May 20, 2025 38
Example-2
// Loop through every number between 1 and 50
int i= 1;
while (i<= 50)
{
// print the number
cout << i<< " ";

// if the loop variable is divisible by 10, print a newline


if (i% 10 == 0)
cout << endl;

// increment the loop counter


i++;
}
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 Tuesday,
42 43 44 May 20, 2025
45 46 47 48 49 50 39
…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;
int main()
using namespace std;
{ int n;
int main() int i=0;
{ Cout<<”enter an integer n:”<<endl;
int n=10, sum=0; Cin>>n;
while(n!=0) While(i<=n)
{ {
if((i%2)==0)
sum=sum+n;
{
n--; Cout<<i<<”is even”<<endl;
} }
cout<<”sum=”<<sum<<endl; i++;
return 0;} }
Tuesday, May 20, 2025
return 0;
40
}
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<<” “;
}
Tuesday, May 20, 2025 cout<<”done!”; 41
This version of the loop will stop after it has executed 10 times:

int i = 0;
while(i<10)
{
cout<<i<<” “;
i++;
}
cout<<”done!”
Tuesday, May 20, 2025 42
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;
}
Tuesday, May 20, 2025 43
ii)Do While Loop

• The do-while loop looks similar to a while loop


turned upside down
Do
{
statement;
statement;
} while (expression);
• Principle: first Action is executed. Then if the
condition is while is TRUE ,action is repeated
and it continues until the condition gets FALSE
Tuesday, May 20, 2025 44
//program that displays list of integer//a program that checks if a number input was even
or odd and after checking, it asks a user whether to
from 0 to number n, as: 0,1,2,3,4,5, try another number to be checked or not
……….,n.(n is inputted from keyboard)#include<iostream>
Using namespace std;
#include<iostream> int main()
using namespace std; {
int main() int n;
char mychar;
{ do
int n ,i=0; {
cout<<”enter n:”<<endl; Cout<<”enter n:”<<endl;
Cin>>n;
cin>>n; if((n%2)==0)
do {
Cout<<n<<”is even”<<endl;
{ }
cout<<i<<”,”<<endl; else
i++; {
Cout<<n<<”is odd”<<endl;
} }
while(i<=n); Cout<<”do you want to try again(y/n)?”<<endl;
Cin>>mychar;
return 0; }
} While((mychar==’y’||(mychar==’Y’)));
Tuesday, May 20, 2025 return 0; 45
}
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
Tuesday, May 20, 2025 46
iii)For loop
Syntax
for (init-statement; test; update)
{
statement;
statement;
// Place as many statements
// here as necessary.
}

Tuesday, May 20, 2025 47


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.
Tuesday, May 20, 2025 48
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 a counter or other
variable that must be modified in each
iteration.
Tuesday, May 20, 2025 49
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 previous program can be un-compacted into its while-statement
equivalent
int i = 0;
while (i < 10)
{
cout << i << " ";
i++;
Tuesday, May 20, 2025 50
}
• Example-1
int main()
{
for(int x=0;x<10;x++) Out put
0
1
{ 2
3
cout<<x; 4
5
cout<<endl; 6
7
} 8
9
return 0;
}
Tuesday, May 20, 2025 51
• Example-2
int main()
{
int sum=0;
for (int x=1;x<=5;x++)
{
sum+=x;
}
cout<<sum;
return 0;
}
Tuesday, May 20, 2025 52
//For looping #include<iostream>
#include<iostream> using namespace std;
using namespace std; int main()
int main()
{
{

int i;
for(i=0;i<100;i+=2) int i;
cout<<i<<endl; for(i=100;i>0;i--)
return 0; cout<<i<<endl;
} return 0;
}
Tuesday, May 20, 2025 53
Multiple Declarations
• Although for loops typically iterate over only
one variable, 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;
Tuesday, May 20, 2025 54
Multiple Declarations
• The previous program produces the result

Tuesday, May 20, 2025 55



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.
// Loop between 1 and 5
int i=1;
while (i<=5)
{
// loop between 1 and i
int j = 1;
while (j <= i)
cout << j++;

// print a newline at the end of each row


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 3 4 May 20, 2025
Tuesday, 56
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
if(i==5) 3
break ; 4
cout<<i<<endl;
}

 The break statement causes a loop to terminate early.


 The for loop in the following program segment appears to execute 10
times, but the break statement causes it to stop after the fourth
iteration.
Tuesday, May 20, 2025 57
continue statement
• when executed within for, while and do…while, the
next iteration is done ignoring the rest of the
statements

Example: Out put


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

}
Tuesday, May 20, 2025 58
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.h>
int main ( )
{
int n =10;
loop:
cout << n << “ “;
n--;
if (n>0) goto loop;
cout<<”End”;
return 0;
}
10 ,9 ,8 ,7, 6, 5,4,3,2,1
Tuesday, May 20, 2025 59
How to solve problem
Develop the algorithm.
Convert to cpp code.
Check the result.
Example:
1) Prime number;
2) Grading system;
3) Simple calculator; etc

Tuesday, May 20, 2025 60


Thank You!

Tuesday, May 20, 2025 61

You might also like