Simple calculator program in C
In this post, you will learn how to write a Simple Calculator program using the C programming language. By using this, you can develop a simple calculator that displays the different arithmetical operations, i.e., addition, subtraction, multiplication, and division.
Algorithm of Simple Calculator
Step 1: Declare local variables
Step 2: Enter any operator at runtime
Step 3: Enter any two integer values at runtime
Step 4: Enter the Choice
Step 5: Apply switch case to select the operator:
case '+': result = num1 + num2;
break;
case '-': result = num1 - num2;
break;
case '*': result = num1 * num2;
break;
case '/': result = num1 / num2;
break;
default: printf("\n Invalid Operator ");
Step 5: Print the result
C program for Simple Calculator
Here is the C program to create a calculator using the switch statement.
#include <stdio.h>
int main(){
char opt;
int num1, num2, result = 0;
printf("\nEnter any one operator( +, -, *, /): ");
scanf("%c", &opt);
printf("Enter two numbers : ");
scanf("%d%d", &num1, &num2);
switch(opt){
case '+':
printf("%d + %d =\t%d\n",num1,num2,num1+num2);
break;
case '-':
printf("%d - %d =\t%d\n",num1,num2,num1-num2);
break;
case '*':
printf("%d * %d =\t%d\n",num1,num2,num1*num2);
break;
case '/':
printf("%d / %d =\t%d\n",num1,num2,num1/num2);
break;
default: printf("\n Invalid Operator ");
}
return 0;
}
Output of the above code:
Enter any one operator( +, -, *, /): *
Enter two numbers : 79 5
79 * 5 = 395
Enter any one operator( +, -, *, /): +
Enter two numbers : 906 450
906 + 450 = 1356
The * operator entered by the user is stored in opt. And, the two operands, 79 and 5 are stored in first and second respectively.
Related Articles
Prime factors of a number in cArmstrong number program in c
Write a program to check leap year in c
C program to find area of rectangle
C program to convert celsius to fahrenheit
Fibonacci series program in C using recursion
Write a program to find area of circle in C
C program to find greatest of three numbers
C program for addition of two numbers
C program to calculate compound interest
C program to find the ASCII value of a character
C program to convert Decimal to Octal
C program to convert decimal to binary
Write a C program to calculate Simple Interest
C program to check whether a number is even or odd
C program to reverse a number
C program to check palindrome number
C program to check whether an alphabet is a vowel or consonant
Program to find square root of a number in C
C program to check whether a number is positive or negative