Decision Making in C++

Introduction

Imagine you’re playing a video game and faced with choices like which path to take or which weapon to use. In C++, decision-making allows our programs to make similar choices based on different conditions. It’s a powerful tool that helps our programs take different actions depending on the situation.

In this article, we’ll explore the concept of decision-making in C++, why it’s important, and how we can use it in our programs. So, let’s dive in and master the art of decision-making in C++!

What Is Decision Making in C++?

Conditional statements also referred to as decision control structures, play a significant role in C/C++ programming. These statements, including if, if-else, switch, and others, are utilized for making decisions within programs.

They are commonly known as decision-making statements and are employed to assess one or multiple conditions, determining whether a specific set of instructions should be executed or not. These decision-making statements guide the path of program execution based on certain conditions.

Decision Making in C++
Decision Making in C++

Need of Conditional Statements

In both real life and programming, there are times when we have to make choices. These choices determine our next steps. Similarly, in programming, we often encounter situations where we have to make decisions and then proceed with specific actions based on those decisions.

For instance, in the programming language C, if a certain condition ‘x’ is met, we carry out action ‘y’, otherwise, we do action ‘z’. We can also encounter more complex scenarios where we have multiple conditions. In such cases, we use an ‘else-if’ structure in C. For instance, if ‘x’ is true, we do action ‘p’. But if ‘x’ is not true and ‘y’ is true, we do action ‘q’. And if neither ‘x’ nor ‘y’ are true, we perform action ‘r’. This ‘else-if’ structure allows us to handle various conditions in our code effectively.

Types of Conditional Statements in C/C++

  • if Statement: This is the simplest type of conditional statement. It checks a condition, and if it’s true, it executes a block of code. If the condition is false, the code block is skipped.
  • if-else Statement: This adds an alternative code block to the ‘if’ statement. If the initial condition is true, the ‘if’ block is executed. If the condition is false, the ‘else’ block is executed.
  • if-else-if Statement: This is an extension of the ‘if-else’ statement. It allows you to check multiple conditions in sequence. If the first condition is true, its block executes. If not, the next condition is checked, and so on. If none of the conditions are true, an optional ‘else’ block can be executed.
  • switch Statement: The ‘switch’ statement is used when you have a specific value to compare against multiple possible cases. Based on the value of the expression provided, the corresponding case block is executed.

1. if Statement

The “if” statement is a basic decision-making tool in programming. It helps us determine whether a specific set of actions or commands should be carried out based on a particular condition. If the given condition is true, a specified block of commands is executed; otherwise, it is skipped. This allows us to control the flow of our program based on whether a certain situation holds true or not.

Syntax of if Statement

C++
if(condition) 
{
 // Statements to execute if</em>
 // condition is true</em>
}

Code Example:

C++
#include <iostream>
using namespace std;

int main() {
    int age;

    cout << "Enter your age: ";
    cin >> age;

    if (age >= 18) {
        cout << "You are an adult." << endl;
    } else {
        cout << "You are a minor." << endl;
    }

    return 0;
}

Output:

C++
Enter your age: 21
You are an adult.

Explanation:

  • If statements are used in programming to perform different actions based on whether a certain condition is true or false.
  • The if statement evaluates an expression inside parentheses and executes the code block within the curly braces if the expression is true.
  • In the given example, the condition checks if the age variable is greater than or equal to 18.
  • If the condition is true, the program outputs “You are an adult,” indicating that the person is 18 years or older.
  • If the condition is false (age is less than 18), the program outputs “You are a minor,” indicating that the person is under 18 years old.

2. if-else in C/C++

In C++, the “if-else” statement is a powerful tool used for decision-making in your code. It allows your program to perform different actions based on whether a certain condition is true or false.

Syntax of if else in C++

C++
if (condition)
{
    // Executes this block if
    // condition is true
}
else
{
    // Executes this block if
    // condition is false
}

Here’s how it works in simple terms:

  1. If-Else Structure: The if-else statement consists of two parts – the “if” part and the “else” part.
  2. Condition Check: The “if” part checks a specific condition inside parentheses to see if it is true or false.
  3. Two Possibilities: If the condition is true, the code block within the “if” statement will be executed. If the condition is false, the code block within the “else” statement (if present) will be executed instead.
  4. Decision Making: The if-else statement helps your program make decisions based on the outcome of the condition check.
  5. Control Flow: Depending on whether the condition is true or false, different parts of your code will be executed, allowing your program to respond accordingly.

Here’s a Code example:

C++
#include <iostream>

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

    if (age >= 18) {
        std::cout << "You are an adult." << std::endl;
    } else {
        std::cout << "You are a minor." << std::endl;
    }

    return 0;
}

Explanation:

  • Asks the user to input their age.
  • Uses the “if-else” statement to check if the entered age is greater than or equal to 18.
  • If the age is 18 or older, the program prints “You are an adult.”
  • If the age is less than 18, the program prints “You are a minor.”

3. if-else-if Statement

The ‘if-else-if‘ statement in C++ allows you to make multiple decisions in your code based on different conditions. It is used when you have multiple conditions to check, and you want to execute specific blocks of code based on which condition is true.

Syntax of if-else-if

C++
if (condition)
    statement;
else if (condition)
    statement;
.
.

else
    statement;

Here’s an explanation with a code example:

Suppose you want to determine a person’s age group based on their age. You can use the ‘if-else-if‘ statement to achieve this. Let’s see the code:

C++
#include <iostream>

int main() {
    int age;

    // Taking input for the age variable
    std::cout << "Enter your age: ";
    std::cin >> age;

    // Using if-else-if statement to make decisions based on age
    if (age < 0) {
        std::cout << "Invalid age. Please enter a valid age.";
    } else if (age < 18) {
        std::cout << "You are a minor.";
    } else if (age >= 18 && age < 65) {
        std::cout << "You are an adult.";
    } else {
        std::cout << "You are a senior citizen.";
    }

    return 0;
}

Explanation:

  1. The program first prompts the user to enter their age.
  2. Then, the ‘if-else-if‘ statement is used to check different conditions:
  • If the age is less than 0, it displays an error message for an invalid age.
  • If the age is less than 18, it outputs “You are a minor.”
  • If the age is between 18 (inclusive) and 65 (exclusive), it outputs “You are an adult.”
  • If none of the above conditions are met, it assumes the person is 65 or older and outputs “You are a senior citizen.”

Output:

  1. If the user enters ‘10‘, the output will be: “You are a minor.”
  2. If the user enters ‘25‘, the output will be: “You are an adult.”
  3. If the user enters ‘75‘, the output will be: “You are a senior citizen.”

The ‘if-else-if‘ statement helps the program make appropriate decisions based on different conditions, making it a powerful tool for control flow in C++ programs.

4. switch Statement

In C++, the switch statement is a control flow statement used to perform different actions based on the value of an expression. It provides an efficient way to handle multiple cases or options without using a series of if-else statements. The expression inside the switch statement is evaluated, and the corresponding case that matches the value of the expression is executed.

Here’s a code example to demonstrate the switch statement:

C++
#include <iostream>

int main() {
    int choice;
    std::cout << "Enter a number (1-3): ";
    std::cin >> choice;

    switch (choice) {
        case 1:
            std::cout << "You chose option 1.\n";
            break;
        case 2:
            std::cout << "You chose option 2.\n";
            break;
        case 3:
            std::cout << "You chose option 3.\n";
            break;
        default:
            std::cout << "Invalid choice.\n";
            break;
    }

    return 0;
}

Output Example:

  1. If you enter “1”:
C++
Enter a number (1-3): 1
You chose option 1.
  1. If you enter “2”:
C++
Enter a number (1-3): 2
You chose option 2.
  1. If you enter “3”:
C++
Enter a number (1-3): 3
You chose option 3.
  1. If you enter any other number:
C++
Enter a number (1-3): 5
Invalid choice.

Explanation:

  • The user called for a number (1-3).
  • Switch statement evaluates the input.
  • Prints specific messages for each case (1, 2, 3).
  • Default case handles invalid input.
  • “Break” statements prevent fall-through to the next case.

Real-life Scenarios

Let’s take a real-life scenario to understand decision-making using various control structures in C++:

Scenario: Online Shopping Discounts

Imagine you are building a program to calculate discounts for an online shopping platform. Here’s how you can use different decision-making structures to implement this:

  1. if Statement:
    If a user’s total purchase amount is greater than $100, they get a 10% discount.
  2. if…else Statement:
    If the total purchase amount is greater than $100, they get a 10% discount. Otherwise, no discount is applied.
  3. if-else-if :
    If the total purchase amount is greater than $200, they get a 15% discount. If it’s greater than $100, they get a 10% discount. Otherwise, no discount is applied.
  4. switch Statement:
    If the user enters their membership level (Silver, Gold, Platinum), they receive different discounts: 5% for Silver, 10% for Gold, and 15% for Platinum.

In this scenario, each decision-making structure helps determine the appropriate discount for the user based on their purchase amount or membership level. The program’s logic branches based on conditions, allowing you to create tailored experiences for users.

A Problem to Solve

Problem: Grade Calculator

Write a C++ program to calculate and display the grade of a student based on their percentage marks. Use the following grading system:

  • A+: 90% and above
  • A: 80% to 89.99%
  • B: 70% to 79.99%
  • C: 60% to 69.99%
  • D: 50% to 59.99%
  • F: Below 50%

Your program should take the percentage marks as input from the user and then display the corresponding grade based on the provided grading system. Use if, if..else, nested if, or if-else-if statements to implement the decision-making logic.

Example Output:

C++
Enter your percentage marks: 87.5
Your grade is: A

Enter your percentage marks: 63.2
Your grade is: C

Enter your percentage marks: 49.8
Your grade is: F

Note: Remember to handle invalid input, such as negative percentage marks or values greater than 100, and provide appropriate messages to the user.

The Pros and Cons of Decision Making

ProsCons
Allows for dynamic and flexible program execution based on conditionsThis may introduce potential logical errors if conditions are not properly handled
Enables different actions to be taken based on specific conditionsRequires careful planning and consideration of all possible scenarios
Improves program interactivity and user experienceMay introduce potential logical errors if conditions are not properly handled
Enhances code readability and organizationCan make code harder to maintain and debug in complex scenarios
The Pros and Cons of Decision Making

Key Takeaways

  • Decision making in C++ allows programs to take different actions based on specific conditions.
  • It enables dynamic and interactive program execution.
  • By using decision-making statements, you can control the flow of your program and execute different code blocks.
  • Decision making enhances the flexibility and functionality of your programs.
  • It allows you to respond to different scenarios and adapt your program’s behavior accordingly.

Conclusion

In summary, decision making is an important aspect of C++ programming. By learning how to use it effectively, you can create programs that make choices based on specific conditions. This makes your programs more interactive and responsive. So, keep practicing and soon you’ll become skilled at using decision making in your programming journey!

FAQs

  • What is decision making in C++?
    Decision making in C++ involves using certain statements that allow our programs to take different actions depending on different conditions.
  • Why do we use decision making in C++?
    We use decision making in C++ to make our programs more dynamic and interactive. It allows our programs to choose between different actions based on different conditions.
  • How do we use decision making in C++?
    We use decision making in C++ by using ‘if‘, ‘if-else‘, ‘if-else if-else‘, ‘switch‘, and the ternary operator ‘? :‘ to control the flow of our program.
  • Can using decision making make code more confusing?
    Yes, if you use decision making incorrectly, it can lead to bugs and errors in your program. It’s important to understand how decision making works and when to use it.
  • What are some examples of using decision making in C++?
    Some examples include using ‘if‘, ‘if-else‘, ‘if-else if-else‘, ‘switch‘, and the ternary operator ‘? :‘ to control the flow of a program based on different conditions.
Deepak Vishwakarma

Founder

RELATED Articles

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.