Table of contents

C++ Program to make a Simple Calculator Using switch...case

Write a C++ program that takes two numbers and an arithmetic operator as input from the user and performs the corresponding operation.
A simple calculator program is an excellent beginner-level project in C++. It allows you to practice using various programming constructs such as functions, conditional statements, and switch-case statements. 

Input and Output Examples

Input:   Number 1: 10    Number 2: 5    Operator: + 
Output: 10 + 5 = 15

Input:   Number 1: 8    Number 2: 3    Operator: /
Output: 8 / 3 = 2.66667

Algorithm to implement a simple calculator

  1. Prompt the user to input two numbers and an arithmetic operator.
  2. Read the input values.
  3. Use a switch-case statement to perform the corresponding operation based on the operator.
  4. Display the result to the user.

Below is the C++ code that implements a simple calculator:

cpp
#include <iostream>
using namespace std;

int main() {
    char op;
    float num1, num2;

    // Step 1: Prompt the user to input two numbers and an operator
    cout << "Enter two numbers: ";
    cin >> num1 >> num2;
    cout << "Enter an operator (+, -, *, /): ";
    cin >> op;

    // Step 3: Perform the corresponding operation based on the operator
    switch(op) {
        case '+':
            cout << num1 << " + " << num2 << " = " << num1 + num2;
            break;
        case '-':
            cout << num1 << " - " << num2 << " = " << num1 - num2;
            break;
        case '*':
            cout << num1 << " * " << num2 << " = " << num1 * num2;
            break;
        case '/':
            if(num2 == 0) {
                cout << "Error! Division by zero.";
            } else {
                cout << num1 << " / " << num2 << " = " << num1 / num2;
            }
            break;
        default:
            cout << "Invalid operator";
    }

    return 0; // Indicates successful termination
}

Testing with Different Input Values

This program can handle various input values and arithmetic operations, including both integer and floating-point numbers.

cpp
Input:
Number 1: -15
Number 2: 7.5
Operator: * 
Output: -15 * 7.5 = -112.5

Input:
Number 1: 20
Number 2: 0
Operator: / 
Output: Error! Division by zero.

Practice Problem

Enhance the calculator program to include additional arithmetic operations such as exponentiation (power) and modulus (remainder) using switch-case statements.

Programming

Related Articles