Control Statements in C – if, else, switch

Control Statements are used to execute/transfer the control from one part of the program to another depending on a condition. These statements are also called as conditional statements.
There are two types of control or conditional statements used in the C language.

  • if-else statement
  • switch statement

    1. if-else statement : if-else statement is used to execute a statement block or a single statement depending on the value of a condition. It has the following syntax :

    if(condition)
    {
      - - - - - - - - -
     <true block>
      - - - - - - - - -
    }
    else
    {
      - - - - - - - - -
      <false block>
      - - - - - - - - -
    }  // where <condition> is a logical expression which will have the value <strong>true</strong> or <strong>false .</strong>
    

  • Nested if-else Statement :
  • An if statement may have another if statement in the < true block > and < false block >. This compound statement is called nested if statement.

    if(condition 1)
    if(condition 2)
    {
      - - - - - - - - -
     <true block 1>
      - - - - - - - - -
    }
    else
    {
      - - - - - - - - -
      <false block 1>
      - - - - - - - - -
    } 
    else
    if(condition 3)
    {
      - - - - - - - - -
     <true block 2>
      - - - - - - - - -
    }
    else
    {
      - - - - - - - - -
      <false block 2> 
      - - - - - - - - -
    } 
    

    2. switch statement : switch statement is used to execute a block of statements depending on the value of a variable or an expression. It has the following syntax :
    switch (<expression>)
    {
     case <label 1>: {
                         - - - - - - - - - -
                          <statement 1>
                         - - - - - - - - - -
                          break;
                      }
    case <label 2>:  {
                         - - - - - - - - - -
                          <statement 2>
                         - - - - - - - - - -
                          break;
                      }
    case <label 3>:  {
                         - - - - - - - - - -
                          <statement 3>
                         - - - - - - - - - -
                          break;
                      }
    case <label n>:  {
                         - - - - - - - - - -
                          <statement n>
                         - - - - - - - - - -
                          break;
                      }
    default:          {
                         - - - - - - - - - -
                          <default statement>
                         - - - - - - - - - -
                          break;
                      }
    }  // where <expression> refers any int or char expression or variable. <label 1>, <label 2>, <label 3>, <label n> are the values which will match with the value of the expression.
    break is a statement which will transfer the control to the end of switch statement.