Switch statement allows us to execute one statement from many statement and that statements are called case. Actually in switch statement, inside the body of switch a number of cases are used and a parameter are passed and from which case this parameter is matched, executed
👉Syntax
👉Example 1
#include<stdio.h> int main() { //Assigning parameter's value int p=2; switch(p) { case 1: printf("it is case 1"); break; case 2: printf("it is case 2"); break; case 3: printf("it is case 3"); break; default: printf("no case matched"); } return 0; } ### output ### it is case 2 //because p=2 so case 2 will execute
👉Example 2
#include<stdio.h> int main() { //Assigning parameter's value int p=5; switch(p) { case 1: printf("it is case 1"); break; case 2: printf("it is case 2"); break; case 3: printf("it is case 3"); break; default: printf("no case matched"); } return 0; } /* ### output ### no case matched because value of p is 5 and it will not match with any case so default case will execute */
👉Example 3
#include<stdio.h> int main() { //Assigning parameter's value int p=5; switch(p) { case 1: printf("Hello"); break; case 2: printf("Hi"); break; case 3: printf("Tata"); break; case 2+1: printf("Bye"); break; default: printf("no case matched"); } return 0; } /* ### output ### Error */
👉Example 4
#include<stdio.h> int main() { //Assigning parameter's value int p=2; switch(p) { case 1: printf("Hello"); break; case 2: printf("Hi"); case 3: printf("Tata"); break; case 4: printf("Bye"); break; default: printf("no case matched"); } return 0; } /* ### output ### HiTata */
👉Example 5
#include<stdio.h> int main() { //Assigning parameter's value int p=3; switch(p) { default: printf("no case matched"); case 1: printf("Hello"); break; case 2: printf("Hi"); break; case 3: printf("Tata"); break; case 4: printf("Bye"); break; } return 0; } /* ### output ### Tata */
👉Program: Check given Alphabet is Vowel or Consonant
#include<stdio.h> int main() { //variable declaration char ch; printf("Enter any alphabet\n"); scanf("%c",&ch); switch(ch) { case 'A': case 'E': case 'I': case 'O': case 'U': case 'a': case 'e': case 'i': case 'o': case 'u': printf("Vowel"); break; default: printf("Consonant"); } return 0; } /* ### output ### Enter any alphabet M Consonant */
Request:-If you found this post helpful then let me know by your comment and share it with your friend.
If you want to ask a question or want to suggest then type your question or suggestion in comment box so that we could do something new for you all.
If you have not subscribed my website then please subscribe my website.
Try to learn something new and teach something new to other.
Thanks.
0 Comments