C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Decision Making Programs in C

Simple calculator using if-else

Introduction

A calculator performs basic arithmetic operations such as:

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)

In this program:

  • The user enters two numbers and an operator.
  • The program checks the operator using if-else and performs the corresponding operation.
  • Invalid operator inputs are handled gracefully.

 

C Program: Simple Calculator using if-else

C

#include <stdio.h>

 

int main() {

    float num1, num2, result;

    char op;

 

    // Input two numbers

    printf("Enter first number: ");

    scanf("%f", &num1);

 

    printf("Enter second number: ");

    scanf("%f", &num2);

 

    // Input operator

    printf("Enter an operator (+, -, *, /): ");

    scanf(" %c", &op);  // space before %c to ignore newline

 

    // Perform operation using if-else

    if (op == '+') {

        result = num1 + num2;

        printf("Result: %.2f + %.2f = %.2f\n", num1, num2, result);

    }

    else if (op == '-') {

        result = num1 - num2;

        printf("Result: %.2f - %.2f = %.2f\n", num1, num2, result);

    }

    else if (op == '*') {

        result = num1 * num2;

        printf("Result: %.2f * %.2f = %.2f\n", num1, num2, result);

    }

    else if (op == '/') {

        if (num2 != 0) {

            result = num1 / num2;

            printf("Result: %.2f / %.2f = %.2f\n", num1, num2, result);

        } else {

            printf("Error: Division by zero is not allowed.\n");

        }

    }

    else {

        printf("Invalid operator!\n");

    }

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter first number: 20
Enter second number: 5
Enter an operator (+, -, *, /): /

Result: 20.00 / 5.00 = 4.00


OUTPUT 2 :

Enter first number: 10
Enter second number: 3
Enter an operator (+, -, *, /): $

Invalid operator!
 

Explanation

  1. User inputs two numbers and an operator.
  2. if-else checks the operator:
    • + → Addition
    • - → Subtraction
    • * → Multiplication
    • / → Division (with zero check)
  3. If the operator is invalid, an error message is shown.