Name :- Pavan Kalaskar
Roll No :- 2026
#include <stdio.h>
Int main() {
// Variables to store the numbers and the result
Float num1, num2, result;
Char opt;
// Prompt the user to enter two numbers
Printf(“Enter two numbers: \n“);
Scanf(“%f %f”, &num1, &num2);
// Ask the user to choose an operation
Printf(“Choose an operation (+, -, *, /): “);
Scanf(“ %c”, &opt); // The space before %c is necessary to ignore any
leftover newline characters
// Perform the operation based on user input and display the result
Switch (opt) {
Case ‘+’:
Result = num1 + num2;
Printf(“Result: %.2f\n”, result);
Break;
Case ‘-‘:
Result = num1 – num2;
Printf(“Result: %.2f\n”, result);
Break;
Case ‘*’:
Result = num1 * num2;
Printf(“Result: %.2f\n”, result);
Break;
Case ‘/’:
If (num2 != 0) { // Check for division by zero
Result = num1 / num2;
Printf(“Result: %.2f\n”, result);
} else {
Printf(“Error: Division by zero is not allowed.\n”);
Break;
Default:
Printf(“Error: Invalid operator.\n”);
}
Output :-
Code Explanation:-
This C program functions as a simple calculator. It begins by declaring
variables to store two numbers (`num1` and `num2`) and the result of an
operation. The user is prompted to input two numbers, then asked to choose
an arithmetic operator (`+`, `-`, `*`, `/`). The program uses a `switch`
statement to determine the operation to perform based on the user’s choice.
For division, it checks if the divisor (`num2`) is zero to prevent division by
zero errors. The result is displayed with two decimal places. If the user
inputs an invalid operator, an error message is shown.