C++

Conditional (Selection) Statements

Conditional Statements are used to execute different blocks of code based on whether a condition is true or false.

In C++ programming language, the most common conditional statements are:

  1. if statement: Executes a block of code if a specified condition is true.
  2. else statement: Executes a block of code if the condition in the if statement is false.
  3. else if statement: Specifies a new condition to test if the previous condition was false.
  4. switch statement: Allows you to execute different blocks of code based on the value of a variable or expression.

The If Else Statement

The if else statement is used to execute one block of code if a condition is true and another block of code if the condition is false.

When the condition is true, the first block of code is executed. When the condition is false, the second block of code is executed.

The computer can be said to be lazy. It starts at the top and keeps checking until it finds a "TRUE" answer. Once it finds one, it does that action and ignores everything else below it.

In C++ programming language, the syntax for an if else statement is as follows:

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

Comparators

Comparators are used to compare values. The most common comparators are:

  1. ==: Equal to
  2. !=: Not equal to
  3. >: Greater than
  4. <: Less than
  5. >=: Greater than or equal to
  6. <=: Less than or equal to

To illustrate the use of if else statements, let's write a simple program which takes an integer value from the user and displays whether it is even or odd.

The algorithm is as follows:

  1. Start.
  2. Input an integer value.
  3. Check if the number is divisible by 2.
  4. If the number is divisible by 2, display "The number is even".
  5. If the number is not divisible by 2, display "The number is odd".
  6. End.

In C++ programming language, the code for this algorithm would look like this:

#include <iostream>
using namespace std;

int main() {
    int num;
    cout << "Enter an integer: ";
    cin >> num;

    if (num % 2 == 0) {
        cout << "The number is even." << endl;
    } else {
        cout << "The number is odd." << endl;
    }

    return 0;
}

In the above C++ program, the condition being checked is whether the number is divisible by 2 using the modulo operator (%). If the result of num % 2 is 0, it means the number is even; otherwise, it is odd.

Note: The modulo operator (%) returns the remainder of a division operation. If a number is divisible by 2, the remainder will be 0, indicating that the number is even. Otherwise, the number is odd.

Another program could be a program which asks the user to enter the age and determines if they are eligible to vote (assuming the voting age is 18).

The algorithm is as follows:

  1. Start.
  2. Input the user's age.
  3. Check if the age is greater than or equal to 18.
  4. If the age is greater than or equal to 18, display "You are eligible to vote."
  5. If the age is less than 18, display "You are not eligible to vote."
  6. End.

In C++ programming language, the code for this algorithm would look like this:

#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter your age: ";
    cin >> age;

    if (age >= 18) {
        cout << "You are eligible to vote." << endl;
    } else {
        cout << "You are not eligible to vote." << endl;
    }

    return 0;
}

The If Else Statement

The if else statement is used to check multiple conditions and execute different blocks of code based on which condition is true.

In C programming language, the syntax for an if else statement is as follows:

if (condition1) {
    // code to be executed if condition1 is true
} else if (condition2) {
    // code to be executed if condition2 is true
} else if (condition3) {
    // code to be executed if condition3 is true
}
.
.
.
 else if (conditionN) {
    // code to be executed if conditionN is true
} else {
    // code to be executed if none of the conditions are true
}

The number of the else if clauses depends on the number of conditions to be checked.

Since the first is if and the last is else, the number of else if can be calculated as:

Number of else if clauses = Number of conditions - 2

For instance if there are 5 position conditions, there will be 3 (5 - 2) else if clauses.

Let's use the B.E.C.E grading system as an example:

Score Grade
75% - 100% 1
70% - 74% 2
65% - 69% 3
60% - 64% 4
55% - 59% 5
50% - 54% 6
45% - 49% 7
40% - 44% 8
0% - 39% 9

There are 9 options and hence 7 (9 - 2) else if clauses.

To write a program that asks the user to enter their score and displays the corresponding grade:

The algorithm is as follows:

  1. Start.
  2. Input the user's score.
  3. Check if the score is greater than or equal to 75 . If true, display "Your grade is 1".
  4. Check if the score is greater than or equal to 70. If true, display "Your grade is 2".
  5. Check if the score is greater than or equal to 65. If true, display "Your grade is 3".
  6. Check if the score is greater than or equal to 60. If true, display "Your grade is 4".
  7. Check if the score is greater than or equal to 55. If true, display "Your grade is 5".
  8. Check if the score is greater than or equal to 50. If true, display "Your grade is 6".
  9. Check if the score is greater than or equal to 45. If true, display "Your grade is 7".
  10. Check if the score is greater than or equal to 40. If true, display "Your grade is 8".
  11. If none of the above conditions are true, display "Your grade is 9".
  12. End.

In C++ programming language, the code for this algorithm would look like this:

#include <iostream>
using namespace std;
int main() {
    int score;
    cout << "Enter your score: ";
    cin >> score;

    if (score >= 75) {
        cout << "Your grade is 1." << endl;
    } else if (score >= 70) {
        cout << "Your grade is 2." << endl;
    } else if (score >= 65) {
        cout << "Your grade is 3." << endl;
    } else if (score >= 60) {
        cout << "Your grade is 4." << endl;
    } else if (score >= 55) {
        cout << "Your grade is 5." << endl;
    } else if (score >= 50) {
        cout << "Your grade is 6." << endl;
    } else if (score >= 45) {
        cout << "Your grade is 7." << endl;
    } else if (score >= 40) {
        cout << "Your grade is 8." << endl;
    } else {
        cout << "Your grade is 9." << endl;
    }

    return 0;
}

Assumption

It is assumed that the user will enter a valid score between 0 and 100.

We will modify this code when we get to iteration (repetition) to repeatedly ask the user to enter a valid score.

Nested If Else Statements

Nested if else statements are if else statements that are contained within another if else statement. They allow you to check multiple conditions in a hierarchical manner.

We can use a nested if else statement to implement the grade-checking algorithm more efficiently.

We will this time check if the score entered is within a specific range before determining the grade

The disadvantage of this design is that, it only runs once and user has to start the program again to enter a new score.

The algorithm is as follows:

  1. Start.
  2. Input the user's score.
  3. Check if the score is between 0 and 100. If false, display "Invalid score. Please enter a score between 0 and 100." and end the program.
  4. If the score is valid, check if the score is greater than or equal to 75 . If true, display "Your grade is 1".
  5. Check if the score is greater than or equal to 70. If true, display "Your grade is 2".
  6. Check if the score is greater than or equal to 65. If true, display "Your grade is 3".
  7. Check if the score is greater than or equal to 60. If true, display "Your grade is 4".
  8. Check if the score is greater than or equal to 55. If true, display "Your grade is 5".
  9. Check if the score is greater than or equal to 50. If true, display "Your grade is 6".
  10. Check if the score is greater than or equal to 45. If true, display "Your grade is 7".
  11. Check if the score is greater than or equal to 40. If true, display "Your grade is 8".
  12. If none of the above conditions are true, display "Your grade is 9".
  13. End.

The modified C++ code for this algorithm would look like this:

#include <iostream>
using namespace std;
int main() {
    int score;
    cout << "Enter your score: ";
    cin >> score;

    if (score < 0 || score > 100) {
        cout << "Invalid score. Please enter a score between 0 and 100." << endl;
    } else {
        if (score >= 75) {
            cout << "Your grade is 1." << endl;
        } else if (score >= 70) {
            cout << "Your grade is 2." << endl;
        } else if (score >= 65) {
            cout << "Your grade is 3." << endl;
        } else if (score >= 60) {
            cout << "Your grade is 4." << endl;
        } else if (score >= 55) {
            cout << "Your grade is 5." << endl;
        } else if (score >= 50) {
            cout << "Your grade is 6." << endl;
        } else if (score >= 45) {
            cout << "Your grade is 7." << endl;
        } else if (score >= 40) {
            cout << "Your grade is 8." << endl;
        } else {
            cout << "Your grade is 9." << endl;
        }
    }

    return 0;
}

The grade checking if else is the nested if-else structure.

We could also modify the voting system to ensure user doesn't enter a negative number using the nested if-else structure.

The modified C++ code for this would look like this:

#include <iostream>
using namespace std;
int main() {
    int age;
    cout << "Enter your age: ";
    cin >> age;

    if (age < 0) {
        cout << "Invalid age. Please enter a valid age." << endl;
    } else {
        if (age >= 18) {
            cout << "You are eligible to vote." << endl;
        } else {
            cout << "You are not eligible to vote." << endl;
        }
    }

    return 0;
}

The Switch Statement

The switch statement is used to execute different blocks of code based on the value of a variable or expression. It is an alternative to using multiple if else statements when you have a large number of conditions to check.

In C++ programming language, the syntax for a switch statement is as follows:

switch (variable) {
    case value1:
        // code block
        break;
    case value2:
        // code block
        break;
        .
        .
        .
       case valuen:
        // code block
        break;
    default:
        // code block
        break;
}

Explanation

The switch statement evaluates the variable and compares it with each case label. When a match is found, the corresponding code block is executed. The break statement is used to exit the switch statement after a match is found and block of code executed.

The default case is optional and is executed if none of the case labels match the variable.

We can use the switch alternative to write the code for the even number check.

The C++ code for this would look like this:

#include <iostream>
using namespace std;
int main() {
    int number;
    cout << "Enter an integer: ";
    cin >> number;

    switch (number%2) {
    case 0:
        cout << "The number is even." << endl;
        break;
    default:
        cout << "The number is not even." << endl;
        break;
    }
    return 0;
}

In the above code, the expressing number%2 returns either 0 or 1 which is compared to the cases (0 and default).

When it is 0, the block of code after the case 0: is executed.

The break; makes it to exit the switch since a match is found.

Without the break;, the execution will continue until next break; is found or the entire rest of code is executed.

Another example of the switch statement would be to ask a user to enter from 1 - 7 to represent the days of the week.

1 - Monday

2 - Tuesday

3 - Wednesday

4 - Thursday

5 - Friday

6 - Saturday

7 - Sunday

The C++ code for this would look like this:

#include <iostream>
using namespace std;
int main() {
    int day;
    cout << "Enter a number (1-7) to represent the day of the week: ";
    cin >> day;

    switch (day) {
    case 1:
        cout << "Monday" << endl;
        break;
    case 2:
        cout << "Tuesday" << endl;
        break;
    case 3:
        cout << "Wednesday" << endl;
        break;
    case 4:
        cout << "Thursday" << endl;
        break;
    case 5:
        cout << "Friday" << endl;
        break;
    case 6:
        cout << "Saturday" << endl;
        break;
    case 7:
        cout << "Sunday" << endl;
        break;
    default:
        cout << "Invalid input. Please enter a number between 1 and 7." << endl;
        break;
    }
    return 0;
}

Note: the break statements are crucial to prevent fall-through to subsequent cases.

When the break is omitted, the program will continue to execute the next case, leading to unintended behavior.