You are on page 1of 53

Selection statements

Chapter 2

1
Program control flow statements
• A program consists of a number of statements
which are usually executed in sequence. This
is called sequential execution. Various C
statements enable you to specify that the next
statement to be executed may be other than the
next one in sequence. This is called transfer of
control.
• This chapter will discuss the use of control
statements in C.

2
The “ if ” statement
• This is used to decide whether to do something
at a special point, or to decide between two
courses of action. The code inside if body
executes only when the condition defined by if
condition (boolean expression) is true. If the
condition is false then compiler skips the
statement enclosed in if’s body.

3
Example of using if condition
• suppose the passing grade on an exam is 60. The
program determines if the condition “student’s
grade is greater than or equal to 60” is true or
false. If the condition is true, then “Passed” is
printed, and the next program statement in order
is “performed”. If the condition is false, the
printing is ignored, and the next program
statement in order is performed.
if ( grade >= 60 ) cout << "Passed\n" ;
cout << “Byebye\n”;
4
If-else statement
• Here, we have two blocks of statements. If
condition results true then statements
in if block gets execution otherwise statements
in else block gets execution. Note that, else
statement cannot exist without if statement.

5
if (condition) statement1 ;
else statement2 ;
statement3;
• Here, condition is the Boolean expression that
is being evaluated. If this condition is true,
statement1 will be executed and statement2
will be ignored. If it is false, statement1 will be
ignored, and statement2 will be executed. After
that, in both cases, statement3 will be
executed.

6
Example
if (grade >= 50) cout << "Pass\n";
else cout << "Fail\n";
cout << “Byebye\n”;

7
The if block
• If we wish to have more than one statement following
the if or the else, they should be grouped together
between curly brackets. Such a grouping is called a
compound statement or a block.
• if( boolean-expression )
{
statements;
}
else
{
statements;
}
8
Example of if block
if (result >= 50)
{
cout << "Passed\n";
cout <<"Congratulations\n";
}
else
{
cout << "Failed\n";
cout << "Good luck in the next time\n";
}
9
Nested if-else
• Sometimes we wish to make a multi-way decision
based on several conditions. The most general
way of doing this is by using nested if…else
statements.
• Nested if…else statements test for multiple cases
by placing if…else statements inside if…else
statements. This works by cascading several
comparisons. As soon as one of these gives a true
result, the following statement or block is
executed, and no further comparisons are
performed.
10
Example of nested if-else

if (x > 0) cout << "x is positive";


else if (x < 0) cout << "x is negative";
else cout << "x is 0";

This prints whether x is positive, negative, or


zero by concatenating two if-else structures.

11
Example: print grade depending on
exam score
if (result >= 90) cout << "Grade A\n";
else if (result >= 80) cout << "Grade B\n";
else if (result >= 70) cout << "Grade C\n";
else if (result >= 60) cout << "Grade D\n";
else if (result >= 50) cout << "Grade E\n";
else cout << “Grade F\n";

12
Example: print grade depending on
exam score
if (result >= 90) cout << "Grade A\n";
else if (result >= 80) cout << "Grade B\n";
else if (result >= 70) cout << "Grade C\n";
else if (result >= 60) cout << "Grade D\n";
else if (result >= 50) cout << "Grade E\n";
else cout << “Grade F\n";

13
The switch Statement
• When you use a series of if or if-else
conditionals on the same variable, your C++
code can become excessively confusing. An
alternative is to use switch, a conditional that
tests one expression for multiple values to
decide which of several blocks of code to
execute. This is another form of the multi way
decision.

14
It is well structured, but can only be used in certain
cases where;
1. Only one variable is tested, all branches must
depend on the value of that variable. The
variable must be an integral type. (int, long,
short or char).
2. Each possible value of the variable can control a
single branch. A final, catch all, default branch
may optionally be used to trap all unspecified
cases.
15
• A switch statement consists of the keyword switch
followed by an expression to test, one or more
case sections with possible values of that
expression, and possibly a default section when
no case matches.
• The evaluation in the case sections of a switch
statement can be only for equality. There’s no way
to test relational operators or Boolean operations.
If one of the case values matches the expression,
execution jumps to those statements and
continues to the end of the switch block unless a
break statement is encountered. If nothing
matches, execution branches to the optional
default statement.
16
• Break statements are needed after each group
of statements for a particular label. If break is
not included, all statements following the case
(including those under any other labels) are
also executed, until the end of the switch block
or a jump statement (such as break) is reached.

17
Switch format
switch( x )
{
case x1:
group statements1;
break;
case x2:
group statements2;
break;
case x3:
group statements3;
break;
default:
group statements4;
break;
}

18
Comparison between if and switch
switch example if-else equivalent

switch (x) if (x == 1)
{ { cout << “One";}
case 1: cout << “One"; break; else if (x == 2)
case 2: cout << “Two"; break; { cout << “Two";}
default: cout << “Unknown"; else
} {cout <<“Unknown";}

19
break statement in switch
switch(number)
{
case 0 : cout << "None\n"; break;
case 1 : cout << "One\n"; break;
case 2 : cout << "Two\n"; break;
case 3 :
case 4 :
case 5 : cout << "Several\n"; break;
default : cout << "Many\n"; break;
}
20
Conditional Operator ?:
• The conditional operator (?:) is another form
of a double selection statement. It also allows
for performing one action when a condition is
true and another when the condition is false. A
conditional expression is written as follows:

Condition? Action when true : Action when false ;

21
Problem 1
Show an algorithm, draw a flowchart, and write
a C++ program to read 2 integer numbers and
print the value of the bigger one.

22
The algorithm
Read first number
Read second number
if first_number > second_number
then bigger ← first_number
else bigger ← second_number
endif
write “Bigger number=” bigger

23
24
int main(void)
{
int firstNum, second_num, bigger_num;
cout << "Please, enter the first number: ";
cin >> firstNum;
cout << "Please, enter the second number: ";
cin >> second_num;
if (firstNum > second_num)
{ bigger_num = firstNum; }
else
{ bigger_num = second_num; }
cout << "The bigger value = " << bigger_num << "\n";
return 0;
} 25
• The previous flowchart and program do not
consider the case if the two numbers are equal.
The following flowchart and program are
modified to take into consideration the case of
equality of the two numbers

26
27
int main(void)
{
int first_num, second_num;
cout << "Please, enter the first number: ";
cin >> first_num;
cout << "Please, enter the second number: ";
cin >> second_num;

28
if (first_num > second_num)
cout << “Bigger = " << first_num << "\n";
else if (second_num > first_num)
cout << “Bigger = " << second_num << "\n";
else
cout << "Equal numbers \n ";
return 0;
}

29
Problem 2
Draw a flowchart and write an algorithm and a
program to read 3 numbers and print the
maximum one.

30
31
Start
Read three numbers a, b, and c
if(a > b)
then if(a > c )
then max ← a
else max ← c
endif
else
if(b > c)
then max ← b
else max ← c
endif
endif
print max
end
32
int main(void)
{
int a, b, c, max;
cout << "Enter 3 integer numbers: ";
cin >> a >> b >> c;
if (a > b)
{
if (a > c) max = a;
else max = c;
}
else
{
if (b > c) max = b;
else max = c;
}
cout << "The maximum number = " << max << "\n";
return 0;
}
33
34
Start
Read three numbers a, b, and c
if(a > b) and (a > c)
then max ← a
else if(b > c) max ← b
else max ← c
endif
endif
print max
end

35
int main(void)
{
int a, b, c, max;
cout << "Enter 3 integer numbers: ";
cin >> a >> b >> c;
if ((a > b) && (a > c)) max = a;
else if (b > c) max = b;
else max = c;
cout << "The maximum = " << max << "\n";
return 0;
}
36
Problem 3
Draw a flowchart and write a program to make a
simple calculator. The program will ask the user
to enter 2 numbers and the operation symbol (+,
-, *,or /). Then, the program will perform the
required operation on the two numbers and print
the result.

37
38
Using if statement
int main(void)
{
float first, second, result;
char symbol;
cout << "Enter first number: ";
cin >> first;
cout << "Enter operation symbol ( * , / , + , or - ): ";
cin >> symbol;
cout << "Enter second number: ";
cin >> second;

39
if (symbol == '+') result = first + second;
else if (symbol == '-') result = first - second;
else if (symbol == '*') result = first * second;
else if (symbol == '/')
{
if (second == 0)
{ cout << "You can not divide by zero\n"; return 1; }
else result = first / second;
}
else { cout << “Wrong operation symbol \n"; return 2; }
cout << "Result of " << first << symbol << second << " = "
<< result << "\n";
return 0;
}

40
switch (symbol)
{
case '+': result = first + second; break;
case '-': result = first - second; break;
case '*': result = first * second; break;
case '/': if (second == 0)
{ cout << "You can not divide by zero\n"; return 1; }
else result = first / second; break;
default: cout << “Wrong operation \n"; return 2;
}
cout << "Result of " << first << symbol << second << " =
" << result << "\n";
return 0;
}

41
Problem 4
• Write a program to read a positive integer
number (less than 10) and print its value in
alphabetic

42
void main(void)
{
int the_entered_number ;
cout << "Enter a positive integer value less than 10: ";
cin >> the_entered_number ;
cout << "You entered ";
if(the_entered_number == 1) cout << "one";
else if(the_entered_number == 2) cout << "two";
else if(the_entered_number == 3) cout << "three";
else if(the_entered_number == 4) cout << "four";
else if(the_entered_number == 5) cout << "five";
else if(the_entered_number == 6) cout << "six";
else if(the_entered_number == 7) cout << "seven";
else if(the_entered_number == 8) cout << "eight";
else if(the_entered_number == 9) cout << "nine";
else cout << " wrong number";
cout << "\n";
}

43
void main(void)
{
int the_entered_number ;
cout << "Enter a positive integer value less than 10: ";
cin >> the_entered_number ;
cout << "You entered ";
switch(the_entered_number)
{
case 1 : cout << "one"; break ;
case 2 : cout << "two"; break ;
case 3 : cout << "three"; break ;
case 4 : cout << "four"; break ;
case 5 : cout << "five"; break ;
case 6 : cout << "six"; break ;
case 7 : cout << "seven"; break ;
case 8 : cout << "eight"; break ;
case 9 : cout << "nine"; break ;
default: cout << " wrong number";
}
}

44
Problem 5
Write a C++ program to read a number which
represents a month number, and print the
corresponding season name according to the
following table.
Month 12, 1, 2 3, 4, 5 6, 7, 8 9, 10, 11
number

Season Winter Spring Summer Fall


name 45
int main(void)
{
int month;
cout << "Please enter month number: ";
cin >> month;
if ((month < 1) || (month > 12))
{ cout << "Wrong month number"; return 1; }
else if ((month == 12) || (month <= 2))
cout<< "Winter \n";
else if (month <= 5) cout << “Spring \n";
else if (month <= 8) cout << "Summer \n";
else if (month <= 11) cout << "Fall \n";
return 0;
}
46
int main(void)
{
int month;
cout << "Please enter month number: ";
cin >> month;
switch (month)
{
case 12:
case 1:
case 2: cout << "Season is Winter \n"; break;
case 3:
case 4:
case 5: cout << "Season is Spring \n"; break;
case 6:
case 7:
case 8: cout << "Season is Summer \n"; break;
case 9:
case 10:
case 11: cout << "Season is Fall \n"; break;
default: cout << "Wrong month number \n";
}
return 0;
}
47
Problem 6
Write a program to read an integer number, then
print if this number is odd or even.

48
void main(void)
{
int num , k ;
cout << "Please enter an integer number: ";
cin >> num ;
k = num % 2 ;
if(k == 0) cout << "Even number\n";
else cout << "Odd number\n";
}

49
Problem 7
Write a program to read 2 numbers and store
them in a, and b. If a < b, exchange (swap) the
numbers. Then print values of a and b.

50
void main(void)
{
int a , b , temp ;
cout << "Please enter 2 integer numbers: ";
cin >> a >> b ;
if(a < b)
{ temp = a ; a = b ; b = temp ; }
cout << a << "\t" << b << "\n" ;
return ;
}

51
int x = 7 ;
if(x < 3) ; x += 5 ;
cout << x ;
52
• double y;
• y = 3.5 + 5 / 2 * 4;
• cout << y;

53

You might also like