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:
-
Declare variables to store the two numbers & the result.
-
Display a menu of operations for the user to choose from (addition, subtraction, multiplication, division).
-
Use the scanf() function to read the user's choice & the two numbers.
-
Based on the user's choice, perform the corresponding mathematical operation using a switch statement.
-
Display the result of the calculation.
-
Ask the user if they want to perform another calculation.
-
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 :
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.