Header Ads

Switch case in C


SWITCH CASE



Control statement that allow us to make a decision from the number of choices is called a switch, or more correctly a switch-case-default, since these three keywords go together to make up the control statement. They most often appear as follows:


Switch ( integer expression )
{
case constant 1 :
do this ;
case constant 2 :
do this ;
case constant 3 :
do this ;
default :
do this ;
}

The integer expression following the keyword Switch is any C expression that will yield an integer value. It could be an integer constant like 1, 2 or 3, or an expression the evaluates to an integers. The keyword case is followed by an integer, character, or float constant. Each constant in each case must be different from all the others. The “do this” lines in the above form of switch represent any valid C statement.
Consider the following program:
#include<stdio.h>
#include<conio.h>
main()
{
                int i=2;
                switch (i)
                {
                                case 1:
                                                printf("I am in case 1\n");
                                                break;
                                case 2:
                                                printf("I am in case 2\n");
                                                break;
                                case 3:
                                                printf("I am in case 3\n");
                                                break;
                                default :
                                                printf("I am in default\n");
                }
                getch();
}
Output of this program would be:-

I am in case 2_     

No comments