Featured Post

Friday, October 14, 2016

switch statement in C



 A switch statement is a multi way decision point. In if else statement there are only two choices(either condition is true or false). When there two or more choices  then we have to use switch statement.

Syntax:
     
                             switch(expression)
                             {
                                   case constant1:
                                    statement(s); /* code to be executed */
                                    break;
                                   case constant2:
                                    statement(s);
                                    break;
                                    .
                                    .
                                    .
                                    .
                                    .
                                    .
                                     default:
                                      /* default code to be executed /
                               }

Every switch statement followed by number of case statements(possible expression values). Every case statement contains a block of statements to be executed. If expression value matches any case constant then corresponding block statements will be executed. If the expression value does not match any case constant then default block will be executed.

/* C program to demonstrate the use of switch statement */

main()

{
   int ch,a,b,c;
   printf("\n 1. Addition  \n 2. Subtraction   \n 3. Multiplication    \n 4. Division ");
   printf("\n enter your choice");
   scanf("%d",&ch);
    printf("\n enter any two numbers");
    scanf("%d%d",&a,&b);
    switch(ch)
    {
            case 1:
                           printf("\n addition of %d and %d is %d",a,b,a+b);
                           break;
             
            case 2:
                         printf("\n subtraction of %d and %d is %d",a,b,a-b);
                           break;
            case 3:
                       printf("\n multiplication of %d and %d is                                                     %d",a,b,a*b);
                           break;
            case 4:
                           printf("\n division of %d and %d is %d",a,b,a/b);
                           break;
             default:
                          printf("\n enter the correct choice");
    }
}

OUTPUT:
       1. Addition
       2. Subtraction
       3. Multiplication
       4. Division
   enter your choice 1
   enter any two numbers
   12    6
   addition of 12 and 6 is 18

                             LOOPS in C

C programming, switch statement, difference between if else and switch statement, conditional statements, iterative statements. default statements, goto statements, break statement, cotinue







No comments:

Post a Comment