C if else vs switch

 What is an if-else statement?

An if-else statement in C programming is a conditional statement that executes a different set of statements based on the condition that is true or false. The 'if' block will be executed only when the specified condition is true, and if the specified condition is false, then the else block will be executed.

Syntax

 if(expression)  
    {  
        statements;  
    }  
    else  
    {  
        statements;  
    }  

 

What is a switch statement?

A switch statement is a conditional statement used in C programming to check the value of a variable and compare it with all the cases. If the value is matched with any case, then its corresponding statements will be executed. Each case has some name or number known as the identifier. The value entered by the user will be compared with all the cases until the case is found. If the value entered by the user is not matched with any case, then the default statement will be executed.

 Syntax

    switch(expression)  
    {  
      case constant 1:  
         statements;  
      break;  
      case constant 2:  
         statements;  
      break;  
      case constant n:  
         statements;  
      break;  
     default:  
        statements;  
    }   

 

Differences b/w if-else and switch statement

 



 


 

No comments:

Post a Comment