- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to write a simple calculator program using C language?
Begin by writing the C code to create a simple calculator. Then, follow the algorithm given below to write a C program.
Algorithm
Step 1: Declare variables Step 2: Enter any operator at runtime Step 3: Enter any two integer values at runtime Step 4: 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("
Invalid Operator "); Step 5: Print the result
Example
Following is the C program for calculator by using the Switch Case −
#include <stdio.h> int main(){ char Operator; float num1, num2, result = 0; printf("
Enter any one operator like +, -, *, / : "); scanf("%c", &Operator); printf("Enter the values of Operands num1 and num2
: "); scanf("%f%f", &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("
Invalid Operator "); } printf("The value = %f", result); return 0; }
Output
When the above program is executed, it produces the following result −
Enter any one operator: + Enter values of Operands num1 and num2: 23 45 The value = 68.000000
Advertisements