Creating A Calculator
Lesson 13Author : Afrixi
Last Updated : January, 2023
here’s an example of how to create a simple calculator in C:
#include <stdio.h>
int main() {
float num1, num2, result;
char operator;
printf("Enter first number: ");
scanf("%f", &num1);
printf("Enter operator (+, -, *, /): ");
scanf(" %c", &operator);
printf("Enter second number: ");
scanf("%f", &num2);
switch(operator) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
if (num2 == 0) {
printf("Error: division by zero\n");
return 1;
}
result = num1 / num2;
break;
default:
printf("Error: invalid operator\n");
return 1;
}
printf("%.2f %c %.2f = %.2f\n", num1, operator, num2, result);
return 0;
}
Let’s go over this code step by step:
- We include the standard input/output library with
#include <stdio.h>
. - We define the
main()
function as usual, which will contain the main code of our program. - We declare three variables of type
float
to hold the two numbers and the result of the calculation, and a variable of typechar
to hold the operator. - We prompt the user to enter the first number using
printf()
and read it in usingscanf()
with the%f
format specifier. - We prompt the user to enter the operator using
printf()
and read it in usingscanf()
with the%c
format specifier. Note the space before the%c
, which is needed to consume the newline character left in the input buffer from the previousscanf()
. - We prompt the user to enter the second number using
printf()
and read it in usingscanf()
with the%f
format specifier. - We use a
switch
statement to perform the appropriate calculation based on the operator entered by the user. - For the division operation, we check if the second number is zero to avoid a division by zero error.
- We print the result of the calculation using
printf()
with the appropriate format specifier (%.2f
for a float with two decimal places). - We return 0 to indicate successful program execution. You can compile and run this code using a C compiler to create a simple calculator program that can perform basic arithmetic operations.