C Online Compiler
Example: Simple Calculator in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Simple Calculator #include <stdio.h> int main() { char operator_char; double num1, num2, result; // Step 1: Prompt user for the operator printf("Enter an operator (+, -, *, /): "); scanf(" %c", &operator_char); // Note the space before %c to consume newline // Step 2: Prompt user for two operands printf("Enter two operands: "); scanf("%lf %lf", &num1, &num2); // Step 3: Use if-else if-else to perform calculation based on operator if (operator_char == '+') { result = num1 + num2; printf("Result: %.1lf %c %.1lf = %.1lf\n", num1, operator_char, num2, result); } else if (operator_char == '-') { result = num1 - num2; printf("Result: %.1lf %c %.1lf = %.1lf\n", num1, operator_char, num2, result); } else if (operator_char == '*') { result = num1 * num2; printf("Result: %.1lf %c %.1lf = %.1lf\n", num1, operator_char, num2, result); } else if (operator_char == '/') { // Handle division by zero if (num2 != 0) { result = num1 / num2; printf("Result: %.1lf %c %.1lf = %.1lf\n", num1, operator_char, num2, result); } else { printf("Error! Division by zero is not allowed.\n"); } } else { printf("Error! Invalid operator entered.\n"); } return 0; }
Output
Clear
ADVERTISEMENTS