Course Content
Detailed Content of Programming in C
0/1
Introduction
0/1
Structure of C program
0/1
Answers of ‘C’ Pointers Programs
0/1
About Lesson

Develop a calculator program that takes two numbers and an operator (+, -, *, /) as input. Use a switch statement to perform the corresponding operation.

#include <stdio.h>

int main() {
double num1, num2, result;
char operator;

// Taking input for the first number
printf(“Enter the first number: “);
scanf(“%lf”, &num1);

// Taking input for the operator
printf(“Enter the operator (+, -, *, /): “);
scanf(” %c”, &operator); // Note the space before %c to consume any newline character left in the input buffer.

// Taking input for the second number
printf(“Enter the second number: “);
scanf(“%lf”, &num2);

// Using a switch statement to perform the corresponding operation
switch (operator) {
case ‘+’:
result = num1 + num2;
printf(“Result: %.2lfn”, result);
break;
case ‘-‘:
result = num1 – num2;
printf(“Result: %.2lfn”, result);
break;
case ‘*’:
result = num1 * num2;
printf(“Result: %.2lfn”, result);
break;
case ‘/’:
if (num2 != 0) {
result = num1 / num2;
printf(“Result: %.2lfn”, result);
} else {
printf(“Error: Division by zero is not allowed.n”);
}
break;
default:
printf(“Invalid operator. Please enter +, -, *, or /.n”);
}

return 0;
}