0% found this document useful (0 votes)
27 views

Chapter 4

Uploaded by

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

Chapter 4

Uploaded by

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

IT 112 – COMPUTER PROGRAMMING 1

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.

This chapter discusses the following in general:

● Fundamental Program Structures


● Decision Control Structures

Learning Outcomes:

At the end of the lesson, you are expected to:


• Identify the different fundamental control program structures
• Identify the form and structure of If Statement
• Apply the use of If statement using conditional operators;
• Identify the form and structure of If-else Statement
• Apply the use of If-else statement using conditional operators;
• Create programs using if and if-else statements
IT 112 – COMPUTER PROGRAMMING 1

Start your lesson here.

Fundamental Control Structures


Programmers often use a flowchart, a tool that helps them plan a program’s logic in
diagram form, as a series of shapes connected by arrows. Shown below are the three
fundamental control structures in programming depicted using a flowchart.

There are three fundamental control structures:

● Sequence Control Structure: This refers to the line-by-line execution in which


the statements are sequentially executed in the same order in which they
appear in the script without branching off in another direction. They might, for
example, perform a series of read or write operations, arithmetic operations, or
variable assignments or in sequential flow as the code is written from top to
bottom.
Prompt the user to
enter first number

Prompt the user to


enter second number

Get the sum of the


two numbers

● Decision Control Structures: A structure that allows various parts of the


program to be executed, depending on the exact situation wherein the
decisions are typically regulated whether a condition is true or false. The
decision control structure may skip the execution of an entire block of
statements or even execute one block of statements instead of another.

is score
False True
> 75

Display Display
“Pass” “Failed”
IT 112 – COMPUTER PROGRAMMING 1

● Loop Control Structure: This is a control structure that allows multiple


executions of a block of statements until a specified condition is met.

Prompt user
to enter a
number
False

is the no
equal to
5

True

Decision Control Structures


These are program structures also known as conditional structures. It simply involves
a number of conditions or parameters which decides one out of several written modules/block
of codes to be executed while skipping other sections.

There are three basic types of decision control structures:

▪ 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

The if-statement has the form/syntax Code Example:


if (boolean_expression) int grade = 78;
statement; if (grade > 75) {
//body of if statement cout<<“You Passed!”;
--OR--
if (boolean_expression) { int grade = 78;
if (grade > 75) {
statement1;
statement2; cout<<“Congratulations!”;

} 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

● The if statement evaluates the boolean_expression inside the parenthesis ( ) before


executing any code or block of codes/statements inside the body of the if statement
● The boolean_expression part of a statement should evaluate to a boolean value which
is either true or a false before executing some statement/s.
● If the boolean_expression/condition evaluates to true, the code inside the body of if is
executed.
● If the boolean_expression/condition evaluates to false, the code inside the body of if is
skipped.

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:

You have a FEVER!


IT 112 – COMPUTER PROGRAMMING 1

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

Lab Exercise : Using if statement

Write a program that uses if structure:


1. Open the Dev C++ IDE, if necessary.

2. Create a new project named if_exercise1

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.

int age = 19;

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.

7. The output should appear as shown in Figure below.

Figure 4.x Output of the If_exercise program


IT 112 – COMPUTER PROGRAMMING 1

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

Lab Exercise 4.1 : Using if statement

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

The if-else statement is used when we want to execute a certain statement if a


condition is true, and a different statement if the condition is false. If the value of
boolean_expression is evaluated to true, then the true block of statements will be
executed. If the value of boolean_expression if false, then the false block of statements
will be executed. In any case, after the execution, the control will be automatically
transferred to the statements appearing outside the block of the If statement.

Shown below is the flowchart of the if-else statement.


If-Else Statement Flowchart

True boolean_expression False

Statemen Statemen
t t

The if-else statement has the Code Example:


form/syntax
if (boolean_expression){ int gwa = 87;
statement; if (gwa > 84){
//executes this block if cout<<“You are Qualified!”;
the condition is true } else {
} else { cout<<“Sorry! You are not Qualified!”;
statement; }
//executes this block if the
condition is false
}

Note:
● If the boolean_expression/condition evaluates to true, the code inside the body of if is
executed.
IT 112 – COMPUTER PROGRAMMING 1

● If the boolean_expression/condition evaluates to false, the code inside the body


of else is executed.

As an example, for the if…else structure, we will use the following pseudo code statement:

If student’s grade is greater than or


equal to 75

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

Lab Exercise 4.2 : Using if-else statement

Write a program that uses if-else structure:


Problem: Create a program that will display the message “Qualified Voter” if the age is
greater than or equal to 18 otherwise display the message “Not Qualified Voter” based on
a given age.

1. Open the Dev C++ IDE, if necessary.

2. Create a new project named if_exercise2

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.

int age = 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…”;

Figure 4.x Code for If_exercise2 program


IT 112 – COMPUTER PROGRAMMING 1

6. Save the file application and then compile and run the application.

7. The output should appear as shown in Figure below.

Figure 4.2 Output of the If_exercise2 program

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:

At the end of the lesson, you are expected to:


Evaluate the output of code fragments having Nested-If Statements
Create programs using Nested-If Statements

Start your lesson here.

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.

The syntax Nested-If statement is:

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

Figure 1. Nested if statement

CONDITION TRUE Statements


1

FALS
E
Nested if
TRUE Statements
else Condition 2
Statements
FALS
E
else
Statements

END

Figure 2. Nested if statement with else clause


IT 112 – COMPUTER PROGRAMMING 1

C++ Nested-if Example


// C++ program to find if an integer is positive or negative or neither (0)
// using nested if statements
#include <iostream>
using namespace std;

int main() {
int num;

cout << "Enter an integer: ";


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

In the above example,


● We take an integer as an input from the user and store it in the variable num.
● We then use an if...else statement to check whether num is not equal to 0.
o If true, then the inner if...else statement will execute.
o If false, the code inside the outer else condition will execute, which prints "The
number is 0 and neither positive nor negative."
● The inner if...else statement checks whether the input number is greater than 0.
o If true, then it will print a statement saying that the number is positive.
o If false, it will print that the number is negative.
IT 112 – COMPUTER PROGRAMMING 1

This time, try the given C++ program.


#include <iostream>
using namespace std;

int main()
{
int num1, num2, num3;

cout << "Enter three numbers: ";


cin >> num1 >> num2 >> num3;

if (num1 >= num2)


{
if (num1 >= num3)
cout << "Largest number is " << num1;
else
cout << "Largest number is " << num3;
}
else
{
if (num2 >= num3)
cout << "Largest number is " << num2;
else
cout << "Largest number is " << 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:

At the end of the lesson, you are expected to:


• Identify the use of switch statements
• Explain and apply the syntax of switch statement
• Create programs using Switch Statements
• Evaluate the output of code fragments having Switch Statements

Start your lesson here.

A switch statement is used evaluate the value of a variable or integer


expression and compare into a list of constant values, also known as a case. If the value
matches to one of the cases, the statements within the block of that case will execute. A
break statement terminates the switch case statement. The default case (optional) is
used if the value of a variable does not match any of the cases.
IT 112 – COMPUTER PROGRAMMING 1

The syntax Switch statement is:


switch (variable or expression) {
case constant1:
// code to be executed if
// expression is equal to constant1;
break;

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.

Rules of Switch Statement

● 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

Figure 1. Switch statement


IT 112 – COMPUTER PROGRAMMING 1

C++ Switch Statement Example:


// Program to illustrate the use of switch Statement
#include <iostream>
using namespace std;

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

Enter a number (1-5): 3


You entered 3
IT 112 – COMPUTER PROGRAMMING 1

Output 2

Enter a number (1-5): 5


You entered 5

Output 3

Enter a number (1-5): 36


The number you entered is out of range!

In the above example,


● We take an integer as an input from the user and store it in the variable number.
● We then use the Switch statement to match the value of number to the list of
cases.
o If the user enters 1, codes within case 1 will execute. Thus, it will display the
message “You entered 1” then break; exits the switch statement.
o If the user enters 2, codes within case 2 will execute. Thus, it will display the
message “You entered 2” then break; exits the switch statement.
o If the user enters 3, codes within case 3 will execute. Thus, it will display the
message “You entered 3” then break; exits the switch statement.
o If the user enters 4, codes within case 4 will execute. Thus, it will display the
message “You entered 4” then break; exits the switch statement.
o If the user enters 5, codes within case 5 will execute. Thus, it will display the
message “You entered 5” then break; exits the switch statement.
o If the user enters a number outside the range of 1-5, codes within default: will
execute. Thus, it will display the message “The number you entered is out of
range!” then break; exits the switch statement.
IT 112 – COMPUTER PROGRAMMING 1

This time, try the given C++ program.


#include <iostream>
using namespace std;

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

A. Evaluate the output of the given code fragments.

1. What is the output if:


a. x = 67
b. x = 0
c. x = -50

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

2. What is the output if:


a. z = 1
b. z = 2
c. z = 5

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

Car Brands Manufacturer


1. Bentley
2. Audi
3. Bugatti
4. Koenigsegg
5. Maserati
Enter the Number of your Selection:1

Bentley is from United Kingdom

Recommended Learning Materials and Resources


To supplement the lesson in this module, you may visit the following links:
● https://beginnersbook.com/2017/08/cpp-if-else-statement/
● https://www.programiz.com/cpp-programming/if-else
● https://www.youtube.com/watch?v=P3MK9jVdHrE&list=PLIY8eNdw5tW_o8gsLqNBu8g
mScCAqKm2Q&index=7
IT 112 – COMPUTER PROGRAMMING 1

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

2. What is the output if:


a. c = 176
b. c = 25
c. c = -5

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

You might also like