Easy to creating a Simple calculator in C.

blog img

Here’s a simple calculator program in C that performs basic operations such as addition, subtraction, multiplication, and division:

c

#include <stdio.h>

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

    // Input operator from the user
    printf("Enter an operator (+, -, *, /): ");
    scanf("%c", &operator);

    // Input two numbers from the user
    printf("Enter two numbers: ");
    scanf("%lf %lf", &num1, &num2);

    // Perform the operation based on the operator
    switch (operator) {
        case '+':
            result = num1 + num2;
            printf("%.2lf + %.2lf = %.2lf\n", num1, num2, result);
            break;
        case '-':
            result = num1 - num2;
            printf("%.2lf - %.2lf = %.2lf\n", num1, num2, result);
            break;
        case '*':
            result = num1 * num2;
            printf("%.2lf * %.2lf = %.2lf\n", num1, num2, result);
            break;
        case '/':
            if (num2 != 0) {
                result = num1 / num2;
                printf("%.2lf / %.2lf = %.2lf\n", num1, num2, result);
            } else {
                printf("Error: Division by zero is not allowed.\n");
            }
            break;
        default:
            printf("Error: Invalid operator.\n");
    }

    return 0;
}

Explanation:

1. The program asks the user to input an operator (+, -, *, /).

2. The user is then prompted to input two numbers.

3. Based on the operator provided, the program calculates the result and displays it.

4. For division, the program checks if the divisor is zero to prevent division by zero errors.

Example Output:

c result

Enter an operator (+, -, *, /): +
Enter two numbers: 5 10
5.00 + 10.00 = 15.00

Share your thoughts

Your email address will not be published. All fields are required.

Related post

  1. Easy to read and write the JSON file

    In C, you can handle JSON data by using libraries…

  1. Easy to create a file in C program.

    To create a file in C programming language, you typically…

  1. Easy way to learn – Arithmetic operators in C

    Here’s a simple example of a C program that performs…

  1. Functions in C – how it’s work

    In C, functions are blocks of code that perform specific…

  1. How to learn constructor – in C

    In C, a constructor is not a built-in feature like…

Popular post

  1. Eclipse IDE – Create New Java Project.

    Opening the New Java Project…

  1. How to start the project in android studio

    Android Studio Open the Android…

  1. How to use ACOSH function in excel

    The ACOSH function returns the…

  1. Complete Header tags in html – easy to learn

    H tags can be used…

  1. Best features in Python programme – easy to learn

    Python is the most widely…