Cascading If Statements in C++

Introduction

This lab will provide students with an introduction to the fundamentals of multi-way conditional selection in the C++ programming language. The focus of this lab is on how to solve simple problems using the C++ cascading “if” statement and logical operators. At the end of this module, students will…

  • Be able to solve simple problems using C++ cascading “if” and “if-else” statements
  • Understand the structure of simple C++ cascading “if” statements
  • Understand and be able to apply complex conditional expressions
  • Understand and apply the basic concepts behind C++ logical operators

These exercises have two different types of answers. Some questions ask for answers to specific questions; you should collect these answers in a Microsoft Word document. Other exercises ask you to write code. Let’s begin!

Part 1: Multi-Way Conditional Selection in C++

We have previously talked about conditional selection when we discussed if statements. This involved the execution of a statement or a sequence of statements, dependent upon the true/false value of a specified condition. This was called a selection construct because it allowed us to execute a different set of code by selecting which option to take (a true condition executed one piece of code, a false condition executed another). We can further extend the if statement to allow for cascading, which allows us to check an arbitrary number of cases.

For example, suppose we wanted to assign a letter grade to a student based on his/her percentage grade. Given that there are more than two possible grades, we would need a decision construct that allows for multiple cases. C++ provides the cascading if statement to handle this situation. To assign student grades, a cascading if statement would appear as follows:

if (pct_grade >= 90) 
{ 
   letter_grade = ‘A’; 
} 
else if (pct_grade >= 80) 
{ 
   letter_grade = ‘B’; 
} 
else if (pct_grade >= 70) 
{ 
   letter_grade = ‘C’; 
} 
else if (pct_grade >= 60) 
{ 
   letter_grade = ‘D’; 
} 
else 
{ 
   letter_grade = ‘F’; 
}

The term cascading refers to the way that control cascades down the statement like water down a waterfall. The top-most condition is evaluated first; if this condition is true, then the corresponding statements are executed and the statement is done. If the top-most condition is not true, then control cascades down to the next condition, and the process repeats. In the example above, the cascading if statement first checks to see if the value of pct_grade is greater than or equal to 90; if it is, the variable letter_grade is assigned the value “A”. If pct_grade is not greater than or equal to 90, the next condition is tested, and the process repeats.

A cascading if statement allows us to check many different conditions, one after another, until we find one with a true value. This is an example of multi-way branching. Each block of code can be called a branch; which branch is executed is decided by which conditional expression has a true value. The general form of a cascading if statement is as follows:

if ( /* conditional expression */ ) 
{
   // one or more statements to execute if the 
   // condition is true 
}
else if ( /* conditional expression */ ) 
{
   // one or more statements to execute if the 
   // condition is true 
}
...  // potentially more else if clauses
else
{
   // the default case; all previous conditions were false 
}

The else and else if clauses are strictly optional. If used, the else clause must appear as the last clause in the statement.

Watch and listen to the Cascading If Statements C++ podcast below:

cascading_if

Review: Relational Operators

Conditional selection constructs alter the flow-of-control based on the result of evaluating a conditional expression. To construct these expressions, all programming languages have built-in binary relational operators for building conditional expressions. C++ has six relational operators, all of which are derived from mathematics:

Operator Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
!= Not equal to
== Equal to

 

These operators are binary in the sense that they require two operands (one on the left of the operator, one on the right). The operator compares these operands and produces a Boolean (true or false) result. For example, the conditional expression (account < 2000.00) is a Boolean expression which is true only if the value of account is less than 2000. If account is not less than 2000, the expression is false. Conditional expressions should always be enclosed in parentheses to avoid any ambiguity.

Logical Operators

Relational operators are used in simple Boolean expressions. However, sometimes you need to test two or more conditional expressions at once. There are three logical operators in C++:

Operator Meaning
&& And
|| Or
! Not

 

There arise cases where you want to test if one thing is true, or if two things are true in conjunction with one another. The logical operator && (AND) allows you to test two Boolean expressions in tandem; if both are true, the end result is true. For example:

if ((score1 == 2) && (score2 > 0)) 
{
   cout << "Condition succeeded!" << endl; 
}    

The logical operator || (OR) combines conditionals so that the entire expression is true if either or both of the two boolean expressions is true. For example:

if ((score1 == 2) || (score2 > 0)) 
{
   cout << "Condition succeeded!" << endl; 
}    

The third logical operator (!, or NOT) is used with single Boolean expressions. The NOT operator “flips” the result of its operand; when the Boolean expression is true, the result of applying the ! operator is to make the expression false, and vice-versa. For example:

if ( !(score1 == 2) ) 
{
   cout << "Condition succeeded!" << endl; 
}    

 

Part 2: College Fees

Macomb State College charges students with different fees related to tuition, parking, computer use, and other factors. Parking Fees are $40/semester for full-time students, $20/semester for part-time students. A student is considered full-time if he/she has 12 or more credit hours. Current tuition Rates are $3500/semester for full-time, $295/credit for part-time. Computer Science (CS) and Mathematics (MATH) majors pay an additional fee which funds the maintenance and upgrade of campus computer resources. This additional major-specific fee is $750.00 for >= 9 credits, $450.00 for [5-8] credits, and $225 for 1-4 credits.

Exercise 1: In this exercise, you will write a program to compute the total amount of fees one would pay if he/she attended Macomb State. You will prompt the user for two things:

  • The number of semester credit hours (a double value)
  • The students’ major, (a string – e.g. MATH, CS)

Using the information in the preceding discussion, compute the total fees that a student would pay for a given semester and display it to the user. All output should be nicely formatted with two digits of precision, dollar signs, and friendly and informative messages. Don’t forget to follow the C++ Coding Guidelines!

Part 3: Body Mass Index

Calculating the body mass index (BMI) is one method of assessing the obesity of an individual, taking into account both weight and height. This measure was created in the 19th century by Adolphe Quetelet and is still used today. The BMI of an individual can be calculated with the following formula:
bmi
The National Institutes of Health (NIH) lists the following categories of BMI values:

  • Underweight = <18.5
  • Normal weight = 18.5 up to but not including 25
  • Overweight = 25 up to but not including 30
  • Obesity = BMI of 30 or greater

Exercise 2: Create a C++ program which prompts the user for his/her name (a string), height in inches (a double), and weight in pounds (a double). Once the input is received, your program should report the user’s name, BMI value, and NIH classification to the screen.

Test your program as well as possible, using many different sets of input data. Some sample input data includes:

Homer, 72 in. tall, 200 pounds
Marge, 65 in. tall, 120 pounds
Bart, 48 in. tall, 75 pounds
Lisa, 45 in. tall, 60 pounds

 

Part 4: Vocabulary Words

You will be assessed on your knowledge of the following terms and concepts as well as the C++ concepts discussed in this document. As a result, you are encouraged to review these terms in the preceding document.

Boolean – true or false.

Conditions – expressions which evaluate to one of two possible values: true or false.

Conditional Selection – a C++ language construct that permits alternate sections of code to be executed based on a conditional (true/false) test.

Compound Statement – a C++ statement that contains multiple statements within it.

Logical Operators – binary operators which test the relationship between two conditional values (or expressions). In C++, the operators are && and ||. These operators produce a Boolean result when applied to two operands. There is also a unary operator (!).

Multi-Way Branching – a C++ language construct that permits alternate sections of code to be executed based on a conditional (true/false) test. In C++, a cascading if statement allows for the checking of many different conditions, one after another, until one is found with a true value. Each block of code can be called a branch; which branch is executed is decided by which conditional expression has a true value.

Operand – a C++ variable, expression, or literal that can be used with a C++ operator. For example, in the expression 3+5, the numbers 3 and 5 are operands and the + symbol is the operator.

Operator – a C++ symbol which allows a specific operation to be performed on one or more operands.

Relational Operators – binary operators which test the relationship between two values. In C++, the operators are ==, !=. >, <, >=, and <=. These operators produce a Boolean result when applied to two operands.

Sequential execution – the standard flow of control in C++, or the way in which statements are executed. A program executes starting with the first statement in the main() function and terminates with the last statement in main(), if all goes well. Individual expressions are executed left-to-right.