Monday, 10 December 2018

NESTED IF ELSE & SWITCH STATEMENT IN C


Nested if-else and switch statement
Choose Your Option

NESTED IF ELSE STATEMENT IN C



  • Nested if -else statement is also known as ladder if-else statement in C. 

  • Nested if-else statement is the extension of the if-else statement.

  • Nested if-else statement is decision-making statement.

  • When series of decisions are involved then we use nested if-else statements.


Syntax


if (condition-1)

{
statement-1
}

else-if (condition-2)

{
statement-2
}

else-if (condition-3)

{
statement-3
}

else

{
statement-4
}

When the true condition is achieved, the statement associated with it will execute and control will be reached at the statement-4. When all conditions are false then the default statement will be executed.

Flow Chart of Nested if-else statement in C



nested if-else statement in C
Flow Chart of the nested if-else statement in C





When condition-1 is true, then statement-1 associated with it will execute otherwise condition-2 will be checked. When condition-2 is true then statements associated with it will execute else next condition will be checked by the compiler i.e. condition and if this condition is true then the code of block will execute else default statement will execute. But when all the conditions are false then statement-4 will execute.


Switch statement in C


When we have various options (conditions) then the nested if-else statement is used. But nested if-else statement increases the complexity of a program when the number of options increases. Switch statement checks the value of an entered variable. When the value has occurred then statements associated with it will execute.


Syntax



Switch (expression)

{
case  value-1:
                  block-1
                  break;
case  value-2:
                block-2
                break;
         
______________
______________
______________
______________

default:
              default block
              break;
}

statement


  • Expression is a character or an integer. Value-1 and Value-2 are constant values.

  • These values should be unique in each case otherwise an error will occur.

  • When the switch statement will be executed, the statement associated with the value-1 and value-2 will execute.

  • The break statement is written at the end of the block of statement to exit from the block of the statement.

  • The default value is executed when all the cases occur false.



The switch statement is readable. In the switch statement, an expression is executed only one time but in the nested if-else statement, the expression is executed the number of times. The switch statement is faster than the nested if-else statement in c. Difference between nested if-else statement and switch statement in C.