C++ Code Example: simple calculator

This is a simple calculator program that asks the user to enter an arithmetic operation (+, -, *, /) and two numbers. It then performs the requested operation and displays the result.

The program starts by declaring three variables: firstNumber, secondNumber, and result, all of type double. It also declares a variable arithmeticOperation of type char to store the user’s choice of arithmetic operation.

The program then prompts the user to enter an arithmetic operation, followed by the first and second numbers. It uses the cin statement to read in these values from the user.

Next, the program uses a switch statement to determine which arithmetic operation to perform. If the user entered ‘+’, it adds the two numbers together and stores the result in the result variable. If the user entered ‘-‘, it subtracts the second number from the first, and so on. If the user entered an unknown arithmetic symbol, the program prints an error message.

Finally, the program displays the result of the arithmetic operation using the cout statement.

This program is a good example of how to use a switch statement to handle different cases depending on user input. It is also a simple introduction to performing basic arithmetic operations in C++.

#include <iostream>
using namespace std;

int main() {
    double firstNumber, secondNumber, result;
    char arithmeticOperation;

    cout << "Please enter an arithmetic operation (+, -, *, /): " << endl;
    cin >> arithmeticOperation;
    cout << "Please enter your first number: " << endl;
    cin >> firstNumber;
    cout << "Please enter your second number: " << endl;
    cin >> secondNumber;

    switch (arithmeticOperation) {
    case '+':
        result = firstNumber + secondNumber;
        break;
    case '-':
        result = firstNumber - secondNumber;
        break;
    case '*':
        result = firstNumber * secondNumber;
        break;
    case '/':
        result = firstNumber / secondNumber;
        break;
    default:
        cout << "Unknown arithmetic symbol" << endl;
    }
    
    cout << firstNumber << ' ' << arithmeticOperation << ' ' << secondNumber << " = " << result << endl;
    return 0;
}
Output
Please enter an arithmetic operation (+, -, *, /): 
+
Please enter your first number: 
6
Please enter your second number: 
9
6 + 9 = 15