How to write a simple calculator program using C language?

A calculator is a simple tool that helps us to calculate mathematical operations easily and quickly. A basic calculator can perform simple arithmetic operations like subtraction, addition, multiplication, and division.

In C programming, we can create a calculator using switch-case statements to handle different operators and perform calculations based on user input.

Syntax

switch(operator) {
    case '+': result = num1 + num2; break;
    case '-': result = num1 - num2; break;
    case '*': result = num1 * num2; break;
    case '/': result = num1 / num2; break;
    default: printf("Invalid operator");
}

Algorithm

  • Step 1: Declare variables for operator, operands, and result
  • Step 2: Prompt user to enter an operator (+, -, *, /)
  • Step 3: Prompt user to enter two numeric values
  • Step 4: Use switch-case to perform the selected operation
  • Step 5: Display the calculated result

Example: Basic Calculator Program

Following is the C program for the calculator. It asks the user to enter an operator (+, -, *, /) and two operands, then performs the arithmetic operation using switch-case −

#include <stdio.h>

int main() {
    char operator;
    float num1, num2, result = 0;
    
    printf("Enter an operator (+, -, *, /): ");
    scanf("%c", &operator);
    
    printf("Enter two numbers: ");
    scanf("%f %f", &num1, &num2);
    
    switch (operator) {
        case '+':
            result = num1 + num2;
            printf("%.2f + %.2f = %.2f<br>", num1, num2, result);
            break;
        case '-':
            result = num1 - num2;
            printf("%.2f - %.2f = %.2f<br>", num1, num2, result);
            break;
        case '*':
            result = num1 * num2;
            printf("%.2f * %.2f = %.2f<br>", num1, num2, result);
            break;
        case '/':
            if (num2 != 0) {
                result = num1 / num2;
                printf("%.2f / %.2f = %.2f<br>", num1, num2, result);
            } else {
                printf("Error: Division by zero is not allowed!<br>");
            }
            break;
        default:
            printf("Error: Invalid operator '%c'<br>", operator);
    }
    
    return 0;
}

Output

Enter an operator (+, -, *, /): +
Enter two numbers: 25.5 14.3
25.50 + 14.30 = 39.80

Key Points

  • The program uses switch-case for clean operator selection
  • Division by zero is handled to prevent runtime errors
  • Float data type allows decimal calculations
  • Input validation ensures proper error handling

Conclusion

This simple calculator program demonstrates basic C programming concepts including user input, switch statements, and arithmetic operations. It provides a foundation for building more advanced calculator applications.

Updated on: 2026-03-15T13:17:05+05:30

22K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements