0
0
CProgramBeginner · 2 min read

C Program to Create Simple Calculator with Basic Operations

A simple calculator in C can be created by using switch to select operations and scanf to get user input, like: switch(choice) { case '+': result = a + b; break; }.
📋

Examples

InputEnter first number: 5 Enter second number: 3 Enter operator (+, -, *, /): +
OutputResult: 8
InputEnter first number: 10 Enter second number: 2 Enter operator (+, -, *, /): /
OutputResult: 5
InputEnter first number: 7 Enter second number: 0 Enter operator (+, -, *, /): /
OutputError! Division by zero.
🧠

How to Think About It

To build a simple calculator, first get two numbers and an operator from the user. Then, use a switch or if statements to decide which operation to perform based on the operator. Finally, print the result or an error if the operation is invalid, like division by zero.
📐

Algorithm

1
Get the first number from the user
2
Get the second number from the user
3
Get the operator (+, -, *, /) from the user
4
Use a switch or if-else to perform the operation based on the operator
5
Check for division by zero if operator is division
6
Print the result or error message
💻

Code

c
#include <stdio.h>

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

    printf("Enter first number: ");
    scanf("%lf", &num1);
    printf("Enter second number: ");
    scanf("%lf", &num2);
    printf("Enter operator (+, -, *, /): ");
    scanf(" %c", &op);

    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 {
                printf("Error! Division by zero.\n");
                return 1;
            }
            break;
        default:
            printf("Invalid operator!\n");
            return 1;
    }

    printf("Result: %.2lf\n", result);
    return 0;
}
Output
Enter first number: 5 Enter second number: 3 Enter operator (+, -, *, /): + Result: 8.00
🔍

Dry Run

Let's trace the input 5, 3, and '+' through the code

1

Input numbers and operator

num1 = 5, num2 = 3, op = '+'

2

Switch on operator

case '+': result = 5 + 3 = 8

3

Print result

Output: Result: 8.00

StepOperationValues
1Inputnum1=5, num2=3, op='+'
2Calculateresult=8
3OutputResult: 8.00
💡

Why This Works

Step 1: Getting user input

The program uses scanf to read two numbers and an operator from the user, storing them in variables.

Step 2: Choosing operation

A switch statement checks the operator and performs the matching arithmetic operation.

Step 3: Handling division by zero

Before dividing, the program checks if the second number is zero to avoid errors and prints an error message if so.

Step 4: Displaying the result

The result is printed with two decimal places using printf.

🔄

Alternative Approaches

Using if-else instead of switch
c
#include <stdio.h>

int main() {
    double a, b, res;
    char op;
    printf("Enter first number: ");
    scanf("%lf", &a);
    printf("Enter second number: ");
    scanf("%lf", &b);
    printf("Enter operator (+, -, *, /): ");
    scanf(" %c", &op);

    if(op == '+') res = a + b;
    else if(op == '-') res = a - b;
    else if(op == '*') res = a * b;
    else if(op == '/') {
        if(b != 0) res = a / b;
        else {
            printf("Error! Division by zero.\n");
            return 1;
        }
    } else {
        printf("Invalid operator!\n");
        return 1;
    }

    printf("Result: %.2lf\n", res);
    return 0;
}
This approach uses if-else statements which some find easier to read but can be longer for many cases.
Using functions for each operation
c
#include <stdio.h>

double add(double x, double y) { return x + y; }
double sub(double x, double y) { return x - y; }
double mul(double x, double y) { return x * y; }
double divi(double x, double y) { return y != 0 ? x / y : 0; }

int main() {
    double num1, num2, result;
    char op;
    printf("Enter first number: ");
    scanf("%lf", &num1);
    printf("Enter second number: ");
    scanf("%lf", &num2);
    printf("Enter operator (+, -, *, /): ");
    scanf(" %c", &op);

    switch(op) {
        case '+': result = add(num1, num2); break;
        case '-': result = sub(num1, num2); break;
        case '*': result = mul(num1, num2); break;
        case '/': 
            if(num2 == 0) {
                printf("Error! Division by zero.\n");
                return 1;
            }
            result = divi(num1, num2);
            break;
        default:
            printf("Invalid operator!\n");
            return 1;
    }
    printf("Result: %.2lf\n", result);
    return 0;
}
This method organizes code better by separating operations into functions, improving readability and reuse.

Complexity: O(1) time, O(1) space

Time Complexity

The program performs a fixed number of operations regardless of input size, so it runs in constant time O(1).

Space Complexity

It uses a few variables for input and output, so space usage is constant O(1).

Which Approach is Fastest?

All approaches run in constant time; using functions adds slight overhead but improves code clarity.

ApproachTimeSpaceBest For
Switch statementO(1)O(1)Simple and clear operation selection
If-else statementsO(1)O(1)Easier for beginners to understand
Functions for operationsO(1)O(1)Better code organization and reuse
💡
Always check for division by zero before dividing to avoid runtime errors.
⚠️
Beginners often forget to add a space before %c in scanf, causing input issues.