Skip to main content

examples of Switch Statement in C

// Following is a simple C program 
// to demonstrate syntax of switch. 


/* Syntax:

switch (n)
{
    case 1: // code to be executed if n = 1;
        break;
    case 2: // code to be executed if n = 2;
        break;
    default: // code to be executed if n doesn't match any cases
}
*/
#include <stdio.h> 
int main() 
int x ;
printf("enter the number\n");
scanf("%d",&x);
switch (x
   case 1printf("Choice is 1"); 
         break
   case 2printf("Choice is 2"); 
            break
   case 3printf("Choice is 3"); 
         break
   defaultprintf("Choice other than 1, 2 and 3"); 
            break
return 0
/* 
Rules for switch case statement:-
1.The expression provided in the switch should result in a
 constant value otherwise it would not be valid.
2.Duplicate case values are not allowed.
3.The default statement is optional.Even if the switch
 case statement do not have a default statement,
4.it would run without any problem.
5.The break statement is used inside the switch to terminate 
a statement sequence. When a break statement is reached,
 the switch terminates, and the flow of control jumps to the
  next line following the switch statement.
6.The break statement is optional. If omitted, execution will
 continue on into the next case.
 The flow of control will fall through to subsequent cases 
 until a break is reached.
7.Nesting of switch statements are allowed, which means you 
can have switch statements inside another switch.
 However nested switch statements should be avoided as 
 it makes program more complex and less readable.
 */

Comments

Popular posts from this blog

example of typecasting in c

/*Type Casting in C Typecasting allows us to convert one data type into other. */ //simple example to cast int value into the float. #include <stdio.h>    int   main (){   float   f = ( float ) 9 / 4 ;     printf ( "f : %f \n " ,  f  );     return   0 ;   }