> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/c++-notes/13.-practice-program-basic-calculator.md).

# 13. Practice Program - Basic Calculator

A console calculator that asks for the **operator first**, then the **two numbers** — and uses a `switch` to run the right calculation. This pulls together topics 06 (arithmetic), 08 (user input), and 12 (switch statements).

***

### The full program

```cpp
#include <iostream>

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

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

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

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

    double result = 0;

    switch (op) {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            result = num1 / num2;
            break;
        default:
            std::cout << "Invalid operator\n";
            return 1;
    }

    std::cout << num1 << " " << op << " " << num2 << " = " << result << '\n';

    return 0;
}
```

**Example run:**

```
Enter an operator (+, -, *, /): *
Enter first number: 6
Enter second number: 7
6 * 7 = 42
```

***

### Breaking it down

| Step                                         | What's happening                                                        |
| -------------------------------------------- | ----------------------------------------------------------------------- |
| `char op;`                                   | Holds a single character like `+`, `-`, `*`, `/`.                       |
| `double num1, num2;`                         | The two numbers — `double` so decimals work too.                        |
| `std::cin >> op;`                            | Read the operator **first**, before the numbers.                        |
| `std::cin >> num1;` then `std::cin >> num2;` | Read each number separately, one prompt at a time.                      |
| `switch (op) { ... }`                        | Picks which math operation to run based on what the user typed.         |
| `default:`                                   | Catches anything that isn't `+ - * /` and exits early with `return 1;`. |

***

### More cool examples

#### 1. Same program, but using `if / else if` instead of `switch`

```cpp
#include <iostream>

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

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

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

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

    double result;

    if (op == '+') {
        result = num1 + num2;
    }
    else if (op == '-') {
        result = num1 - num2;
    }
    else if (op == '*') {
        result = num1 * num2;
    }
    else if (op == '/') {
        result = num1 / num2;
    }
    else {
        std::cout << "Invalid operator\n";
        return 1;
    }

    std::cout << "Result: " << result << '\n';

    return 0;
}
```

#### 2. Guarding against division by zero

```cpp
#include <iostream>

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

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

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

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

    double result = 0;

    switch (op) {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            if (num2 == 0) {
                std::cout << "Error: cannot divide by zero\n";
                return 1;
            }
            result = num1 / num2;
            break;
        default:
            std::cout << "Invalid operator\n";
            return 1;
    }

    std::cout << "Result: " << result << '\n';

    return 0;
}
```

#### 3. Adding modulus (`%`) — whole numbers only

```cpp
#include <iostream>

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

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

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

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

    int result = 0;

    switch (op) {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            result = num1 / num2;
            break;
        case '%':
            result = num1 % num2;
            break;
        default:
            std::cout << "Invalid operator\n";
            return 1;
    }

    std::cout << "Result: " << result << '\n';

    return 0;
}
```

#### 4. Looping so you can calculate again without restarting

```cpp
#include <iostream>

int main() {
    char op, again;

    do {
        double num1, num2, result = 0;

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

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

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

        switch (op) {
            case '+': result = num1 + num2; break;
            case '-': result = num1 - num2; break;
            case '*': result = num1 * num2; break;
            case '/': result = num1 / num2; break;
            default:
                std::cout << "Invalid operator\n";
                continue;
        }

        std::cout << "Result: " << result << '\n';

        std::cout << "Calculate again? (y/n): ";
        std::cin >> again;

    } while (again == 'y' || again == 'Y');

    return 0;
}
```

> This last one uses a `do-while` loop — worth covering as its own topic if you haven't hit loops yet in the course.

***

### Quick Recap

* Order of input here: **operator first**, then **number 1**, then **number 2**.
* A `switch` on `op` is a clean way to route to the right calculation (topic 12).
* Always handle the "invalid operator" case with `default:` — don't assume the user types correctly.
* Division needs an extra check for `num2 == 0` to avoid a divide-by-zero bug.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/c++-notes/13.-practice-program-basic-calculator.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
