How to make calculator in C ?

Here's a basic example of how to make a simple calculator program in C:-

Calculator in C programming
Calculator in C programming
           
#include
#include

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

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

scanf("%c", &operator);

printf("Enter two numbers: ");

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

switch(operator)
case '+': result = num1 + num2; break; 

case '-': result = num1 - num2;
break;

case '*': result = num1 * num2;
break;

case '/': result = num1 / num2;
break;

default: printf("Error: Invalid operator");

return 0;
}

printf("%.2lf %c %.2lf = %.2lf", num1, operator, num2, result);

getch();
return 0;
}


Explanation:    

  1. We first include the standard input-output library stdio.h. In the main() function, we declare four variables: operator, num1, num2, and result. 
  2. We prompt the user to enter an operator (+, -, *, /) using the printf() function and read the operator input from the user using the scanf() function. 
  3. We prompt the user to enter two numbers using the printf() function and read the number inputs from the user using the scanf() function.
  4. We use a switch statement to perform the appropriate arithmetic operation based on the operator entered by the user. If the operator is invalid, we print an error message and return 1. 
  5. We print the result using the printf() function. 
  6. We return 0 to indicate successful program execution. 

Note: This is a very basic example of a calculator program and doesn't include input validation or error handling for situations such as division by zero.

Post a Comment

Previous Post Next Post
© 2023 Developed and Design By
NILESH NISHAD