For working professionals
For fresh graduates
More
5. Array in C
13. Boolean in C
18. Operators in C
33. Comments in C
38. Constants in C
41. Data Types in C
49. Double In C
58. For Loop in C
60. Functions in C
70. Identifiers in C
81. Linked list in C
83. Macros in C
86. Nested Loop in C
97. Pseudo-Code In C
100. Recursion in C
103. Square Root in C
104. Stack in C
106. Static function in C
107. Stdio.h in C
108. Storage Classes in C
109. strcat() in C
110. Strcmp in C
111. Strcpy in C
114. String Length in C
115. String Pointer in C
116. strlen() in C
117. Structures in C
119. Switch Case in C
120. C Ternary Operator
121. Tokens in C
125. Type Casting in C
126. Types of Error in C
127. Unary Operator in C
128. Use of C Language
A simple calculator program in C lets you perform basic arithmetic operations like addition, subtraction, multiplication, and division. But how do you build one? This guide compares various methods to help you choose the best approach.
In this tutorial, you'll walk through these methods in a simple calculator program in C. By the end, you’ll know which method best suits your needs.
Boost your C programming skills with our Software Development courses — take the next step in your learning journey!
A simple calculator program in C allows you to perform basic arithmetic operations like addition, subtraction, multiplication, and division. The switch statement is one of the easiest and most efficient ways to implement this kind of program.
It evaluates an expression and then executes the corresponding case block based on the result.
Let’s look at this implementation:
#include <stdio.h>
int main() {
// Declare variables for input and result
int num1, num2, result;
char operator;
// Display menu options to the user
printf("Select an operation (+, -, *, /): ");
scanf(" %c", &operator); // Takes the operator input
// Take two integer inputs
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// Switch statement to handle the operation based on user input
switch (operator) {
case '+':
result = num1 + num2; // If operator is '+', add the numbers
break;
case '-':
result = num1 - num2; // If operator is '-', subtract the numbers
break;
case '*':
result = num1 * num2; // If operator is '*', multiply the numbers
break;
case '/':
if (num2 != 0) { // Check if divisor is not zero
result = num1 / num2; // If operator is '/', divide the numbers
} else {
printf("Error: Division by zero is not allowed.\n");
return 1; // Exit if division by zero occurs
}
break;
default:
printf("Invalid operator!\n"); // If user enters an invalid operator
return 1; // Exit if invalid operator is entered
}
// Display the result
printf("Result: %d\n", result);
return 0;
}
Output:
For an input of 5 and 3 with the operator +:
Select an operation (+, -, *, /): +
Enter two numbers: 5 3
Result: 8
For an input of 6 and 2 with the operator /:
Select an operation (+, -, *, /): /
Enter two numbers: 6 2
Result: 3
Explanation:
You can also if (scanf("%d", &num1) != 1) to check for invalid input and prompt the user again.
When to Use This Method:
Also Read: Difference Between C and Java: Which One Should You Learn?
Next, let’s explore how if-else if statements offer more flexibility in building your calculator.
In the if-else if method, the calculator logic is driven by a series of conditional checks that evaluate the operator entered by the user. This approach is more flexible than the switch statement, as it allows multiple conditions to be tested in sequence.
Before performing calculations, it's important to note that C follows operator precedence rules. For example, multiplication and division are evaluated before addition and subtraction, unless parentheses change the order.
Here’s how to implement a simple calculator program in C using if-else if statements.
#include <stdio.h>
int main() {
// Declare variables for numbers and result
int num1, num2, result;
char operator;
// Display the operation choices to the user
printf("Select an operation (+, -, *, /): ");
scanf(" %c", &operator); // Taking operator input
// Take two integer inputs from the user
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// Using if-else if statements to check the operator and perform the calculation
if (operator == '+') {
result = num1 + num2; // Perform addition if operator is '+'
}
else if (operator == '-') {
result = num1 - num2; // Perform subtraction if operator is '-'
}
else if (operator == '*') {
result = num1 * num2; // Perform multiplication if operator is '*'
}
else if (operator == '/') {
if (num2 != 0) {
result = num1 / num2; // Perform division if operator is '/' and num2 is not zero
} else {
printf("Error: Division by zero is not allowed.\n");
return 1; // Exit the program if division by zero occurs
}
}
else {
printf("Invalid operator!\n"); // Handle invalid operator input
return 1; // Exit if operator is not valid
}
// Display the result of the operation
printf("Result: %d\n", result);
return 0;
}
Output:
For input 5 and 3 with the operator +:
Select an operation (+, -, *, /): +
Enter two numbers: 5 3
Result: 8
For input 6 and 2 with the operator /:
Select an operation (+, -, *, /): /
Enter two numbers: 6 2
Result: 3
Explanation:
When to Use This Method:
Also Read: Top 25+ C Programming Projects for Beginners and Professionals
Now that we’ve covered the basics, let’s add a loop to keep the calculator running, using a do-while and switch statement combo.
In this method, we will use a do-while loop combined with a switch statement to build a simple calculator program in C that can perform multiple operations without restarting the program. The do-while loop ensures that the calculator keeps running until the user quits, making it more interactive and user-friendly.
Let’s explore how to implement this functionality with the help of the switch statement.
#include <stdio.h>
int main() {
// Declare variables for numbers, result, and operator
int num1, num2, result;
char operator;
char continueChoice;
// Do-while loop to keep the calculator running until the user chooses to exit
do {
// Display operation choices to the user
printf("Select an operation (+, -, *, /): ");
scanf(" %c", &operator); // Taking operator input
// Take two numbers as input from the user
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// Switch statement to handle the operation based on user input
switch (operator) {
case '+':
result = num1 + num2; // Perform addition
break;
case '-':
result = num1 - num2; // Perform subtraction
break;
case '*':
result = num1 * num2; // Perform multiplication
break;
case '/':
if (num2 != 0) {
result = num1 / num2; // Perform division, check for zero division
} else {
printf("Error: Division by zero is not allowed.\n");
continue; // Skip to the next iteration of the loop
}
break;
default:
printf("Invalid operator!\n");
continue; // Skip to the next iteration if invalid operator is entered
}
// Display the result of the operation
printf("Result: %d\n", result);
// Ask the user if they want to perform another calculation
printf("Do you want to perform another calculation? (y/n): ");
scanf(" %c", &continueChoice); // Read user input to continue or exit
} while (continueChoice == 'y' || continueChoice == 'Y'); // Continue if user chooses 'y'
printf("Thank you for using the calculator. Goodbye!\n"); // Exit message
return 0;
}
Output:
For an input of 5 and 3 with the operator +:
Select an operation (+, -, *, /): +
Enter two numbers: 5 3
Result: 8
Do you want to perform another calculation? (y/n): y
For an input of 6 and 2 with the operator /:
Select an operation (+, -, *, /): /
Enter two numbers: 6 2
Result: 3
Do you want to perform another calculation? (y/n): n
Thank you for using the calculator. Goodbye!
Explanation:
When to Use This Method:
Also Read: Command Line Arguments in C Explained
Now, let’s take the modular approach by using functions with a switch statement for a more organized and scalable calculator.
In this approach, you use functions to handle each operation, while a switch statement calls the respective function based on the user's choice. This modular programming technique improves the organization of your code and allows for easy maintenance and scalability.
Instead of cluttering the main() function, each operation is neatly separated into its own function, which can be reused or updated independently. Let’s dive into the code.
#include <stdio.h>
// Function to perform addition
int add(int num1, int num2) {
return num1 + num2;
}
// Function to perform subtraction
int subtract(int num1, int num2) {
return num1 - num2;
}
// Function to perform multiplication
int multiply(int num1, int num2) {
return num1 * num2;
}
// Function to perform division
int divide(int num1, int num2) {
if (num2 != 0) {
return num1 / num2;
} else {
printf("Error: Division by zero is not allowed.\n");
return 0; // Return 0 in case of division by zero
}
}
int main() {
// Declare variables for numbers and operator
int num1, num2, result;
char operator;
// Display the operation choices to the user
printf("Select an operation (+, -, *, /): ");
scanf(" %c", &operator); // Taking operator input
// Take two numbers as input from the user
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// Switch statement to call the respective function based on the operator
switch (operator) {
case '+':
result = add(num1, num2); // Call add function
break;
case '-':
result = subtract(num1, num2); // Call subtract function
break;
case '*':
result = multiply(num1, num2); // Call multiply function
break;
case '/':
result = divide(num1, num2); // Call divide function
break;
default:
printf("Invalid operator!\n");
return 1; // Exit if the operator is invalid
}
// Display the result of the operation
printf("Result: %d\n", result);
return 0;
}
Output:
For an input of 5 and 3 with the operator +:
Select an operation (+, -, *, /): +
Enter two numbers: 5 3
Result: 8
For an input of 6 and 2 with the operator /:
Select an operation (+, -, *, /): /
Enter two numbers: 6 2
Result: 3
Explanation:
When to Use This Method:
Also Read: Top 9 Popular String Functions in C with Examples Every Programmer Should Know in 2025
Now that we’ve explored different methods for creating a simple calculator program in C, we can compare them and determine which works best for various scenarios.
Each method has its strengths and drawbacks, depending on the requirements of your program. To help you decide, here’s a comparison table highlighting each approach's advantages, disadvantages and complexity.
Method | Advantages | Disadvantages | Complexity |
Switch Statement | - Simple to implement - Clean and efficient for fixed operations - Easy to read | - Limited to a fixed set of operations - Not flexible for complex conditions | Low |
If-Else If Statement | - Flexible for more complex conditions - Easy to modify for more operations | - Can become messy with many conditions - Less efficient for multiple options | Medium |
Do-While Loop and Switch | - Keeps the calculator running continuously - Simple to use for repeat operations | - Needs additional logic for stopping conditions - More complex for beginners | Medium |
Function and Switch Statement | - Modular and organized - Easy to extend with new operations - Easier maintenance | - Requires more functions to be defined - Can become cumbersome for simple tasks | High |
By understanding these methods and their trade-offs, you can decide which approach to take for your next simple calculator program in C!
Test your understanding of building a simple calculator program in C with these questions! From basic concepts to more advanced applications, let’s see how well you know the various methods used for building calculators in C.
1. What is the purpose of a switch statement in a simple calculator program in C?
A) To loop through operations
B) To handle multiple operations based on user input
C) To store the result of calculations
D) To perform arithmetic operations directly
2. Which of the following is a key advantage of using an if-else if statement in a simple calculator program in C?
A) It simplifies the code
B) It handles complex conditions and multiple operations
C) It automatically prevents division by zero
D) It is faster than a switch statement
3. When would you prefer using a do-while loop in a calculator program in C?
A) For a program that only performs one calculation
B) When you want the program to continuously allow the user to perform multiple operations until they choose to exit
C) To simplify the menu structure
D) To avoid the need for function calls
4. What is the primary benefit of breaking down operations into functions in a calculator program in C?
A) It makes the program slower but more readable
B) It makes the program modular, organized, and scalable
C) It reduces the number of operations you need to perform
D) It makes error handling easier
5. Which of the following statements about the switch statement in C is true for a calculator program?
A) It allows you to handle only one operation at a time
B) It can handle both arithmetic operations and input validation
C) It is most efficient for programs with a fixed number of operations
D) It is the best choice when dealing with complex logical conditions
6. Which method best suits a calculator program that performs multiple operations continuously without restarting?
A) If-else if statements
B) Do-while loop with switch
C) Function-based approach
D) Simple switch statement
7. What is the main disadvantage of using too many if-else if statements in a calculator program in C?
A) The code becomes harder to maintain and less readable
B) The program will execute faster
C) It automatically handles edge cases
D) It increases the modularity of the program
8. What would happen in a simple calculator program if you used an infinite loop without a way to exit the program?
A) The program will perform calculations only once
B) The program will continuously ask for new input without stopping
C) The program will throw an error message
D) The program will terminate after one calculation
9. Why is it useful to separate each operation into a function in a calculator program?
A) It makes the program easier to understand and extend
B) It reduces the program’s execution time
C) It automatically handles user input
D) It avoids the use of switches
10. Which method should you use if your calculator program requires both flexibility and readability when adding or removing operations?
A) Simple switch statement
B) If-else if statement
C) Function with switch statement
D) Do-while loop
Understanding how to build a simple calculator program in C is just the beginning—keep enhancing your C programming skills with expert-led courses and hands-on projects.
upGrad offers comprehensive courses that dive deeper into C programming, helping you master concepts like function-based programming, loops, switch statements, and more.
Check out some of the best upGrad’s courses:
You can also get personalized career counseling with upGrad to guide your career path, or visit your nearest upGrad center and start hands-on training today!
Similar Reads:
Explore C Tutorials: From Beginner Concepts to Advanced Techniques
Array in C: Introduction, Declaration, Initialisation and More
Exploring Array of Pointers in C: A Beginner's Guide
What is C Function Call Stack: A Complete Tutorial
Binary Search in C
Constant Pointer in C: The Fundamentals and Best Practices
Dangling Pointer in C: Causes, Risks, and Prevention Techniques
Find Out About Data Structures in C and How to Use Them?
A. You can easily extend your simple calculator program in C by adding more case statements in the switch block or adding new functions for additional operations. Ensure you update the menu for the new options.
A. Yes, input validation can be added by checking if the user enters valid numbers or operators before performing operations. You can use if or switch conditions to ensure correct input.
A. To improve user experience, provide clear instructions, display operation results after every calculation, and give users an option to continue or exit after each operation.
A. While a for loop can be used, a do-while loop is more suitable for repeated operations in a simple calculator program in C, as it ensures the calculator runs at least once before checking the exit condition.
A. Yes, division by zero can be handled using a conditional check before performing the division. If the second number is zero, display an error message and prevent the division operation.
A. For performance optimization, avoid repetitive code by using functions for different operations, and keep the logic simple. Also, ensure that your program only runs necessary calculations without excessive condition checks.
A. Yes, you can modify the program to handle floating-point numbers by changing the data type of the numbers and the result from int to float or double.
A. You can implement a feature where users can perform multiple operations sequentially by keeping the calculator running in a loop and updating the result after each operation.
A. Using functions for each operation and a switch statement to handle user input makes your simple calculator program in C scalable. It allows for easy addition of new operations in the future.
A. A simple menu can be implemented using printf to display options and scanf to take the user’s input. Then, use the input in a switch or if-else structure to perform the corresponding operation.
A. Yes, you can build a GUI-based calculator in C using libraries like GTK or Qt. However, this would require more advanced programming beyond a console-based simple calculator program in C.
Take a Free C Programming Quiz
Answer quick questions and assess your C programming knowledge
Author
Start Learning For Free
Explore Our Free Software Tutorials and Elevate your Career.
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.