View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Calculator Program in C

Updated on 14/02/202516,213 Views

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!

Calculator Program in C Using Switch Statement

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:

  • Variable Declaration:
    • int num1, num2, result; - Variables to store the two input numbers and the result.
    • char operator; - A variable to store the operator entered by the user.
  • Menu Display:
    • printf("Select an operation (+, -, *, /): "); - Displays the menu to let the user choose an operation.
    • scanf(" %c", &operator); - Takes the operator input from the user. Notice the space before %c in scanf. It ensures any leftover newline characters are ignored.
  • Taking Inputs:
    • scanf("%d %d", &num1, &num2); - Reads two integers from the user for the calculation.
    • To handle decimals, use float num1, num2; and %.2f in print.
  • Switch Statement:
    • switch (operator) - The core of this calculator. It checks the value of operator and executes the corresponding block of code based on the input.
      • case '+': result = num1 + num2; break; - If the user selects +, the program adds the two numbers.
      • Similar cases exist for subtraction (-), multiplication (*), and division (/).
  • Error Handling:
    • Division by zero is checked using if (num2 != 0). If the user tries to divide by zero, an error message is displayed, and the program terminates.

You can also if (scanf("%d", &num1) != 1) to check for invalid input and prompt the user again.

  • Result Display:
    • printf("Result: %d\n", result); - Outputs the result of the operation.

When to Use This Method:

  • The switch statement is ideal for a simple calculator program in C because it is straightforward and efficient in handling multiple conditions based on user input.
  • It's particularly effective when you have a fixed set of operations, such as the arithmetic operations in a basic calculator.
  • If your calculator doesn't require complex decision-making or conditions, the switch statement is perfect for simplicity and clarity.
  • Switch statements are often faster than if-else because compilers optimize them using a jump table, allowing direct branching instead of sequential checks.

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.

Calculator Program in C Using If-Else If Statement

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:

  • Variable Declaration:
    • int num1, num2, result; - Variables to store the two numbers and the result.
    • char operator; - A variable to store the operator entered by the user.
  • Menu Display:
    • printf("Select an operation (+, -, *, /): "); - Prompts the user to select an operation.
    • scanf(" %c", &operator); - Takes the operator input from the user. The space before %c ensures any leftover newline characters are ignored.
  • Taking Inputs:
    • scanf("%d %d", &num1, &num2); - Reads two integers from the user for the calculation.
    • To handle decimals, use float num1, num2; and %.2f in print.
  • If-Else If Logic:
    • if (operator == '+') - The first condition checks if the operator is addition, and if true, it adds the two numbers.
    • Similar blocks for subtraction (-), multiplication (*), and division (/).
    • The division by zero check is done with if (num2 != 0) to prevent errors.
  • Invalid Operator Handling:
    • The else statement at the end handles any invalid operator input from the user, ensuring that only valid operations are allowed.
  • Result Display:
    • printf("Result: %d\n", result); - Outputs the result of the operation.

When to Use This Method:

  • If-else statements offer great flexibility in conditional logic, especially when the user's input is uncertain.
  • This method is ideal for simple operations that require more control over the tested conditions.
  • It works well in a simple calculator program in C, where the number of operations is fixed and the conditions are straightforward.
  • This method is recommended if you need to handle complex logic, as it allows for easy customization and adjustments.

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.

Calculator Program in C Using Do-While Loop and Switch Statement

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:

  • Variable Declaration:
    • int num1, num2, result; - Variables to store the two input numbers and the result.
    • char operator, continueChoice; - The operator for the operation and a variable to store the user’s decision to continue or quit.
  • Do-While Loop:
    • The do-while loop ensures the program keeps running until the user decides to stop by pressing n or any other key.
    • do { ... } while (continueChoice == 'y' || continueChoice == 'Y'); - The loop executes the calculator functionality and then asks if the user wants to perform another calculation. If the user inputs y, the loop repeats.
  • Menu Display and Input:
    • printf("Select an operation (+, -, *, /): "); - Displays the menu of operations to the user.
    • scanf(" %c", &operator); - Reads the operator entered by the user.
    • scanf("%d %d", &num1, &num2); - Takes two integer inputs for the operation.
  • Switch Statement:
    • Based on the operator input, the switch statement executes the corresponding operation:
      • case '+': - Adds the two numbers.
      • case '-': - Subtracts the two numbers.
      • case '*': - Multiplies the two numbers.
      • case '/': - Divides the two numbers and handles division by zero.
  • Error Handling:
    • if (num2 != 0) - Prevents division by zero. If the second number is zero, an error message is displayed and the loop continues.
    • default: - If the operator is invalid, it prints an error message and asks the user to re-enter the operator.
  • Result and Continuation Prompt:
    • printf("Result: %d\n", result); - Displays the result of the operation.
    • printf("Do you want to perform another calculation? (y/n): "); - Asks the user if they want to continue.
    • scanf(" %c", &continueChoice); - Takes the user's response and checks if they want to continue the loop.
    • scanf() leaves newline characters in the buffer, which can cause issues with subsequent input. Use while (getchar() != '\n'); after scanf() to clear the buffer.

When to Use This Method:

  • The do-while loop with a switch statement is ideal when creating a simple calculator program in C that allows multiple operations without restarting the program.
  • This method is perfect for interactive applications where users must perform calculations repeatedly.
  • It’s useful when you want the calculator to be flexible, allowing users to continue as long as they wish and exit only when they explicitly decide to.

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.

Calculator Program in C Using Function and Switch Statement

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:

  • Modular Functions:
    • Each operation (addition, subtraction, multiplication, division) is implemented in its own function:
      • add(), subtract(), multiply(), and divide().
      • This makes the code modular, organized, and easier to read.
  • Function Calls:
    • The switch statement checks the operator in the main() function and calls the respective function.
    • For example, if the operator is +, the add() function is called with the two numbers as arguments, and the result is stored in the result.
  • Switch Statement:
    • The switch statement is used to select which function to call based on the operator entered by the user.
    • It keeps the code compact and ensures only the necessary function is called.
  • Error Handling:
    • The divide() function includes a check for division by zero. An error message is displayed if the second number is zero, and the result is set to 0.
    • For decimal calculations, use float or double instead of int, as int truncates decimal values, leading to inaccurate results.
  • Result Display:
    • After operating, the result is printed using printf("Result: %d\n", result);.

When to Use This Method:

  • This method is highly effective in a simple calculator program in C when you need to break down the operations into separate, reusable blocks of code.
  • Using functions makes the program scalable. New operations can be added easily without modifying the core logic.
  • It is also useful for maintaining the code, as changes to a specific operation can be made inside its function without affecting the rest of the program.

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.

Which is The Best Calculator Program in C?

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!

How Well Do You Know Building a Simple Calculator Program in C? 10 MCQs

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.

How Can upGrad Help You Master Building a Simple Calculator Program in C?

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?

FAQs

1. How can I extend my simple calculator program in C to include more operations?

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.

2. Can I add input validation in my simple calculator program in C?

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.

3. How do I make my simple calculator program in C more user-friendly?

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.

3. Can I use a for loop instead of a do-while loop in my simple calculator program in C?

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.

4. Is it possible to handle errors like division by zero in a simple calculator program in C?

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.

5. How do I optimize my simple calculator program in C for performance?

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.

6. Can I use floating-point numbers in my simple calculator program in C?

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.

7. How can I make my simple calculator program in C handle multiple operations in one go?

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.

8. What’s the best method to organize a simple calculator program in C for scalability?

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.

9. How do I implement a menu for the user in my simple calculator program in C?

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.

10. Can I create a simple calculator program in C that runs in a graphical user interface (GUI)?

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.

image

Take a Free C Programming Quiz

Answer quick questions and assess your C programming knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Start Learning For Free

Explore Our Free Software Tutorials and Elevate your Career.

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

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.