Make a calculator using if else in c language

C language



 Here calculator programe using if else in c language 

#include <stdio.h>


int main() 

{

    char op;

    int num1, num2, result;


    // Get operator and operands from the user

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

    scanf("%c", &op);


    printf("Enter two numbers: ");

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


    // Perform calculations based on the operator

    if (op == '+') {

        result = num1 + num2;

    } else if (op == '-') {

        result = num1 - num2;

    } else if (op == '*') {

        result = num1 * num2;

    } else if (op == '/') {

        result = num1 / num2;

    } else {

        printf("Error: Invalid operator.\n");

        return 1; // Exit with an error code

    }


    // Display the result

    printf("Result: %d %c %d = %d\n", num1, op, num2, result);


    return 0;

}

explain 

Step-by-Step Guide: Building a Simple Calculator in C

Step 1: Introduction

#include <stdio.h>

int main() 
{
    // ...
}
In the introductory section, we include the necessary header file (stdio.h) and set up the main function of our program.

Step 2: Variable Declaration

    char op;
    int num1, num2, result;
Here, we declare variables to store the operator (op), two numbers (num1 and num2), and the result of the calculation (result).

Step 3: User Input

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

    printf("Enter two numbers: ");
    scanf("%d %d", &num1, &num2);
We prompt the user to enter an operator and two numbers. The entered values are stored in the respective variables.

Step 4: Perform Calculations

    // Perform calculations based on the operator
    if (op == '+') {
        result = num1 + num2;
    } else if (op == '-') {
        result = num1 - num2;
    } else if (op == '*') {
        result = num1 * num2;
    } else if (op == '/') {
        result = num1 / num2;
    } else {
        printf("Error: Invalid operator.\n");
        return 1; // Exit with an error code
    }
Using if-else statements, we determine the operation based on the entered operator and perform the corresponding calculation. If an invalid operator is entered, an error message is displayed, and the program exits with an error code.

Step 5: Display the Result


    // Display the result
    printf("Result: %d %c %d = %d\n", num1, op, num2, result);

    return 0;
}
Finally, we display the result of the calculation.

Conclusion
Feel free to copy and paste this code into your C compiler to run and experiment with it. This simple calculator program is an excellent starting point for understanding basic programming concepts and logic.



thx for visit my site ( student )



0 Comments