Notification texts go here Contact Us Buy Now!

C Programming: Basic Calculator

C Programming: Basic Calculator

In this C programming tutorial, we'll create a basic calculator that takes user input for an operator and two numbers, performs the requested operation, and displays the result.

Code: Simple Calculator in C


#include <stdio.h>

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

    printf("\nEnter an operator (+ - * /):");
    scanf("%c", &operator);

    printf("\nEnter number 1:");
    scanf("%lf", &num1);

    printf("\nEnter number 2:");
    scanf("%lf", &num2);

    switch (operator) {
        case '+':
            result = num1 + num2;
            printf("Result: %.2lf", result);
            break;
        case '-':
            result = num1 - num2;
            printf("Result: %.2lf", result);
            break;
        case '*':
            result = num1 * num2;
            printf("Result: %.2lf", result);
            break;
        case '/':
            result = num1 / num2;
            printf("Result: %.2lf", result);
            break;
        default:
            printf("%c is not valid", operator);
    }

    return 0;
}
    

This C program allows users to input an operator (+, -, *, /) and two numbers. It then performs the requested operation and displays the result with two decimal places.

Explanation:

The code uses the switch statement to determine the operation based on the entered operator. The result is calculated accordingly and displayed to the user.

Conclusion

You've just created a simple calculator using C programming! This example is a great introduction to basic user input and decision-making in C. Feel free to experiment with the code and explore more advanced programming concepts.

If you have any questions or need further clarification, don't hesitate to leave a comment below.

About the Author

Coding | Riding | Music, Embracing the beauty of code, the thrill of the ride, and the rhythm of life. Let's explore the journey together!

1 comment

  1. This is my first comment
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.
Code Copied!