Experiment 1
Experiment 1
Experiment No: 1
Title:
Program to simulate simple calculator that performs basic tasks such as
addition, subtraction, multiplication and division.
Aim:
To make a simple calculator
Objective:
To understand the usage of switch-case and decision-making constructs
in C.
To implement arithmetic operations in a C program.
To simulate a calculator that can add, subtract, multiply, and divide two
numbers.
Theory:
The switch statement in C allows multi-way branching based on the value
of an integral expression (like int or char).
It consists of multiple case labels, each representing a constant value,
with optional break statements to prevent fall-through to subsequent
cases. A default case can catch unmatched values. While switch can be
more efficient than multiple if-else statements, it is limited to integral
types and cannot perform range checks. Variables declared within a case
are scoped
Information Technology C Programming WCE
only to that case. Overall, the switch statement provides a clear way to
handle complex conditional logic.
Code:
#include <stdio.h>
int main() {
char operator;
double num1, num2, result;
if(num2 != 0) {
result = num1 / num2;
printf("%.2lf / %.2lf = %.2lf\n", num1, num2, result);
} else {
printf("Error! Division by zero.\n");
}
break;
default:
printf("Error! Invalid operator.\n");
}
return 0;
}
Snapshot of Output :
Information Technology C Programming WCE
Addition
Subtraction
Multiplication
Division
Division By Zero
Invalid Operator
Conclusion :
Information Technology C Programming WCE
The C program successfully simulates a simple calculator that performs
addition, subtraction, multiplication, and division based on user input. By using
the switch-case construct, different operations are performed efficiently. The
program also handles division by zero to avoid runtime errors.