Discuss switch case statement in C language programming language by taking a suitable example
The switch statement allows us to execute one code block among many alternatives.
You can do the same thing with the if...else..if ladder. However, the syntax of the switch statement is much easier to read and write.
Syntax of switch...case
switch (expression)
{
case constant1:
// statements
break;
case constant2:
// statements
break;
.
.
.
default:
// default statements
}
Example:
#include <stdio.h>
int main() {
char operation;
double n1, n2;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operation);
printf("Enter operand 1: ");
scanf("%lf",&n1);
printf("Enter operand 2: ");
scanf("%lf",&n2);
switch(operation)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",n1, n2, n1+n2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",n1, n2, n1-n2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",n1, n2, n1*n2);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",n1, n2, n1/n2);
break;
default:
printf("Error! operator is not correct");
}
scanf("%lf",&n2);
return 0;
}
Comments
Leave a comment