Last Updated: Jun 9, 2024
Difficulty: Easy

# C Program to Make a Simple Calculator

Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

## Introduction

A calculator is a basic tool that helps us perform mathematical operations quickly & easily. A simple calculator can perform basic arithmetic operations such as addition, subtraction, multiplication, and division.

In this article, we will learn how to create a simple calculator program in C that can add, subtract, multiply & divide two numbers. Apart from that we will also learn the step by step approach with time and space complexity.

## Approach: Simple Calculator Program Using Switch Statement

To create a simple calculator program in C, we will follow these steps:

1. Declare variables to store the two numbers & the result.

2. Display a menu of operations for the user to choose from (addition, subtraction, multiplication, division).

3. Use the scanf() function to read the user's choice & the two numbers.

4. Based on the user's choice, perform the corresponding mathematical operation using a switch statement.

5. Display the result of the calculation.

6. Ask the user if they want to perform another calculation.

7. Repeat steps 2-6 until the user chooses to exit the program.

Now we will look at a complete code for this calculator program in C :

• C

### C

``#include <stdio.h>int main() {    float number1, number2;    char operation;        // Prompting user for input    printf("Enter two numbers: ");    scanf("%f %f", &number1, &number2);    printf("Enter an operation (+, -, *, /): ");    scanf(" %c", &operation);  // Notice the space before %c to capture the previous newline character.    // Processing the operation using a switch statement    switch(operation) {        case '+':            printf("%.2f + %.2f = %.2f\n", number1, number2, number1 + number2);            break;        case '-':            printf("%.2f - %.2f = %.2f\n", number1, number2, number1 - number2);            break;        case '*':            printf("%.2f * %.2f = %.2f\n", number1, number2, number1 * number2);            break;        case '/':            if(number2 != 0.0) {                printf("%.2f / %.2f = %.2f\n", number1, number2, number1 / number2);            } else {                printf("Division by zero is not allowed.\n");            }            break;        default:            printf("Invalid operation.\n");    }    return 0;}``

Output

``````Enter two numbers: 5 6
Enter an operation (+, -, *, /): +
5.00 + 6.00 = 11.00``````

### Explanation

• Library Inclusion: We start by including the stdio.h library, which is necessary for input and output operations.

• Main Function: The main function is the entry point of any C program.

• Variable Declaration: We declare two floating-point variables number1 and number2 for the operands, and a character variable operation for the operator.

• Input: The program prompts the user to enter two numbers and an operation. It uses scanf to read the input. The space before %c in the scanf function is crucial as it consumes any whitespace characters, including the newline left in the input buffer by previous inputs.

• Switch Statement: The operations are processed using a switch statement. Each case checks for the operation entered (+, -, *, /) and performs the corresponding arithmetic operation, printing the result. The default case handles any invalid operations entered by the user.

• Handling Division by Zero: There is a specific check in the division case to ensure there is no division by zero, which would otherwise cause a runtime error.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

## Time and Space Complexity Analysis

### Time Complexity

The time complexity of this calculator program is O(1), which means it is constant time complexity. This is because no matter the input size or the numbers entered by the user, the program performs a fixed number of operations determined by the switch statement. Each case in the switch executes in constant time since they involve only basic arithmetic operations.

### Space Complexity

The space complexity of the program is also O(1), or constant space complexity. The program uses a fixed amount of space regardless of the input size:

• Two float variables (number1 and number2) for the numbers.

• One char variable (operation) for storing the operation symbol.

These variables occupy a constant amount of memory, and no additional space is required as the input size changes.

### Can I add more operations to this calculator?

Yes, you can extend the functionality of this calculator by adding more cases to the switch statement. For example, you could include modulus %, exponentiation, or even functions to calculate the square root.

### Why does the program ask for the operation after the numbers?

The sequence ensures that both numbers are ready when the operation is determined, allowing immediate calculation. However, you can modify the order if it suits your application better.

### What happens if I enter an invalid operation?

The program handles invalid operations through the default case in the switch statement, which prints "Invalid operation." It ensures the program does not crash and provides user feedback for correction.

## Conclusion

In this article, we have learned how to create a simple calculator in C using a switch statement. We talked about the basics of user input, variable declaration, and implementing conditional logic with switch statements to perform arithmetic operations. We also discussed the time and space complexity of the program. This program serves as a foundation for beginners to learn the fundamental programming concepts which would be helpful for them to increase their problem solving skill for more complex programming concepts.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.

Topics covered
1.
Introduction
2.
Approach: Simple Calculator Program Using Switch Statement
2.1.
C
2.2.
Explanation
3.
Time and Space Complexity Analysis
3.1.
Time Complexity
3.2.
Space Complexity
4.