Switch Case Statement
Description
Switch case statement is used when user has multiple alternative of codes to choose, depending upon the value of single variable.
Syntax
switch (integer expression or integer or character variable)
{
case 1:
statement;
statement;
break;
case 2:
statement;
statement;
break;
case 3:
statement;
statement;
break;
default:
statement;
}
In the above syntax after case keyword constant (1, 2, 3) is considered as integer it may be character too.
First integer expression is calculated then the value of integer or character is matched one after another with constant values of case statements. When a match is found then that case section of code is executed and if no match is found then default keyword code is executed.
- Switch variable and case constant variables should be of same data type.
- Value of switch variable should be assigned before entering the switch case.
- Each case keyword is followed by a constant and a colon.
- Every case section should end with break statement to end the switch case else it enters into the next case.
Source code
- //Using switch case statement
- #include <stdio.h>
- #include <conio.h>
- void main()
- {
- int choice;
- clrscr();
- printf("Select any option number from 1 to 4 : ");
- scanf("%d",&choice);
- switch(choice)
- {
- case 1:
- printf("You have selected first option");
- break;
- case 2:
- printf("You have selected second option");
- break;
- case 3:
- printf("You have selected third option");
- break;
- case 4:
- printf("You have selected fourth option");
- break;
- default:
- printf("Invalid option selected");
- break;
- }
- getch();
- }
Program working steps
- First line of the program is the comment, 2nd and 3rd line is about preprocessor directive included in the program.
- void main() function from where the program execution starts.
- Variable declaration int choice and clrscr() function to clear the screen.
- Program asks the user to enter any number from 0 to 4, After entering the number program stores the value to variable choice.
- Switch statement variable value(i.e. choice) is compared with constant values followed by the each case statements. When a match is found then the program executes the statements from that particular case and breaks the switch loop. And if no match is found it executes the default keyword statement and terminates the switch loop.
- Eg: If user enters 2 then the output will be 'You have selected second option'.
- getch() function to avoid flash up and exit off console screen.