Switch case in C
1.What is switch case in C ?
Ans: Switch case statement evaluates a given expression and based on the evaluated value(matching a certain condition), it executes the statements associated with it. Basically, it is used to perform different actions based on different conditions(cases).
Simple Explanation :
In this image we can see that there is a main switch which have control on electrical supply in home. We have some button in our electrical board which are connected to different electrical devices. If we switch on particular device like fan then only fan gets on.
In switch case the expression written in the bracket is the main switch here. If we enter the case number or an alphabet it enter that case.
Rules of the switch case statement :
Following are some of the rules that we need to follow while using the switch statement:
- In a switch statement, the “case value” must be of “char” and “int” type.
- There can be one or N number of cases.
- The values in the case must be unique.
- Each statement of the case can have a break statement.
- The default Statement is also optional.
Working of Switch case loop :
switch(expression)
{
case value1: statement_1;
break;
case value2: statement_2;
break;
.
.
.
case value_n: statement_n;
break;
default: default_statement;
}
Example:
1. Write a program to find number of days in a particular month.
#include <stdio.h>
int main()
{
int month;
/* Input month number from user */
printf("Enter month number(1-12): ");
scanf("%d", &month);
switch(month)
{
case 1:
printf("31 days");
break;
case 2:
printf("28/29 days");
break;
case 3:
printf("31 days");
break;
case 4:
printf("30 days");
break;
case 5:
printf("31 days");
break;
case 6:
printf("30 days");
break;
case 7:
printf("31 days");
break;
case 8:
printf("31 days");
break;
case 9:
printf("30 days");
break;
case 10:
printf("31 days");
break;
case 11:
printf("30 days");
break;
case 12:
printf("31 days");
break;
default:
printf("Invalid input! Please enter month number between 1-12");
}
}
Output :
2. C program to create calculator using switch case and functions.
#include <stdio.h>
int main()
{
char op;
float num1, num2, result=0.0f;
/* Print welcome message */
printf("WELCOME TO SIMPLE CALCULATOR\n");
printf("----------------------------\n");
printf("Enter [number 1] [+ - * /] [number 2]\n");
/* Input two number and operator from user */
scanf("%f %c %f", &num1, &op, &num2);
/* Switch the value and perform action based on operator*/
switch(op)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
printf("Invalid operator");
}
/* Prints the result */
printf("%.2f %c %.2f = %.2f", num1, op, num2, result);
}
0 Comments