Chapter 4
Chapter 4
CHAPTER 4
Selection Control Statements
IT 112 – COMPUTER PROGRAMMING 1
Control Structures
Control Structures are just a way to define the control flow of programs. Any algorithm
or program can be more easily understood if it uses self-contained modules called logic or
control structures. It essentially analyzes and selects the direction in which the program flows
on the basis of certain parameters or conditions.
As in real life circumstances, the time comes when we need to make certain choices,
and on the basis of those choices, we decide what we will do next. Different circumstances
occur in programming where we need to make certain decisions, and on the basis of those
decisions, we must execute the next block of code. In this chapter, we will identify the different
fundamental control structures and eventually discuss the different decision control
structures which is very vital in computer programming.
Learning Outcomes:
is score
False True
> 75
Display Display
“Pass” “Failed”
IT 112 – COMPUTER PROGRAMMING 1
Prompt user
to enter a
number
False
is the no
equal to
5
True
▪ if statement
▪ if–else statement
▪ Nested If and Nested If-else statement
▪ switch statements
IT 112 – COMPUTER PROGRAMMING 1
if Statement
The If statement is one of the powerful conditional statements. It is responsible for
changing the program execution flow. The if statement specifies that a statement (of a block
of code/statement) will be executed if and only if a certain boolean statement is true or if the
condition is met. The condition is evaluated first before any statement or block of
statement made within the body of the If statement.
The diagram below presents the flowchart of the if statement.
If-Statement
Flowchart
True Boolean_expression False
Statement
} cout<<“You Passed!”;
}
Note:
● The curly braces { } are optional part of the if statement but is recommended to use
everytime.
● Statements are usually indented inside the if-block.
● The code inside the { } is the body of the if statement.
IT 112 – COMPUTER PROGRAMMING 1
Example:
More Example:
Example 1:
Using an if statement, we create a program that will display the
message “You have a FEVER!” if the temperature is above 37.50.
Code:
float temp = 38;
if (temp>37.50) {
cout << You have a FEVER!”
}
Output:
Example 2:
Using an if statement, change the value of a Boolean variable named
hasFever to true if the given temperature is greater than a variable named
normal_temp.
Code:
boolean hasFever=false;
float normal_temp=37.50;
float temp;
if (temp>normal_temp) {
hasFever=true;
}
3. Position the insertion point after the opening curly brace of the main()method, press
Enter and declare a variable named age with a value of 18.
4. Press Enter at the end of the age variable declaration statement. Create an If
statement by following the if syntax. Type the conditional expression age=>18 as the
Boolean expression of the if statement.
5. Type the statement cout<<”You are of LEGAL AGE”; after the open curly brace of
the if Statement.
IT 112 – COMPUTER PROGRAMMING 1
6. Save the file application and then compile and run the application.
Thinking Box:
Based on our example, what do you think is the output if we change the value
of age from 18 to 15?
IT 112 – COMPUTER PROGRAMMING 1
A. Write program that will ask the user to input their 5 quiz score i.e. 86,95 etc., then compute
the average on the 5 quizzes by adding them and dividing it by 5. Based on the average,
create an if structure that will display the message “Outstanding” if the average computed
is equal or higher than 91.
B. Write program that will ask the user to input their grade for the subjects Math, English and
Filipino. Write separate if conditions based on the following conditions. Display the
message “Isa kang Mathinik!” if the grade in Math is greater than or equal to 90. Display
the message “English is easy for you!” if the grade in English is greater than 89. Display
the message “Makabayang Pilipino” if the grade in Filipino is greater than 88.
IT 112 – COMPUTER PROGRAMMING 1
if-else Statement
Statemen Statemen
t t
Note:
● If the boolean_expression/condition evaluates to true, the code inside the body of if is
executed.
IT 112 – COMPUTER PROGRAMMING 1
As an example, for the if…else structure, we will use the following pseudo code statement:
Display “Passed”
True False
grade=>75
Else
Display “Failed”
Display Display
“Passed” “Failed”
Which prints “Passed” if the student’s
grade equal or greater than 75, but
prints “Failed” if grade is less than 75
IT 112 – COMPUTER PROGRAMMING 1
More examples:
Example 1:
Using an if-else statement, we create a program that will print “Qualified” if
the GWA-General Weighted Average is equal or greater than 87 and will print the
phrase “Sorry, you are not Qualified” if the GWA is less than 87.
Code:
int grade = 84;
if (grade>87) {
cout<<”Qualified”;
} else {
cout<<”Sorry, you are not Qualified”;
}
Output:
Qualified
Example2:
Code:
int n=15;
if ( n > 10) {
cout << "n is greater than 10";
} else {
cout << "n is smaller than 10";
}
Output:
n is greater than 10
IT 112 – COMPUTER PROGRAMMING 1
3. Position the insertion point after the opening curly brace of the main()method, press
Enter and declare a variable named age with a value of 50.
4. Press Enter at the end of the age variable declaration statement. Create an If
statement by following the if syntax. Type the conditional expression (age>=45) as the
Boolean expression of the if statement.
5. Type the statement cout<<”You can run for PRESIDENT!”; after the open curly
brace of the if Statement. After the closing curly brace type the else statement with its
open and curly braces, then position the cursor at the middle of the curly braces. Type
the statement cout<<”You can run anywhere…”;
6. Save the file application and then compile and run the application.
Thinking Box:
Based on our example, what do you think is the output if we change the value
of age from 50 to 40?
IT 112 – COMPUTER PROGRAMMING 1
Nested-If Statement
This lesson introduces the use of Nested-If Statement. The flow of execution for
Nested-If Statement as well as its syntax will be presented. Sample code fragments will
also be presented to demonstrate how Nested-If Statement behaves. Problem sets (Try
Me!) will be given at the end of the lesson to give you time to practice before taking the
assessment tasks. Assessment tasks will be submitted on or before the scheduled date
as specified in the Course Guide.
Learning Outcomes:
Nesting is a theory that places one element inside of another. This means that a
Nested-If statement is simply represented as an If statement placed inside another If
statement.
// outer if statement
if (condition 1) {
// statements
// inner if statements
if (condition 2) {
// statements
}
}
IT 112 – COMPUTER PROGRAMMING 1
The statements inside the block of nested if statement is only executed when:
● the condition of the outer if statement is true, and also
● the condition of the nested if statement is also true.
Where:
● If condition 1 is evaluated TRUE, the statements inside its block will execute. Since, the
inner if statement is part of the code block of the outer if statement, then the execution
will continue to evaluate condition 2.
● If condition 2 is evaluated to TRUE, the statements inside its block will execute then
Nested-if terminates. Otherwise, the Nested-if terminates early.
● If condition 1 is evaluated to FALSE, the Nested-if terminates.
● The inner if statement is what we call the Nested-if Statement.
Note:
● We can add else and else-if statements to the inner if statement as necessary.
● The inner if statement can be inserted inside the outer else or else-if statements.
● We can nest multiple levels of if statements.
// outer if statement
if (condition 1) {
// statements
// inner if statement
if (condition 2) {
// statements
}
else {
// statements
}
}
else {
// statements
}
IT 112 – COMPUTER PROGRAMMING 1
Nested if Flowchart:
TRUE
CONDITION Statements
1
FALS
E TRUE
Nested if
Statements
Condition 2
FALS
END E
FALS
E
Nested if
TRUE Statements
else Condition 2
Statements
FALS
E
else
Statements
END
int main() {
int num;
// outer if condition
if (num != 0) {
// inner if condition
if (num > 0) {
cout << "The number is positive." << endl;
}
// inner else condition
else {
cout << "The number is negative." << endl;
}
}
// outer else condition
else {
cout << "The number is 0 and it is neither positive nor negative." << endl;
}
cout << "This line is always printed." << endl;
return 0;
}
IT 112 – COMPUTER PROGRAMMING 1
Output 1
Enter an integer: 34
The number is even.
This line is always printed.
Output 2
Enter an integer: 35
The number is odd.
This line is always printed.
Output 3
Enter an integer: 0
The number is 0 and it is neither even nor odd.
This line is always printed.
int main()
{
int num1, num2, num3;
return 0;
}
Output
Enter three numbers: 23
8
15
Largest number: 23
IT 112 – COMPUTER PROGRAMMING 1
Switch Statement
This lesson introduces the use of Switch Statement. The flow of execution for
Switch Statement as well as its syntax will be presented. Sample code fragments will also
be presented to demonstrate how Switch Statement behaves. Problem sets (Try Me!) will
be given at the end of the lesson to give you time to practice before taking the assessment
tasks. Assessment tasks will be submitted on or before the scheduled date as specified
in the Course Guide.
Learning Outcomes:
case constant2:
// code to be executed if
// expression is equal to constant2;
break;
.
.
.
default:
// code to be executed if
// expression doesn't match any constant
}
The expression is evaluated once and matched with the values for each case.
● If there is a match, the block of code after the matching case will execute. For
example, if the value of the variable is equal to constant2, the codes inside the
block of case constant2: will execute until the break statement is encountered.
● If there is no match, the codes within the block of default: will execute.
Note: We can do the same with the use if...else…if statement. Though, the syntax of
the switch statement is much easier to read and write.
● The variable used in a switch statement can only be a short, byte, int or char data type.
The values for each case and the variable must have the same data types.
● The expression in the switch statement should result to a constant value.
● Identical case values are not valid.
● The default statement is optional. The switch case statement would still run
without any problem.
● The break statement is used terminate the switch statement sequence. If the
break statement is reached, the switch statement terminates, and the flow of
control jumps to the next line of statement after end of the switch statement.
IT 112 – COMPUTER PROGRAMMING 1
● The break statement is also optional. If removed, execution will continue on into
the next case. The flow of control will continue through the succeeding cases until
a break statement is reached.
● Nested switch statements are allowed. However, it makes program more complex
and less readable.
Switch Flowchart:
Switch
Expression
TRUE
Case Statements
1 Break
FALSE Statement
TRUE
Case Statements
2 Break
FALSE Statement
TRUE
Case Statements
3 Break
FALSE Statement
Default
Statements
END
int main() {
int number;
cout << "Enter a number (1-5): ";
cin >> number;
switch (number) {
case 1:
cout << "You entered 1" <<;
break;
case 2:
cout << "You entered 2" <<;
break;
case 3:
cout << "You entered 3" <<;
break;
case 4:
cout << "You entered 4" <<;
break;
case 5:
cout << "You entered 5" <<;
break;
default:
// number doesn't match any case constant (1-5)
cout << "The number you entered is out of range!";
break;
}
return 0;
}
Output 1
Output 2
Output 3
int main() {
char letter;
cout << "Select a character(a,b,c): ";
cin >> letter;
switch (letter) {
case ‘a’:
cout << "a is for Apple" <<;
break;
case ‘b’:
cout << "b is for Banana" <<;
break;
case ‘c’:
cout << "c is for Cherry" <<;
break;
default:
// letter doesn't match any case constant (a, b, c)
cout << "Sorry! The letter you entered is out of selection!";
break;
}
return 0;
}
Output
Select a character(a,b,c): b
b is for Banana
IT 112 – COMPUTER PROGRAMMING 1
if (x != 0) {
if (x > 50) {
x = x * 100;
cout << x << endl;
}
else {
x = x - 10;
cout << x << endl;
}
}
else {
x = x + 50;
cout << x << endl;
}
switch (z) {
case 1:
z = (z + 10) * 25;
cout << x <<;
break;
case 2:
z = z - 10;
cout << x + 30 <<;
break;
case 3:
z = z - 10;
cout << z <<;
break;
default:
cout << z * z <<;
break;
}
IT 112 – COMPUTER PROGRAMMING 1
B. Programming Exercise
1. Write a program that will ask the user to enter an integer. Display a statement that
indicates whether the integer is even, odd, or zero. Use nested-if statement.
2. Write a switch statement program that will output the following. The user then enters a
valid integer from the selection and the program should output the originating country of
the manufacturer. Use a default statement if the user enters an invalid selection.
Bentley – United Kingdom
Audi – Germany
Bugatti – France
Koenigsegg – Sweden
Maserati – Italy
Output
Assessment Task
A. Evaluate the output of the given code fragments.
1. What is the output if:
a. k = 856
b. k = 0
c. k = 23
if (k > 0) {
if (k > 50) {
if (k < 500) {
k = k * 100;
cout << k << endl;
}
}
else {
k = k - 10;
cout << k << endl;
}
}
else {
k = k + 500;
cout << x << endl;
}
switch (z) {
case 1:
c = (c + 10) - 80;
cout << c <<;
case 2:
c = c - 10;
cout << c + 30 <<;
case 3:
c = c - 10;
cout << c <<;
default:
cout << c * c <<;
break;
}