Basic Calculator

Program to create a basic calculator with arithmetic operations

BeginnerTopic: Loop Programs
Back

C++ Basic Calculator Program

This program helps you to learn the fundamental structure and syntax of C++ programming.

Try This Code
#include <iostream>
using namespace std;

int main() {
    char op;
    double num1, num2, result;
    
    cout << "Enter operator (+, -, *, /): ";
    cin >> op;
    
    cout << "Enter two numbers: ";
    cin >> num1 >> num2;
    
    switch(op) {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            if (num2 != 0) {
                result = num1 / num2;
            } else {
                cout << "Error: Division by zero!" << endl;
                return 1;
            }
            break;
        default:
            cout << "Error: Invalid operator!" << endl;
            return 1;
    }
    
    cout << num1 << " " << op << " " << num2 << " = " << result << endl;
    
    return 0;
}
Output
Enter operator (+, -, *, /): *
Enter two numbers: 5 4
5 * 4 = 20

Understanding Basic Calculator

This program creates a basic calculator using a switch statement. It reads an operator and two numbers, then performs the corresponding operation. We handle division by zero and invalid operators. The switch statement provides a clean way to handle multiple cases.

Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.

Table of Contents