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

CP1 - Unit 9 - Conditional Statements

This document discusses conditional statements in programming. It introduces if, if-else, and nested if statements. If statements execute code if a condition is true. If-else statements execute one block of code if the condition is true, and another block if the condition is false. Nested if statements contain if statements within other if statements to create more complex conditional logic. The document provides examples of using each type of conditional statement to make decisions in programs based on evaluated conditions.

Uploaded by

Nathaniel Napay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

CP1 - Unit 9 - Conditional Statements

This document discusses conditional statements in programming. It introduces if, if-else, and nested if statements. If statements execute code if a condition is true. If-else statements execute one block of code if the condition is true, and another block if the condition is false. Nested if statements contain if statements within other if statements to create more complex conditional logic. The document provides examples of using each type of conditional statement to make decisions in programs based on evaluated conditions.

Uploaded by

Nathaniel Napay
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Conditional Statements

UNIT 9: CONDITIONAL STATEMENTS

Introduction

Programs are executed from top to bottom (linear sequence). But as our problem or
requirements become complex, our programs more often than not will have to make decisions
to skip some of its parts and jump to some part depending on the answer after evaluating the
conditional statement that we provide. This is the part where we can apply the relational and
logical operators we discussed in the previous lesson.

Decision making or selection structure requires a programmer to specify one or more


conditions to be evaluated along with the statement/s that will be executed if the condition is
true. Optionally, the programmer may also provide statement/s that will be executed if the
evaluation is false.

Learning Objectives

After successful completion of this lesson, you should be able to:

1. Apply the use of relational and logical operators in writing conditional statements.
2. Define the format of if, if...else, switch, nested if and nested
switch statement.
3. Determine what conditional statement to use to satisfy all the requirements of the
program.

Course Materials

C++ programming language provides following types of decision making statements:

1. if statement - consists of a boolean expression followed by one or more


statements.
2. If…else statement - is an ‘if’ statement followed by an optional ‘else’ statement,
which executes when the Boolean expression is false.
3. switch statement - allows a variable to be tested for equality against a list of values.
4. nested if - one ‘if’ or ‘else if’ statement inside another ‘if’ or ‘else if’ statement(s).
5. nested switch statement - one ‘switch’ statement inside another ‘switch’ statement(s).

63
Conditional Statements

9.1 if statement Use the if statement to specify a block of C++ code to be executed if a
condition is true.

condition

True

False
Conditional
codes

Syntax:

if (condition) {
// block of code to be executed if the condition is true
}

Examples:

Determine if a person is a Senior Citizen based on age.

int age =0 ;
:
cin >> age;
if (age >= 60){
cout << “SENIOR CITIZEN”;
}

64
Conditional Statements

Give 20% discount if customer is a senior citizen

int age =0 ;
float price = 0.0;

cin >> age;


:
cin >> price;
if (age >= 60){
cout << “price discounted! “;
price = price – (price * 0.20);
}
cout << “\nPlease pay: “ << price;

9.2 if … else statement Use the else statement to specify a block of code to be executed if
the condition is false.

False
Conditional
condition codes

True

Conditional
codes

Syntax:

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

65
Conditional Statements

Examples:

Determine if a person is a MINOR or an ADULT based on age

int age =0 ;
:
cin >> age;
if (age < 18){
cout << “MINOR”;
} else {
cout << “ADULT”;
}

Note: if there is only ONE statement for true or for false it is ok not to include the braces. Use
indentions to make your program easier to read and debug. Usual error – ‘else without if’

if (age < 18)


cout << “MINOR”;
else
cout << “ADULT”;

if (age < 18)


cout << “MINOR”; PLEASE DO NOT TYPE YOUR
else PROGRAM LIKE THIS!!!!
cout << “ADULT”;

Also note that conditions are written inside the parentheses () and there is no semicolon
after the close parenthesis.

float moSalary =0.0;


int yearService = 0;
float loan =0.0;
:
cin >> moSalary;
:
cin>> yearService;
:
if (moSalary > 20000 && yearService >=3)
loan = moSalary * 0.50;
else
loan = moSalary * 0.15;

cout<< “\nApproved Loan: “ << loan;

66
Conditional Statements

9.3 if else if ladder Several if + else structures can be concatenated with the intention of
checking a range of values.

True
Conditional
condition codes

False

True
Conditional
condition codes

False

Conditional
codes

Syntax:

if (condition) {
// block of code to be executed if the condition is true
} else if (condition){
// block of code to be executed if the condition is false
} else
// block of code to be executed if the condition is false
}

Note: This is NOT limited to two if (condition)

67
Conditional Statements

Examples:

Determine if a number is positive, negative or zero.

cin >>x;
if (x >0)
cout << “x is positive”;
else if (x < 0)
cout << “x is negative”;
else
cout << “x is zero”;

Determine the equivalent grade in SIS

cin>> grade;

if (grade >= 97)


sis = 1.0;
else if (grade >= 94)
sis = 1.25;
else if (grade >= 91)
sis = 1.50;
else if (grade > = 88)
sis = 1.75;
else if (grade >= 85)
sis = 2.0;
else if (grade >= 82)
sis = 2.25;
else if (grade >= 79)
sis = 2.50;
else if (grade >=76)
sis = 2.75;
else if (grade >=75)
sis = 3.00;
else sis = 5.00;

68
Conditional Statements

9.4 Nested if there is another if statement inside an if statement.

Syntax:

if (condition1) {
// block of code to be executed if the condition is true
if (condition2){
// block of code to be executed if the condition is false
} else
// block of code to be executed if the condition is false
}

Examples

float moSalary =0.0;


int yearService = 0;
float loan =0.0;
:
cin >> moSalary;
:
cin>> yearService;
:

if (moSalary > 20000)


if (yearService >=3)
loan = moSalary * 0.50;
else
loan = moSalary * 0.30;
else
loan = moSalary * 0.15;

cout<< “\nApproved Loan: “ << loan;

float pupcet =0.0;


float seniorGrade =0.0;
:
cin >> pupcet;
:
cin>> seniorGrade;
:
if (pupcet > 75)
if (seniorGrade > 85)
cout << “Admitted”;
else
cout << “Denied Admission”;

69
Conditional Statements

For pupcet = 90 and seniorGrade = 90 --- Admitted

For pupcet = 90 and seniorGrade = 80 ---- Denied Admission

For pupcet = 70 and seniorGrade = 90 ----- NO OUTPUT!

70
Conditional Statements

Why?

if (pupcet > 75)


if (seniorGrade > 85)
cout << “Admitted”;
else
cout << “Denied Admission”;
// no corresponding else

Remedy

if (pupcet > 75.0)


if (seniorGrade > 85.0)
cout << "\n\nAdmitted";
else
cout << "\n\nDenied Admission";
else
cout << "\n\nDenied Admission";

9.5 switch statement - A switch statement allows an expression to be tested for equality
against a list of values. Each value is called a case, and the expression being switched
on is checked for each case.

Syntax:

switch(expression) {
case constant-expression :
statement(s);
break; //optional
case constant-expression :
statement(s);
break; //optional

71
Conditional Statements

// you can have any number of case statements.


default : //Optional
statement(s);
}

The following rules apply to a switch statement −https://www.tutorialspoint.com/


 The expression used in a switch statement must have an integral or enumerated type,
or be of a class type in which the class has a single conversion function to an integral or
enumerated type.
 You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
 The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control will fall
through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases
is true. No break is needed in the default case.

Examples:

Determines if a number is EVEN or ODD.

int number=0;

cout <<"\nEnter a whole number: ";


cin >> number;

switch (number % 2) {
case 0: cout << "\n EVEN number";
break;
case 1: cout << "\n ODD number";
}

72
Conditional Statements

Determine monthly subscription fee based on plan ( A- C)

char plan = '';


int freecallSameNet = 0;
float callRate = 0.0;

cout <<"\nEnter a plan [ A- C ]: ";


cin >> plan;

switch (plan)
{
case 'a':
case 'A': mfee = 700.00;
freecallSameNet = 20;
callRate = 7.00;
break;
case 'b':
case 'B': mfee = 900.00;
freecallSameNet = 40;
callRate = 6.50;
break;
case 'c':
case 'C': mfee = 1200.00;
freecallSameNet = 60;
callRate = 6.00;
break;

default: cout << "Wrong plan entered. Try again!";


}

Equivalent with an if statement

if (plan =='a' || plan == 'A') {


mfee = 700.00;
freecallSameNet = 20;
callRate = 7.00;
} else if (plan =='b' || plan == 'B') {
mfee = 900.00;
freecallSameNet = 40;
callRate = 6.50;
}else if (plan =='c' || plan == 'C') {
mfee = 1200.00;
freecallSameNet = 60;
callRate = 6.00;
}else
cout << "Wrong plan entered. Try again!";

73
Conditional Statements

9.6 Nested switch is/are switch statement within a switch statement.

Consider the table below:

Course # and Year Tuition Fee per Miscellaneous


Description Level Unit Fee

1 - BSA 1 324.65 4545.77


2 456.32 5664.65
3 432.76 3565.78
4 345.76 5645.76
2 - BSIT 1 546.76 3453.67
2 657.89 5656.78
3 767.90 6577.78
4 665.87 4564.78
0 - Other All 565.78 7656.78
Courses level

Input course #, year level, number of units enrolled, then compute and display the amount
to pay.

# include<iostream>
using namespace std;

int main()
{
int cNo = 0, Ylevel = 0, units =0;
float tuitionfee = 0.0, miscFee= 0.0, amt2Pay=0.0, error=0;

cout <<"\nCourse No. Description ";


cout <<"\n\n 1 BSA ";
cout <<"\n 2 BSIT";
cout <<"\n 0 Other courses";
cout <<"\n\n Enter course number: ";
cin >> cNo;
cout <<"\nEnter year level: [ 1 - 4 ]: ";
cin >> Ylevel;
cout << "\nNumber of units enrolled: ";
cin >> units;

switch (cNo)
{
case 1: switch(Ylevel)
{
case 1: tuitionfee = units* 324.65;
miscFee = 4545.77;
break;
case 2: tuitionfee = units* 456.32;
miscFee = 5664.65;
break;

74
Conditional Statements

case 3: tuitionfee = units* 432.76;


miscFee = 3565.78;
break;
case 4: tuitionfee = units* 345.76;
miscFee = 5645.76;
break;
default: cout << "\n\nWrong year level for BSA";
error = 1;
} break;

case 2: switch(Ylevel)
{
case 1: tuitionfee = units* 546.76;
miscFee = 3453.67;
break;
case 2: tuitionfee = units* 657.89;
miscFee = 5656.78;
break;
case 3: tuitionfee = units* 767.90;
miscFee = 6577.78;
break;
case 4: tuitionfee = units* 665.87;
miscFee = 4564.78;
break;
default: cout << "\n\nWrong year level for BSIT";
error =1;
} break;

case 0: if (Ylevel > 0 && Ylevel <5)


{
tuitionfee = 565.78;
miscFee = 7656.78;
} else {
cout << "\n\nWrong year level for Other Courses.";
error =1;
}
break;

default: cout << "\n\nWrong course number.";


error = 1;
}
if (!error) {
cout << "\n\n\n Please pay:";
cout << "\n\n Tuition Fee: " << tuitionfee;
cout << "\n\n Miscellaneous Fee: " << miscFee;
cout << "\n\n TOTAL: " << tuitionfee + miscFee;
}
return 0;
}
Note: error variable added as flag to catch if there was an error in the data entry. If wrong
data were entered no amount should be displayed.

75
Conditional Statements

Activities

Write C++ statements for the following conditions: (declare and initialize variables that you
will be using before writing the if statement)

1. Write an if statement that displays the string “Firetree” if the user enter the letter F (in any
case).
2. Write an if statement that displays the string “Entry error” if the user enters a number that is
less than 0; otherwise, display the string “Valid number”
3. Write an if statement that displays the string “Reorder” if the user a number less than 10;
otherwise display the string “OK”
4. Write an if statement that assigns the number 10 to the bonus variable if the user enters a
sales amount that is less than or equal to $250. If the user enters a sales amount that is
greater than $250, prompt the user to enter the bonus rate, and then multiply the user’s
response by the sales amount and assign the result to the bonus variable.
5. Write an if statement that displays the string “Valid entry” when the user enters either the
integer 1, the integer 2, or the integer 3; otherwise, display the string “Error entry”
6. Write an if statement to test if the input data (two meter readings) is valid. To be valid, both
meter readings must be greater than zero, and the current meter reading must be greater
that the previous reading. If the data is not valid, display an appropriate error message.
7. Write an if statement to test if the number of registrants is greater than zero but less than 50.
Display an appropriate error message if the number of registrants is invalid.
8. Write an if statement that will display the shipping charge based on the province entered by
the user. If the user enters any other state, the result should be an “Incorrect state” message.

Province Shipping Charge (Php)

Laguna 130

Cavite 130

9. 9. Write an if statement that will display the shipping charge based on the province entered
by the user. If the user enters any other state, the shipping charge should be 0..

Province Shipping Charge (Php)

Batangas 250

Quezon 300

76
Conditional Statements

Programming Exercises

1. Write a C program the will determine the total amount the company owed using an if.
The seminar fee per person is based on the number of people the company registers, as
showed in the table below. (For example, if the company registers seven people, then
the total amount owed by the company is Php 12600.00

Number of Registrants Fee Per Person

1–4 Php 2000.00

5 – 10 Php 1800.00

11 or more Php 1500.00

2. Write a C program that will ask the user to input the following: total monthly income,
total monthly expenses, preferred model house (A,B or C) and mode of payment (C –
cash or I – installment). Please refer to the table below to see if loan will be granted or
not and how much will a customer pay if cash payment was chosen.

House Model Total Contract Price Down Payment Monthly Amortization

A 3,563,890.00 30% of TCP 25,789.00

B 2,678,400.00 20% of TCP 20,675.00

C 1,980,700.00 15% of TCP 18,763.00

For a loan to be granted monthly amortization must be less than (total monthly income
less total monthly expenses). A 5% discount from the TCP price is given if mode is cash
basis.

Examples:

Total Monthly Income: 156,900.00

Total Monthly Expenses: 113,560.00

House Model (A, B or C): A

Mode of Payment (C or I): C

77
Conditional Statements

Total Contract Price: 3,563,890.00

Discount: 178,194.50

Balance: 3,385,695.50

--------------------------------------------

Total Monthly Income: 156,900.00

Total Monthly Expenses: 113,560.00

House Model (A, B or C): A

Mode of Payment (C or I): I

Total Contract Price: 3,563,890.00

Down Payment: 1,069,167.00

Monthly Amortization: 25,789.00

LOAN APPROVED! Congratulation!

--------------------------------------------

Total Monthly Income: 156,900.00

Total Monthly Expenses: 136,450.00

House Model (A, B or C): A

Mode of Payment (C or I): I

Total Contract Price: 3,563,890.00

Down Payment: 1,069,167.00

Monthly Amortization : 25,789.00

Sorry LOAN DENIED!

78
Conditional Statements

Online References

https://www.w3schools.com/cpp/cpp_conditions.asp/

https://ecomputernotes.com/cpp/control-structures/conditional-statements

https://www.programiz.com/cpp-programming/if-else

79

You might also like