Switch Case Example in C
On this page (8sections)
About this program
This is an example program in simple example programs. Read the concept first: Hello World - Simple C Program, then study the code and output below.
Definition
In C programming language, the switch statement is a type of selection mechanism used to allow block code among many alternatives.Simply, It changes the control flow of program execution via multiple blocks.
Switch Statement Rules
- A switch works with the char and int data types.
- It also works with enum types
- Switch expression/variable datatype and case datatype are should be matched.
- A switch block has many numbers of case statements, Each case ends with a colon.
- Each case ends with a break statement. Else all case blocks will execute until a break statement is reached.
- The switch exists When a break statement is reached,
- A switch block has only one number of default case statements, It should end of the switch.
- The default case block executed when none of the cases is true.
- No break is needed in the default case.
Switch Statement Usage
- We can use switch statements alternative for an if..else ladder.
- The switch statement is often faster than nested if…else Ladder.
- Switch statement syntax is well structured and easy to understand.
Syntax:
switch ( <expression> or <variable> ) {
case value1:
//Block 1 Code Here
break;
case value2:
//Block 1 Code Here
break;
...
default:
Code to execute for not match case
break;
}
Example Program For Switch
/* Example Program For Switch Case In C Programming Language
little drops @ thiyagaraaj.com
Coded By:THIYAGARAAJ MP */
// Header Files
#include<stdio.h>
#include<conio.h>
//Main Function
int main()
{
// Variable Declaration
char ch;
//Get Input Value
printf("Enter the Vowel (In Capital Letter):");
scanf("%c",&ch);
//Switch Case Check
switch( ch )
{
case 'A' : printf( "Your Character Is A\n" );
break;
case 'E' : printf( "Your Character Is E\n" );
break;
case 'I' : printf( "Your Character Is I\n" );
break;
case 'O' : printf( "Your Character Is O\n" );
break;
case 'U' : printf( "Your Character Is U\n" );
break;
default : printf( "Your Character is Not Vowel.Otherwise Not a Capital Letter\n" );
break;
}
// Wait For Output Screen
getch();
//Main Function return Statement
return 0;
}
Sample Output:
Enter the Vowel (In Capital Letter):A
Your Character Is A
Enter the Vowel (In Capital Letter):O
Your Character Is O
Enter the Vowel (In Capital Letter):h
Your Character is Not Vowel.Or Not a Capital Letter
Related Pages
Learn the concept first, then study the code:
- C Programs — Browse all C Programs.
- Hello World - Simple C Program — Tutorial — your first C program explained line by line.
- Hello World C Language Example Program — More in simple example programs.
- If Statement Example Program In C Programming Language — More in simple example programs.