Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Conditions and Operators: Conditions and Switch - Case

---
jupytext:
  formats: md:myst
  text_representation:
    extension: .md
    format_name: myst
kernelspec:
  display_name: Python 3
  language: python
  name: python3
---

Conditions and Operators: Conditions and Switch - Case

Adapted from: “Learn Modern C++” by cpptutor: Learn Modern C++: Conditions and Operators

Program that Demonstrates Conditions and Switch Case

// 03-calc.cpp : simple calculator with four functions
 
#include <iostream>
using namespace std;
 
int main() {
    int r{}, x{}, y{};
    char op{};
    cout << "Please enter a calculation (number op number, op is one of +-*/):\n";
    cin >> x >> op >> y;
    switch (op) {
    case '+':
        r = x + y;
        break;
    case '-':
        r = x - y;
        break;
    case '*':
        r = x * y;
        break;
    case '/':
        if (y) {
            r = x / y;
        }
        else {
            cerr << "Error: divide by zero.\n";
        }
        break;
    default:
        cerr << "Error: invalid op.\n";
        break;
    }
    cout << "Result: " << r << '\n';
}

Explanation of the Above Code

This C++ program implements a simple calculator that performs basic arithmetic operations (+, -, *, /) based on user input. Here’s a breakdown of the code:

Code Explanation:

  1. Header Inclusion:

    #include <iostream>
    • The <iostream> header is included to enable input (cin) and output (cout and cerr) operations.

  2. Namespace:

    using namespace std;
    • This allows the program to use standard library features (like cin, cout, and cerr) without prefixing them with std::.

  3. Main Function:

    int main() {
    • The main function is the entry point of the program.

  4. Variable Declarations:

    int r{}, x{}, y{};
    char op{};
    • r: Stores the result of the calculation.

    • x and y: Store the two numbers entered by the user.

    • op: Stores the operator entered by the user.

  5. User Input:

    cout << "Please enter a calculation (number op number, op is one of +-*/):\n";
    cin >> x >> op >> y;
    • Prompts the user to enter a calculation in the format number operator number (e.g., 5 + 3).

    • Reads the input values into x, op, and y.

  6. Switch Statement:

    switch (op) {
    • Evaluates the operator (op) and performs the corresponding arithmetic operation.

    • Case ‘+’:

      case '+':
          r = x + y;
          break;
      • Adds x and y and stores the result in r.

    • Case ‘-’:

      case '-':
          r = x - y;
          break;
      • Subtracts y from x and stores the result in r.

    • Case ‘*’:

      case '*':
          r = x * y;
          break;
      • Multiplies x and y and stores the result in r.

    • Case ‘/’:

      case '/':
          if (y) {
              r = x / y;
          }
          else {
              cerr << "Error: divide by zero.\n";
          }
          break;
      • Divides x by y and stores the result in r.

      • Checks if y is zero to avoid division by zero. If y is zero, an error message is printed to cerr.

    • Default Case:

      default:
          cerr << "Error: invalid op.\n";
          break;
      • Handles invalid operators by printing an error message to cerr.

  7. Output the Result:

    cout << "Result: " << r << '\n';
    • Prints the result of the calculation to the console.

Key Features:

  • Error Handling:

    • Division by zero is explicitly checked, and an error message is displayed if it occurs.

    • Invalid operators are handled with a default case in the switch statement.

  • User Interaction:

    • The program is interactive, prompting the user for input and displaying the result.

Example Input/Output:

  1. Valid Input:

    Input: 5 + 3
    Output: Result: 8
  2. Division by Zero:

    Input: 5 / 0
    Output: Error: divide by zero.
  3. Invalid Operator:

    Input: 5 % 3
    Output: Error: invalid op.

Compile and Run Code

Use Python to Change to Working Directory

import os
root_dir = os.getcwd()
code_dir = root_dir + "/" + "Cpp_Code/03_Conditions_and_Operators"
os.chdir(code_dir)

Use Docker to Compile the Code in a C++23 Environment

!docker run --rm -v $(pwd):/app cpp23-clang18:latest clang++-18 -std=c++23 -stdlib=libc++ /app/03-calc.cpp -o /app/03-calc

Use Docker to Run Executable in a C++23 Environment

!echo "5 + 5" | docker run -i --rm -v $(pwd):/app cpp23-clang18:latest ./03-calc
Please enter a calculation (number op number, op is one of +-*/):
Result: 10
!echo "5 * 5" | docker run -i --rm -v $(pwd):/app cpp23-clang18:latest ./03-calc
Please enter a calculation (number op number, op is one of +-*/):
Result: 25
!echo "25 / 5" | docker run -i --rm -v $(pwd):/app cpp23-clang18:latest ./03-calc
Please enter a calculation (number op number, op is one of +-*/):
Result: 5
!echo "15 - 5" | docker run -i --rm -v $(pwd):/app cpp23-clang18:latest ./03-calc
Please enter a calculation (number op number, op is one of +-*/):
Result: 10
!echo "15 / 0" | docker run -i --rm -v $(pwd):/app cpp23-clang18:latest ./03-calc
Please enter a calculation (number op number, op is one of +-*/):
Result: 0
Error: divide by zero.
!echo "15 V 5" | docker run -i --rm -v $(pwd):/app cpp23-clang18:latest ./03-calc
Please enter a calculation (number op number, op is one of +-*/):
Result: 0
Error: invalid op.