cppbeginner10 minutes

Basic Calculator CLI Mini-Project in C++

Create a simple command-line calculator program in C++ that performs basic arithmetic operations like addition, subtraction, multiplication, and division based on user input.

Challenge prompt

Write a C++ program that asks the user to input two numbers and an operation (+, -, *, /). The program should then calculate and display the result of applying the chosen operation to the two numbers. Make sure to handle division by zero gracefully by displaying an error message.

Guidance

  • Use basic variables to store user inputs for numbers and the operator.
  • Use if-else or switch-case statements to decide the operation.
  • Check for division by zero before performing division to avoid errors.

Hints

  • Use the 'cin' object to get input from the user.
  • Remember to include checks for invalid operators.
  • Use 'cout' to display the result or error messages.

Starter code

#include <iostream>
using namespace std;

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

    cout << "Enter first number: ";
    cin >> num1;
    cout << "Enter an operator (+, -, *, /): ";
    cin >> op;
    cout << "Enter second number: ";
    cin >> num2;

    // Your code here

    return 0;
}

Expected output

Example run: Enter first number: 8 Enter an operator (+, -, *, /): / Enter second number: 2 Result: 4

Core concepts

variablesconditional statementsinput/outputbasic arithmetic

Challenge a Friend

Send this duel to someone else and see if they can solve it.