C Program to Make a Simple Calculator using if/else statements
A simple calculator includes addition, subtraction, multiplication, and division.
This calculator program in C helps the user to enter the Operator (+, -, *, or /) and two values. Using those two values and operand, it will perform Arithmetic Operations.
#include <stdio.h>
int main()
{
char opt;
int n1, n2;
float r;
printf (" Select an operator (+, -, *, /,) to perform an operation in C calculator \n ");
scanf ("%c", &opt); printf (" Enter the first number: ");
scanf(" %d", &n1);
printf (" Enter the second number: ");
scanf (" %d", &n2);
if (opt == '+')
{
r = n1 + n2;
printf (" Addition of %d and %d is: %f", n1, n2, r);
}
else if (opt == '-')
{
r = n1 - n2; // subtract two numbers
printf (" Subtraction of %d and %d is: %f", n1, n2, r);
}
else if (opt == '*')
{
r = n1 * n2; // multiply two numbers
printf (" Multiplication of %d and %d is: %f", n1, n2, r);
}
else if (opt == '/')
{
if (n2 == 0)
{
printf (" \n Divisor cannot be zero. Please enter another value ");
scanf ("%d", &n2);
}
r= n1 / n2;
printf (" Division of %d and %d is: %.2f", n1, n2, r);
}
else
{
printf(" \n You have entered wrong inputs ");
}
return 0;
}
You can use other methods also to solve this problem. This is the simplest way one can approach it.