Switch case statement
The switch-case statement is a multi way decision that tests
whether an expression matches one of the number of constant expression and
branches accordingly. switch case
statements are a substitute for long if statements. The basic format for using
switch case is outlined below.
Switch (expression or variable)
{
case constant-expr1:
statement sequence;
break;
case constant-expr2:
statement sequence;
break;
case : constant-expr3:
statement sequence;
break;
...
default:
statement sequence;
}
The expression
or variable has a value. The case says that if the expression or variable has
value which is after that cases then
execute the statements that follows the
colon until the break is reached. Only one case is executed since only one
value holds for expression or variable inside switch. The break is used to break out of the case statements. Break is a
keyword that breaks out of the code block .The break prevents the
program from testing the next case statement also.
Below is a sample program, in which not all of the proper functions are actually declared, but which shows how one would use switch case in a program.
Below is a sample program, in which not all of the proper functions are actually declared, but which shows how one would use switch case in a program.
#include <stdio.h>
#include <conio.h>
void main()
{
int input;
printf("1. Play game");
printf("2. Load game");
printf("3. Play multiplayer");
printf("4. Exit");
scanf(“%d”,&input);
switch (input)
{ /*switch block starts */
case 1: printf(“Play game is choosen”); /*note use of : and ; */
break;
case 2:
printf(“Load game is choosen”);
break;
case 3:
printf(“Play multiplayer is choosen”);
break;
case 4:
exit(0);
default:
printf(“Error, bad input “);
} /* end of switch */
} /* end of main() */
Another example:
/* this program
takes input a alphabetic character and determines that either the character is
vowel or consonant and if other
character is found than letter it gives appropriate message */
#include<stdio.h>
void main()
{
char ch;
printf(“\nEnter a character:”);
scanf(“%c”,&ch);
if((ch>=’A’&&ch<=’Z’)||(ch>=’a’&&ch<=’z’))
{
printf(“This is alphabetic character.”);
switch(ch)
{
case ‘A’: case ‘a’:
case ‘E’: case ‘e’:
case ‘I’: case ‘i’:
case ‘O’: case ‘o’:
case ‘U’: case ‘u’:
printf(“\nThe letter is vowel “);
break;
default: printf(“\nThe letter is consonant.”);
} /*
end switch */
} /*end if */
else printf(“The character is not
alphabetic.”);
} /*end main() */
No comments:
Post a Comment