In this C programming tutorial, we'll create a basic calculator that takes user input for an operator and two numbers, performs the requested operation, and displays the result.
Code: Simple Calculator in C
#include <stdio.h>
int main() {
char operator;
double num1;
double num2;
double result;
printf("\nEnter an operator (+ - * /):");
scanf("%c", &operator);
printf("\nEnter number 1:");
scanf("%lf", &num1);
printf("\nEnter number 2:");
scanf("%lf", &num2);
switch (operator) {
case '+':
result = num1 + num2;
printf("Result: %.2lf", result);
break;
case '-':
result = num1 - num2;
printf("Result: %.2lf", result);
break;
case '*':
result = num1 * num2;
printf("Result: %.2lf", result);
break;
case '/':
result = num1 / num2;
printf("Result: %.2lf", result);
break;
default:
printf("%c is not valid", operator);
}
return 0;
}
This C program allows users to input an operator (+, -, *, /) and two numbers. It then performs the requested operation and displays the result with two decimal places.
Explanation:
The code uses the switch
statement to determine the operation based on the entered operator.
The result is calculated accordingly and displayed to the user.
Conclusion
You've just created a simple calculator using C programming! This example is a great introduction to basic user input and decision-making in C. Feel free to experiment with the code and explore more advanced programming concepts.
If you have any questions or need further clarification, don't hesitate to leave a comment below.