Explain switch case with proper example in c
In C programming language, switch case is a control statement that allows you to select one of several alternatives based on the value of a given expression.
Here is an example of using switch case in C:
Code :-
#include <stdio.h>
int main() {
int num;
printf("Enter a number between 1 and 3: ");
scanf("%d", &num);
switch(num) {
case 1:
printf("You entered one.\n");
break;
case 2:
printf("You entered two.\n");
break;
case 3:
printf("You entered three.\n");
break;
default:
printf("Invalid input!\n");
}
return 0;
}
In the above example, the user is prompted to enter a number between 1 and 3. The input is then read using the scanf() function and stored in the num variable. The switch statement then checks the value of num and executes the code block associated with the matching case.
If num is equal to 1, the code block associated with case 1 is executed, which prints "You entered one." to the console. Similarly, if num is equal to 2 or 3, the code blocks associated with case 2 or case 3 are executed respectively.
If num does not match any of the cases, the code block associated with the default case is executed, which prints "Invalid input!" to the console.
Note that each case block is terminated with a break statement. This is important as it tells the switch statement to exit after executing the matching code block. If a break statement is not used, the code execution will "fall through" to the next case and continue executing until it reaches a break statement.
Write a c program to make calculator using switch case
Here's a C program that uses switch case to make a basic calculator:
code
#include <stdio.h>
int main() {
char operator;
double num1, num2;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
switch(operator) {
case '+':
printf("%.2lf + %.2lf = %.2lf", num1, num2, num1 + num2);
break;
case '-':
printf("%.2lf - %.2lf = %.2lf", num1, num2, num1 - num2);
break;
case '*':
printf("%.2lf * %.2lf = %.2lf", num1, num2, num1 * num2);
break;
case '/':
if(num2 == 0) {
printf("Error: division by zero!");
} else {
printf("%.2lf / %.2lf = %.2lf", num1, num2, num1 / num2);
}
break;
default:
printf("Error: invalid operator!");
}
return 0;
}
Output:-
In this program, the user is prompted to enter an operator (+, -, *, or /) and two numbers. The program then uses switch case to perform the appropriate arithmetic operation on the two numbers based on the operator entered.
If the operator entered is invalid or division by zero is attempted, an error message is displayed. Otherwise, the program prints the result of the operation to the console.
Thanks for visit my post🙏
0 Comments