Easy Tutorial
❮ Cpp Pointer To Pointer Cpp Examples Endl ❯

C++ Example - Implementing a Simple Calculator

C++ Example

Create a simple calculator in C++ that can perform +, -, *, /.

Example

#include <iostream>
using namespace std;

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

    cout << "Enter an operator: +, -, *, /: ";
    cin >> op;

    cout << "Enter two numbers: ";
    cin >> num1 >> num2;

    switch(op)
    {
        case '+':
            cout << num1 + num2;
            break;

        case '-':
            cout << num1 - num2;
            break;

        case '*':
            cout << num1 * num2;
            break;

        case '/':
            if (num2 == 0)
            {
                cout << "error: cannot divide by zero";
                break;
            }
            else
            {
                cout << num1 / num2;
                break;
            }

        default:
            // If the operator is not +, -, *, or /, display an error message
            cout << "Error! Please enter a valid operator.";
            break;
    }

    return 0;
}

The output of the above program is:

Enter an operator: +, -, *, /: +
Enter two numbers: 1
2
3

C++ Example

❮ Cpp Pointer To Pointer Cpp Examples Endl ❯