c-plus-plus
  1. c-plus-plus-calculator-program

C++ Programs Calculator Program

A calculator program is a simple application that performs arithmetic operations such as addition, subtraction, multiplication, and division on two numbers. In this page, we will create a simple calculator program in C++.

Syntax

#include <iostream>
using namespace std;

int main() {
    // code
    return 0;
}

Example

#include <iostream>
using namespace std;

int main() {
    char oper;
    double num1, num2;

    cout << "Enter operator (+,-,*,/): ";
    cin >> oper;

    cout << "Enter first number: ";
    cin >> num1;

    cout << "Enter second number: ";
    cin >> num2;

    switch (oper) {
        case '+':
            cout << num1 << " + " << num2 << " = " << num1 + num2 << endl;
            break;
        case '-':
            cout << num1 << " - " << num2 << " = " << num1 - num2 << endl;
            break;
        case '*':
            cout << num1 << " * " << num2 << " = " << num1 * num2 << endl;
            break;
        case '/':
            if (num2 == 0) {
                cout << "Error: Cannot divide by zero." << endl;
            } else {
                cout << num1 << " / " << num2 << " = " << num1 / num2 << endl;
            }
            break;
        default:
            cout << "Error: Invalid operator." << endl;
            break;
    }

    return 0;
}

Output

Enter operator (+,-,*,/): +
Enter first number: 10
Enter second number: 20
10 + 20 = 30

Explanation

In the above example, we first ask the user to enter an operator (+, -, *, /) and two numbers. We then use a switch statement to perform the arithmetic operation based on the operator entered by the user.

If the user tries to divide by zero, we display an error message. If the user enters an invalid operator, we also display an error message.

Use

A calculator program can be useful in many situations where you need to perform simple arithmetic calculations without the need for a physical calculator.

Important Points

  • A calculator program can perform arithmetic operations such as addition, subtraction, multiplication, and division.
  • We can use control structures like if-else or switch statements to handle user input and perform the calculations.
  • If the user tries to divide by zero, we need to handle the error gracefully.

Summary

In summary, creating a calculator program in C++ is a great way to practice using control structures and handling user input. It's a useful program that you can use to perform simple calculations without the need for a physical calculator.

Published on: