C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Evaluate Arithmetic Expression Program in C

Introduction

In C, arithmetic expressions consist of operands (numbers) and operators (+, -, *, /, %).
This program allows the user to enter an arithmetic expression and evaluates it.

We’ll handle:

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)
  • Modulus (%) (for integers only)

 

C Program: Evaluate Arithmetic Expression

C

#include <stdio.h>

 

int main() {

    float num1, num2, result;

    char op;

 

    printf("Enter an arithmetic expression (e.g., 12 + 5): ");

    scanf("%f %c %f", &num1, &op, &num2);

 

    switch (op) {

        case '+':

            result = num1 + num2;

            printf("Result: %.2f\n", result);

            break;

        case '-':

            result = num1 - num2;

            printf("Result: %.2f\n", result);

            break;

        case '*':

            result = num1 * num2;

            printf("Result: %.2f\n", result);

            break;

        case '/':

            if (num2 != 0)

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

            else

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

            break;

        case '%':

            // Modulus only works with integers

            if ((int)num2 != 0)

                printf("Result: %d\n", (int)num1 % (int)num2);

            else

                printf("Error: Division by zero in modulus.\n");

            break;

        default:

            printf("Invalid operator! Use +, -, *, /, or %%\n");

    }

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter an arithmetic expression (e.g., 12 + 5): 12 + 5
Result: 17.00

OUTPUT 2 :
Enter an arithmetic expression (e.g., 12 + 5): 25 / 5
Result: 5.00

OUTPUT 3 :
Enter an arithmetic expression (e.g., 12 + 5): 20 % 3
Result: 2


OUTPUT 4 :
Enter an arithmetic expression (e.g., 12 + 5): 10 / 0
Error: Division by zero is not allowed.

Explanation

  1. Input is taken as:

 

number1 operator number2

Example: 25 * 4

 

  1. switch statement checks which operator (+, -, *, /, %) was entered.
  2. Performs calculation and prints result.
  3. Includes checks to avoid division by zero.
  4. % operator is handled separately since it only applies to integers.