Go Back

Switch Case in C Programming: A Leaning path

3/15/2023
All Articles

#switch case #cLanguage #c_program #coding

Switch Case in C Programming: A Leaning path

Switch Case in C Programming: A Leaning path

A switch statement enables the comparison of a variable's value to a list of possible values. Each value is called a case, and the variable being switched on is checked for each switch case.

Syntax of code :

switch(expression ){    
case value1:    
 //executed code;    
 break;   
case value2:    
 //executed code;    
 break;  
default:     
 //default block if no condition is match
 }
 

Point to be remaimber in Switch 

  • The break statement in is optional. 
  • If there is no break statement found in the case, After the matched case, all other cases will be executed.
  • In C Language switch can use  expression an integer or character type.
  • In C Language  ,case value used only inside the switch statement
 

Below Example of switch in C :

#include<stdio.h>  
int main(){    
int n=0;    
printf("enter a number for matching:");     
scanf("%d",&n);    
switch(n){          
case 1:    
printf("number is: 1");    
break;    
case 2:    
printf("number is  2");    
break;    
case 3:    
printf("number is  3");    
break;  
default: 
 printf("number is not in  1, 2 or 3");    
}    
return 0;  
}

Article