switch Statement in C-language - C-Tutorial

Latest

Saturday, 8 October 2016

switch Statement in C-language

switch Statement:                   

switch statement is also a multi-way decision that allows for placing different block statements and execution depends on the result of the expression value.  The general format of switch statement is:


Syntax:           switch(Expression)
                        {
                                    case value1:   
                                                Block-1 code to be executed if expression equals to value1;
                                                break;
                                    case value2:   
                                                Block-2 code to be executed if expression equals to value2;
                                                break;
                                                .
                                                .
                                                .
                                    case valuen:   
                                                Block-n code to be executed if expression equals to valuen;
                                                break;
                                    default:          
                                    code/s to be executed if expression doesn't match to any cases;

                        }    next statements after switch statements



Ø  First Expression is evaluated and it produces an integer value.
Ø  Now, the expression value will be compared with case values value1, value2, ---, valuen by the compiler.  If any case value coincide with the expression value then that particular block statements are executed until break statement is encountered.
Ø  break is a branch control statement used to transfer the control out of the loop.
Ø  If the expression value doesn’t match with any case value then default block statements will be executed.  Default block is optional block.
Ø  Case values value1, value2, …. are either integer constants (or) character constants.
Ø  Case labels must be unique.  No two case labels should have the same name.
Ø  Generally switch statements are used for creating menu programs.

#include<stdio.h>
#include<conio.h>
main()
{
            int n;
            clrscr();
            printf("\n Enter a number (1 to 7):");
            scanf("%d",&n);
            switch(n)
            {
            case 1: printf(" Monday");
                        break;
            case 2: printf(" Tuesday");
                        break;
            case 3: printf(" Wednesday");
                        break;
            case 4: printf(" Thursday");
                        break;
            case 5: printf(" Friday");
                        break;
            case 6: printf(" Saturday");
                        break;
            case 7: printf(" Sunday");
                        break;
            }
getch();
}

No comments:

Post a Comment