C Program To Make Simple Calculatorc Program That Gets Two Strings From Input And Stores Them In Variables Such As Str1 And Str2
This article guides you through creating a simple calculator program in C. You will learn how to accept user input for two numbers and an arithmetic operator, then perform the corresponding calculation and display the result.
Problem Statement
Many everyday tasks require basic arithmetic operations, such as addition, subtraction, multiplication, and division. Building a simple command-line calculator addresses the need for a quick, accessible tool to perform these calculations without requiring a graphical interface.
Example
The calculator will prompt the user for two numbers and an operator. For instance, if a user enters 10, +, and 5, the output will be 15.0.
Background & Knowledge Prerequisites
To understand and implement this C program, you should have a basic understanding of:
- C data types:
intfor integers,floatordoublefor decimal numbers. - Input/Output functions:
printf()for displaying output andscanf()for reading input. - Arithmetic operators:
+,-,*,/. - Conditional statements:
if-elseorswitchstatements for decision-making.
Use Cases or Case Studies
A simple calculator program can be incredibly useful in various scenarios:
- Learning C Programming: It serves as an excellent beginner project to practice fundamental C concepts like I/O, variables, and control flow.
- Quick Command-Line Calculations: Developers or users working in a terminal environment can quickly perform calculations without switching applications.
- Embedding in Larger Systems: The core logic can be a component within a larger application that requires basic computational capabilities.
- Educational Tools: Teachers can use it to demonstrate basic programming principles or mathematics.
- Basic Scripting: For simple batch scripts or automated tasks where quick calculations are needed.
Solution Approaches
We will implement a straightforward approach using a switch statement to handle different arithmetic operations.
Simple Calculator using switch statement
This approach takes two numbers and an operator from the user, then uses a switch statement to execute the appropriate arithmetic operation.
// Simple C Calculator
#include <stdio.h>
int main() {
// Step 1: Declare variables to store numbers, operator, and result
char operator_char;
double num1, num2, result;
// Step 2: Prompt user for the first number
printf("Enter first number: ");
scanf("%lf", &num1);
// Step 3: Prompt user for the operator
printf("Enter an operator (+, -, *, /): ");
scanf(" %c", &operator_char); // Note the space before %c to consume newline
// Step 4: Prompt user for the second number
printf("Enter second number: ");
scanf("%lf", &num2);
// Step 5: Use a switch statement to perform the calculation based on the operator
switch (operator_char) {
case '+':
result = num1 + num2;
printf("Result: %.2lf + %.2lf = %.2lf\\n", num1, num2, result);
break;
case '-':
result = num1 - num2;
printf("Result: %.2lf - %.2lf = %.2lf\\n", num1, num2, result);
break;
case '*':
result = num1 * num2;
printf("Result: %.2lf * %.2lf = %.2lf\\n", num1, num2, result);
break;
case '/':
// Handle division by zero
if (num2 == 0) {
printf("Error: Division by zero is not allowed.\\n");
} else {
result = num1 / num2;
printf("Result: %.2lf / %.2lf = %.2lf\\n", num1, num2, result);
}
break;
default:
printf("Error: Invalid operator entered.\\n");
break;
}
return 0;
}
Sample Output
Enter first number: 10
Enter an operator (+, -, *, /): *
Enter second number: 4
Result: 10.00 * 4.00 = 40.00
Enter first number: 7
Enter an operator (+, -, *, /): /
Enter second number: 0
Error: Division by zero is not allowed.
Stepwise Explanation
- Variable Declaration: We declare
operator_charof typecharto store the arithmetic operator, andnum1,num2,resultof typedoubleto handle floating-point numbers for more precise calculations. - Input for First Number: The program prompts the user to enter the first number using
printf()and reads it intonum1usingscanf("%lf", &num1). The%lfformat specifier is used for readingdoublevalues. - Input for Operator: The user is then asked to enter an operator.
scanf(" %c", &operator_char)reads the character. The space before%cis crucial; it tellsscanfto consume any leftover whitespace characters (like the newline character from the previousscanf) before reading the actual character. - Input for Second Number: Similarly, the second number is prompted and read into
num2. - Conditional Calculation (Switch):
- A
switchstatement evaluates theoperator_char. - For each
case(+,-,*,/), the corresponding arithmetic operation is performed, and the result is stored in theresultvariable. - The
printf()function displays the calculation and its result, formatted to two decimal places (.2lf). - Division by Zero Handling: Specifically for the division case (
/), anifstatement checks ifnum2is zero. If it is, an error message is printed to prevent a runtime error. Otherwise, the division proceeds. - The
breakstatement exits theswitchblock after a matching case is found. - The
defaultcase catches any invalid operator input, printing an error message.
- Return 0: The
mainfunction returns0to indicate successful execution.
Conclusion
Creating a simple calculator in C demonstrates fundamental programming concepts, including user input/output, variable handling, arithmetic operations, and conditional logic. This basic structure can be expanded upon for more complex calculations or features.
Summary
- A C program can implement a basic calculator by taking two numbers and an operator as input.
- The
scanf()andprintf()functions are essential for handling user input and displaying results. - The
switchstatement provides a clean way to manage different arithmetic operations based on the user's operator choice. - Error handling, such as preventing division by zero, is crucial for robust programs.
- This project is excellent for practicing core C programming skills and understanding control flow.