+1 vote
in Programming Languages by (73.8k points)
I want to create a basic calculator using C programming. The code should perform addition, subtraction, multiplication, division, and remainder based on user input. Please give me the C code for the basic calculator.

1 Answer

+3 votes
by (56.5k points)
selected by
 
Best answer

Here is the basic calculator written in C programming language. It performs all basic mathematical operations.

#include <stdio.h>

int main() {

    char operator;

    float num1, num2, result;

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

    scanf("%c", &operator);

    printf("Enter two numbers: ");

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

    switch(operator) {

        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;

        case '%':

            result = (int)num1 % (int)num2;

            break;

        default:

            printf("Error! wrong operator provided.\n");

            return -1;   

    }

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

    return 0;

}


...