- switch case in c programming questions
- switch case with do you want to continue in c
- A switch case is a control statement in C that allows you to choose between several different options based on the value of a particular expression.
- C has a built-in multi-way decision statement known as a switch. It is a keyword we can select a single option from multiple options. The switch is having expression; each and every option is known as case and must be followed by colon.
- Each and every case ends with break statement.
- The last case is default even that will have break.
- The break is a keyword. Each and every case ends with break statement
SYNTAX:-
switch(expression)
{
case value-1 :block-1 break;
case value-2 :block-2 break;
case value-3 :block-3 break;
.........
.........
.........
.........
default :default-block break;
}
Here is an example of how to use a switch case in a C program:
- # include <stdio.h>
- void main() {
- char operator;
- double a,b;
- printf("Enter an operator (+, -, *,): ");
- scanf("%c", &operator);
- printf("Enter two numbers ");
- scanf("%lf %lf",&a, &b);
- switch(operator)
- {
- case '+':
- printf("%.1lf + %.1lf = %.1lf",a, b, a + b);
- break;
- case '-':
- printf("%.1lf - %.1lf = %.1lf",a, b, a - b);
- break;
- case '*':
- printf("%.1lf * %.1lf = %.1lf",a, b, a * b);
- break;
- case '/':
- printf("%.1lf / %.1lf = %.1lf",a, b, a / b);
- break;
- default:
- printf("Error! operator is not correct");
- }
- }
Output:
- Enter an operator (+, -, *,): +
- Enter two numbers 12
- 12
- 12.0 + 12.0 = 24.0
- Process returned 18 (0x12) execution time : 7.392 s
- Press any key to continue.
- In the below example, the program prompts the user to enter a number and then uses a switch case to determine what to do based on the value of the number. If the user enters 1, the program will print "You entered 1.
- " If the user enters 2, the program will print "You entered 2," and so on. If the user enters a value that is not covered by any of the cases, the default case will be executed.
No comments