1. Home

Explore C Tutorials: From Beginner Concepts to Advanced Techniques

Dive into our C tutorials and expand your programming skills. From fundamental concepts to advanced techniques, we've got you covered. Start your journey to C mastery today

• 130 Lessons
• 22 Hours
28

# Calculator Program in C

Updated on 19/07/20245,635 Views

The heart of every software application, even the most sophisticated ones, lies in the efficient execution of fundamental operations like addition, subtraction, multiplication, and division. Let's start by creating a simple calculator program in C. We will gradually advance towards building a complex calculator code in C that can perform scientific calculations too.

## Introduction

C programming is a robust language with diverse applications. One such application is creating a calculator program. The simplicity of the C language and its powerful features like conditional and looping statements make it an ideal choice for such applications.

## Simple Calculator Using Switch Statement

A calculator program in C using a switch statement is a classic example that illustrates the usage of switch cases for different mathematical operations.

Here is the code snippet for a simple calculator program using the switch statement:

 `#includeint main() {   int a, b, choice;   printf("Enter two integers: ");   scanf("%d %d", &a, &b);   printf("Enter choice: 1.Addition 2.Subtraction 3.Multiplication 4.Division\n");   scanf("%d", &choice);   switch(choice) {      case 1: printf("Result: %d", a + b);         break;      case 2: printf("Result: %d", a - b);         break;      case 3: printf("Result: %d", a * b);         break;      case 4: if(b != 0)                 printf("Result: %.2f", (float)a / b);              else                 printf("Error! Division by zero not possible.");         break;      default: printf("Error! Invalid choice.");         break;   }   return 0;}`

In this code:

• We first include the stdio.h library, which is used for input-output operations in C.
• We define the main() function where our code execution begins. Inside the main function, we declare three variables: a, b, and choice.
• We then ask the user to enter two integer numbers and store them in variables a and b using the scanf function.
• We provide the user with choices for different operations and store their choice in the choice variable.
• Using a switch statement, we check the user's choice. For example, if the choice is 1, we perform addition (a + b) and display the result.
• In the case of division (case 4), we check if the divisor b is not zero before performing the division to avoid a division-by-zero error.
• If the user enters a choice that is not in the provided list, the default case is executed, and an error message is printed.

## Algorithm of Calculator Program

In programming, an algorithm is a step-by-step procedure to solve a specific problem. Writing an effective algorithm is the cornerstone of successful programming.

For our calculator program in C, the algorithm can be broken down into the following steps:

1. Initialisation: Define and initialise the variables that we will use to hold the numbers for calculation (typically, these are integer or float variables), and the variable to hold the user's choice of operation.

2. Input from User: Request the user to input two numbers. Using scanf(), we read these numbers and store them in our initialised variables.

3. Display Options: We provide a menu to the user, outlining the different operations they can choose from. For a simple calculator, these are typically - 1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division.

4. Capture Choice: Using scanf(), we capture the user's choice and store it in our choice variable.

5. Perform Calculation: Based on the user's choice, we perform the corresponding mathematical operation. This is where control statements come into play. We can use either a switch or if-else statement to check the user's choice and perform the appropriate calculation. For instance, if the user's choice is 1 (Addition), we add the two input numbers.

6. Division Exception: If the operation is a division, we include an exception-handling scenario to handle division by zero, as this operation is undefined.

7. Output the Result: After the calculation, we output the result using printf(). If the user has made an invalid choice (i.e., not between the ones provided), we print an error message.

8. Repetition or Exit: Finally, for programs using a do-while loop, we ask the user if they wish to continue with another calculation or exit the program. If the user wishes to continue, we go back to step 2; otherwise, we exit the program.

By following this algorithm, we ensure that our calculator program is interactive, user-friendly, and robust.

## Different Ways to Create a Calculator Program in C

Now that we've understood the basics of creating a calculator program in C, let's explore different ways of implementing it:

### 1. Calculator Program in C using the Switch Statement

We've already seen how to use a switch statement to create a calculator program above. The switch statement is excellent when you have multiple cases to handle, and each corresponds to an operation in the calculator program.

### 2. Calculator Program in C Using if else if Statement

While the switch statement is great for multiple choices, the if-else statement provides users with more flexibility and control. Here's a calculator program in C using the if else if statement:

 `#includeint main() {   int a, b, choice;   printf("Enter two integers: ");   scanf("%d %d", &a, &b);   printf("Enter choice: 1.Addition 2.Subtraction 3.Multiplication 4.Division\n");   scanf("%d", &choice);   if(choice == 1)      printf("Result: %d", a + b);   else if(choice == 2)      printf("Result: %d", a - b);   else if(choice == 3)      printf("Result: %d", a * b);   else if(choice == 4) {      if(b != 0)         printf("Result: %.2f", (float)a / b);      else         printf("Error! Division by zero not possible.");   } else      printf("Error! Invalid choice.");   return 0;}`

This code works similarly to the calculator program in C using switch statement one, but instead of a switch statement, it uses an if-else if structure to check the user's choice and perform the corresponding operation. It gives you more flexibility and control over your code, but it can become cluttered if you have a lot of choices.

### 3. Calculator Program in C using do-while loop and Switch Statement

Here, we make our calculator program in C more interactive by running it continuously using a do-while loop until the user wishes to exit.

 `#includeint main() {   int a, b, choice;   char exit;   do {      printf("Enter two integers: ");      scanf("%d %d", &a, &b);      printf("Enter choice: 1.Addition 2.Subtraction 3.Multiplication 4.Division\n");      scanf("%d", &choice);      switch(choice) {         case 1: printf("Result: %d", a + b);            break;         case 2: printf("Result: %d", a - b);            break;         case 3: printf("Result: %d", a * b);            break;         case 4: if(b != 0)                     printf("Result: %.2f", (float)a / b);                  else                     printf("Error! Division by zero not possible.");            break;         default: printf("Error! Invalid choice.");            break;      }            printf("\nDo you want to continue? (Y/N)");      getchar();      scanf("%c", &exit);   } while(exit == 'Y' || exit == 'y');   return 0;}`

In this code, we use a do-while loop to make the calculator program more interactive. It runs continuously, performing operations as per the user's choice until the user decides to exit. After each calculation, it asks the user whether they want to continue or not. If the user inputs Y or y, it repeats the calculations; otherwise, it exits the loop and ends the program.

## Conclusion

Developing a calculator program in C is a valuable exercise in understanding control statements and user input in C. We discussed different ways of creating a calculator program in C, using switch statements, if-else statements, and loops.

As we progress from a simple calculator to a scientific one, the complexity of code increases, and so does the learning. Embrace this complexity, and you'll be well on your way to becoming a proficient C programmer.

Get hands-on with these concepts and many more with upGrad's Master of Science with Computer Science Program. Try it out today to learn C programming from industry experts and become job-ready!

## FAQs

1. Why is C used for creating calculator programs?

C is a powerful, efficient, and widely-used language that provides control structures like if, else, switch, and loops, making it suitable for calculator programs.

2. How does a calculator program work?

A calculator program works by taking input from the user, applying the mathematical operation chosen by the user on the inputs, and providing the output.

3. What is the difference between using a switch and if-else for the calculator program?

Both switch and if-else can be used for creating a calculator program. While the switch is easier and cleaner for multiple choices, if-else gives more flexibility and control over the code.

4. How to handle division by zero in the calculator program?

In our calculator program, before performing the division, we check if the divisor is zero. If it is, we print an error message instead of performing the division to avoid runtime errors.

5. Can the calculator program perform scientific calculations?

The basic calculator program we've created can perform only basic operations. However, it can be extended to perform scientific calculations like square root, power, factorial, etc. by adding more cases in the switch statement.

Director of Engineering

Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More

###### Get Free Career Counselling
+91
*
By clicking, I accept theT&Cand
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.

Talk to our experts. We’re available 24/7.

Indian Nationals

1800 210 2020

Foreign Nationals

+918045604032

## Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...