C is a very easy and beginner-friendly language to learn the concept of writing a simple calculator program. Creating a simple calculator in C can help you understand various concepts like input/output handling, variable declarations, handling exceptions, etc. In this blog, we will delve deep into making a simple and useful calculator program in C with different approaches, code examples, etc.
To create a calculator program in C, we need to have a clear understanding of control statements or control structures. The control statements are the most important part of writing a calculator program in C as they play a vital role in the decision-making and repetition process in the program. Throughout this blog, you will understand the different logic to create a simple calculator program.
But before we move on to the different approaches, let’s first understand a simple algorithm to create a calculator program in C. Let’s get started.
Algorithm to write a simple calculator program in C
Creating a calculator in C is very simple and the algorithm behind this is also very easy. We will understand the algorithm in steps and see how we can implement this in C using one of the approaches that we will discuss later in this blog. Below is a detailed algorithm for creating a simple calculator program in C using the if-else statement approach:
Initialising the variables to get the user inputs like two numbers (num1 and num2) and choice of operator (either +, -, *, /). Input variables can be declared in float, double, or int type.
Getting the input from the users. Next, we will ask the user for the two input numbers (as operands) on which we will perform the arithmetic operation. Another input will be to get the operator.
Performing Calculation. Next, we will calculate and perform the arithmetic operations on the two input numbers. The calculation will be done based on the user’s choice that he entered earlier. To do this, the control statements are used like if-else, switch, while, etc.
After the calculation, the result is then printed and displayed to the user using the printf() statement in C.
End the program and exit.
Pseudocode
Let’s now understand the pseudocode for the discussed algorithm that you can not only apply in C language, but in other languages also. The pseudocode for creating a simple calculator program in C is:
START
DECLARE char arithmeticOperator
DECLARE int firstNum, secondNum
DECLARE int sumResult
PRINT "Enter operator choice from (+, -, *, /): "
READ arithmeticOperator
PRINT "Enter the first number: "
READ firstNum
PRINT "Enter the second number: "
READ secondNum
IF arithmeticOperator == '+'
sumResult = firstNum+ secondNum
ELSE IF arithmeticOperator == '-'
sumResult = firstNum - secondNum
ELSE IF arithmeticOperator == '*'
sumResult = firstNum * secondNum
ELSE IF arithmeticOperator == '/'
IF secondNum != 0
sumResult = firstNum / secondNum
ELSE
PRINT "Error! Division by zero with a number is not possible"
EXIT
ELSE
PRINT "Error! Arithmetic Operator is not correct."
EXIT
PRINT "The result is: ", sumResult
END
The given pseudocode uses the if-else statement to demonstrate how we can create a simple calculator program in c. If you can understand this algorithm and pseudocode clearly and know how to declare variables, how to handle user input and handle the errors and exceptions, you’re good to go.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Approaches
In C language, there are various approaches by which you can write a simple calculator program. We will discuss the common approaches to creating a calculator program in C, and these are:
Using If-else statement
Using a switch case statement
Using functions
Let’s discuss these approaches in detail with the code examples, their explanation, and the respective output of each example.
1. Using If-else statement
The first approach or method for creating a simple calculator program is to leverage the If-else statements of C language. The if-else statement is a very common and easy approach to use for creating a calculator program in which there are multiple if conditions like, if there is addition, use the + operator to add the two inputs, similarly if there is a need to subtract two numbers, simply use the – operator, and this will work for other operators like divide (/), multiplication (*), etc.
This approach is very useful for determining the answer and applying arithmetic operations based on which operator the user provides in the inputs. Let’s see a detailed example now for creating a calculator using if-else statements:
Code example:
#include <stdio.h>
int main() {
// declaring a variable to get operator choice
char arOpChoice;
// Asking for an arithmetic operator from the user
printf("Enter an arithmetic operator (+, -, *, /): ");
scanf("%c", &arOpChoice);
// declaring two user inputs to be taken by the user
int firstNum, secondNum;
// declaring the result variable to be used to add the sum of two numbers
int sumResult;
// Taking two input numbers from the user
printf("Enter the first number: ");
scanf("%d", &firstNum);
printf("Enter the second number: ");
scanf("%d", &secondNum);
// Performing the arithmetic operation based on the user's choice
if (arOpChoice == '+') {
sumResult = firstNum + secondNum;
} else if (arOpChoice == '-') {
sumResult = firstNum - secondNum;
} else if (arOpChoice == '*') {
sumResult = firstNum * secondNum;
} else if (arOpChoice == '/') {
// checking a new condition if the number is asked to be divided by 0 or not
if (secondNum != 0) {
sumResult = firstNum / secondNum;
} else {
printf("Error! You can't divide any number by zero.n");
return 1;
}
// if operator is entered wrong or invalid by the user
} else {
printf("Error! You have entered the wrong operator. Please enter the operator as per choice given.n");
return 1;
}
// Printing the result
printf("Result: %dn", sumResult);
return 0;
}
Output:
Enter an arithmetic operator (+, -, *, /): +
Enter the first number: 34
Enter the second number: 34
Result: 68
Enter an arithmetic operator (+, -, *, /): -
Enter the first number: 32
Enter the second number: 12
Result: 20
Enter an arithmetic operator (+, -, *, /): *
Enter the first number: 24
Enter the second number: 10
Result: 240
Enter an arithmetic operator (+, -, *, /): /
Enter the first number: 56
Enter the second number: 2
Result: 28
Enter an arithmetic operator (+, -, *, /): /
Enter the first number: 32
Enter the second number: 0
Error! You can't divide any number by zero
Explanation:
In this example, we are using an if-else statement to perform the calculations in C. Here, the if-else statement performs the arithmetic operations conditionally. Like, if the user enters the + operator, then that block of if-statement will be executed, etc. We have run the different cases and displayed the actual output after running the whole program.
2. Using Switch case statement
Another approach for creating a simple calculator program is to leverage the switch case statement of C language. Using the switch case statement allows you to handle multiple conditions effectively and will make your code look clearer. The working of a switch statement is easy, wherein it checks first for the choice variable (i.e.,+, -, *, or /) in the upcoming example. This choice variable is usually a character. After which it executes the appropriate case block with the arithmetic operation defined in that case.
This approach is straightforward, but it will make your code difficult when scaled or when the cases are increased. Let’s see a detailed example now for creating a calculator using switch case statements:
Code example:
#include <stdio.h>
int main() {
// declaring a variable to get operator choice
char arOpChoice;
// Asking for an arithmetic operator from the user
printf("Enter an arithmetic operator (+, -, *, /): ");
scanf("%c", &arOpChoice);
// declaring two user inputs to be taken by the user
int firstNum, secondNum;
// declaring the result variable to be used to add the sum of two numbers
int sumResult;
// Taking two input numbers from the user
printf("Enter the first number: ");
scanf("%d", &firstNum);
printf("Enter the second number: ");
scanf("%d", &secondNum);
// Performing the arithmetic operation based on the user choice in the switch case
switch (arOpChoice) {
case '+':
sumResult = firstNum + secondNum;
break;
case '-':
sumResult = firstNum - secondNum;
break;
case '*':
sumResult = firstNum * secondNum;
break;
case '/':
if (secondNum != 0) {
sumResult = firstNum / secondNum;
} else {
printf("Error! You can't divide any number by zero.n");
return 1;
}
break;
default:
printf("Error! You have entered the wrong operator. Please enter the operator as per choice given. n");
return 1;
}
// Printing the result
printf("Result: %dn", sumResult);
return 0;
}
Output:
Enter an arithmetic operator (+, -, *, /): +
Enter the first number: 33
Enter the second number: 23
Result: 56
Enter an arithmetic operator (+, -, *, /): -
Enter the first number: 52
Enter the second number: 7
Result: 45
Enter an arithmetic operator (+, -, *, /): *
Enter the first number: 300
Enter the second number: 4
Result: 1200
Enter an arithmetic operator (+, -, *, /): /
Enter the first number: 34
Enter the second number: 10
Result: 3
Enter an arithmetic operator (+, -, *, /): /
Enter the first number: 90
Enter the second number: 0
Error! You can't divide any number by zero.
Explanation:
In this example, we are using a switch statement to perform the calculations in C. Here, the switch statement is used to perform the arithmetic operations. We have run the different cases and displayed the actual output after running the whole program.
3. Using C function
Another approach that you can leverage is using the functions in C. To create a calculator program, you can define different functions to handle different arithmetic operations. You can create a function that will only calculate the addition of two numbers by taking two input parameters, num1 and num2, and return their result. Similarly, other functions like subtraction, multiplication, or division of two numbers can also be created to calculate the result.
This approach makes the program more concise, more modular code, etc. The functions used in creating a calculator can be reused in other parts of the program or anywhere else. Let’s see a detailed example now for creating a calculator using a functional approach:
Code example:
#include <stdio.h>
int main() {
// declaring a variable to get operator choice
char arOpChoice;
// Asking for an arithmetic operator from the user
printf("Enter an arithmetic operator (+, -, *, /): ");
scanf("%c", &arOpChoice);
// declaring two user inputs to be taken by the user
int firstNum, secondNum;
// declaring the result variable to be used to add the sum of two numbers
int sumResult;
// Taking two input numbers from the user
printf("Enter the first number: ");
scanf("%d", &firstNum);
printf("Enter the second number: ");
scanf("%d", &secondNum);
// Performing the arithmetic operation based on the user's choice
if (arOpChoice == '+') {
sumResult = addNumbers(firstNum, secondNum);
} else if (arOpChoice == '-') {
sumResult = subtractNumbers(firstNum, secondNum);
} else if (arOpChoice == '*') {
sumResult = multiplyNumbers(firstNum, secondNum);
} else if (arOpChoice == '/') {
sumResult = divideNumbers(firstNum, secondNum);
// if operator is entered wrong or invalid by the user
} else {
printf("Error! You have entered the wrong operator. Please enter the operator as per choice given.n");
return 1;
}
// Printing the result
printf("Result: %dn", sumResult);
return 0;
}
//declaring an add function to add two numbers
int addNumbers(int n1, int n2) {
return n1 + n2;
}
//declaring a subtract function to subtract two numbers
int subtractNumbers(int n1, int n2) {
return n1 - n2;
}
//declaring a multiply function to multiply two numbers
int multiplyNumbers(int n1, int n2) {
return n1 * n2;
}
//declaring a divide function to divide two numbers
int divideNumbers(int n1, int n2) {
// checking a new condition if the number is asked to be divided by 0 or not
if(n2 != 0) return n1 / n2;
else {
printf("Error! You can't divide any number by zero.n");
return 1;
}
}
Output:
Enter an arithmetic operator (+, -, *, /): /
Enter the first number: 523
Enter the second number: 20
Result: 26
Enter an arithmetic operator (+, -, *, /): *
Enter the first number: 43
Enter the second number: 10
Result: 430
Enter an arithmetic operator (+, -, *, /): -
Enter the first number: 30
Enter the second number: 4
Result: 26
Enter an arithmetic operator (+, -, *, /): +
Enter the first number: 78
Enter the second number: 67
Result: 145
Explanation:
In this example, we are using a functional approach to perform the calculations in C. We have defined the separate functions for each operation and returned the result between two different parameters given in those functions. Here, the if-else statement is used which calls each function based on the choice of operator (arOpChoice) given by the user in the beginning. We have run the different cases and displayed the actual output after running the whole program.
These are some of the common approaches to creating a calculator program in C but there are more approaches that you can use to write this program. Now the choice between which approach to choose depends on various factors like the program complexity, time constraints, or any specific requirements.
Conclusion
In this blog, we have learned how to create a simple calculator program in C. We have seen the different approaches or methods for creating the calculator program. The first approach of using if-else statements is discussed with their examples, then a switch case approach is also discussed where we learned how a switch statement handles the different cases in it using the input operator, and finally, we learned the functional approach where we defined the separate functions for each arithmetic operation. Now, the choice of the best approach depends on you, your needs, and your specific requirements.
FAQs
How to do calculations in C language?
In C language, you can perform the calculation using a calculator program. You can perform different arithmetic operations by using different approaches like using an if-else statement, while loop, switch case, etc.
How can I handle the division by zero exception in the calculator program?
To handle the division by zero exception, we have added a check where we check if the divisor is zero, and show the user a message that you can’t perform this operation. If you do not write this type of exceptional checks in your program, it will lead to runtime errors.
How do I create a calculator in C?
Here is a simple algorithm of calculator program in C:
Use a conditional statement like If-else or switch to check the operator.
Perform the calculation
Display the result.
Exit from the program.
Can I use this calculator program in C for complex calculations?
Yes, but the examples shown in this blog are simple. To perform more complex calculations, you can extend program example code functionality to handle complex numbers, mathematical functions, scientific computations, etc.
How do I handle invalid user input or other exceptions?
To handle the invalid user input, you can use a control flow like conditional statements including the if-else, switch statements, etc., to check if the user input is valid or not and then perform the calculation.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.