A Switch case statement is a multi way decision statement, that is a simplified version of if-else block,switch statement are mostly used in two situation-:
1- When there is only one variable to evaluate in the expression.
2- When many condition are being tested for when there are many condition to test, using the "if " and " if-else " construct becomes a bit complicated and confusing,therefore switch case statement are often used as alternative to long if statement.
ads
The switch case expression is either an integer or character type.If the value of switch expression matches any of the constant case,the relevant code is executed and control moves out of the switch case statement.If the expression does not matches any of the constant case,then the default statement is executed.
In switch statement case and default are keyword or reserved words. Every case statement terminates with colon(;).The break statementis used to exit from current case structure.
- The cases in switch statement mean not to be arrange in ascending or descending order.we can put the case in any order we want.
- It is possible to execute a common statement for multiple cases.
Syntax-:
switch(integer/character)
{case value1: statement;
-
-
-
break;
case value 2: statement;
-
-
-
break;
-
-
-
case value n: statement ;
-
-
-
break;
default: statement;
}
Example-:
#include<stdio.h>
#include<conio.h>
main()
{char ch;
printf("Enter any character");
scanf("%c",&ch);
switch(ch)
{ case 'A':
case 'a': printf(" \n %c is a vowel",ch);
break;
case 'E':
case 'e': printf("\n %c is a vowel",ch);
break;
case 'I':
case 'i': printf("\n %c is a vowel",ch);
break;
case 'O':
case 'o': printf("\n %c is a vowel",ch);
break;
case'U':
case'u': printf("\n %c is a vowel",ch);
break;
default: printf("\n %c is not a vowel",ch);
break;
}
getch();
}
output-:Enter any character O
O is a vowel
subscribe tech programiz to learn C language
ReplyDelete