Control Statements in C

  • Control statements in C themselves are statements, when they are executed, a control structure controls the execution of other statements: e.g., deciding whether or not to execute some statement; deciding which one of a pair of statements to execute; re-executing a statement, etc.
  • Many control structures make their decisions by evaluating boolean expressions.
  • Control structures include various formats of if statements, switch statements, and the Loop control statements include for, while, and do-while statements.
  • These Control statements determine the “flow of control” in a program and enable us to specify the order in which the various instructions in a program are to be executed by the computer.
  • Normally, high-level procedural programming languages require/use the following basic type of control statements: –
    1. Sequence Control instructions/statements
    2. Selection/Decision/Conditional Control instructions/statements
    3. Repetition or Looping Control instructions/statements
    4. switch case Statement
    5. goto Statement
    6. break Statement
    7. continue Statement
    8. exit Statement

(A) Sequence Statements

  • Sequence instruction means executing one instruction after another, in the order in which they occur in the source file.
  • This is usually built into the language as a default action, as it is with C. If an instruction is not a control statement, then the next instruction to be executed will simply be the next one in sequence.

(B) Selection/Decision/Conditional Statements

  • Selection means executing different sections of code depending on a specific condition or the value of a variable.
  • This allows a program to take different courses of action depending on different conditions.
  • In a C program, a decision causes a one-time jump to a different part of the program, depending on the value of an expression.
  • Decisions in C can be made in several ways. The most important is with the if…else statement, which chooses between two alternatives.
  • It is used to execute an instruction or sequence/block of instructions only if a condition is fulfilled/satisfied.
  • In if statements, the expression is evaluated first, and then, depending on whether the value of the expression (relation or condition) is “true” or “false”, it transfers the control to a particular statement or a group of statements.
  • C provides three basic selection structures.
    1. if statement
    2. if…else statement
    3. Nested if…else statement
    4. else – if statement 
    5. switch case statement
(a) if statement : –
    • It is used to execute an instruction or block of instructions only if a condition is fulfilled.
    • Syntax =
if (condition)
    Single line statement/code;
OR 
if (condition)
{
    Multiple line/Block of statements/codes;
}
(here condition is the expression that is to be evaluated. If the given condition is true, the statement is executed. If it is false, the statement is ignored (not executed) and the program continues on the next instruction after the conditional statement area.)
    (b) if-else statement : –
    • If…else statement is used when a different sequence of instructions is to be executed depending on the logical value (True / False) of the condition evaluated.
    • Syntax = 
    if (condition)
          Single line Statement1/Code1;
    else
          Single line Statement2/Code2 ;
    Statement3/Code3;

    Or

    if (condition)
       {
        Multiple Lines/Block of Statement1/Code1;
        }
    else
        {
          Multiple Lines/ Block of Statement2/Code2;
        }

     Statement3/Code3;

    (Here, if the condition is true, then the sequence of statements (Statements1 Block) executes; otherwise, the Statements2 Block of codes get executed. In both cases, the control is then transferred to Statements3 to follow the sequential execution of the program.)

    (c) Nested if-else statement : –
    • In a nested if… else statement, an entire if…else construct is written within either the body of the if statement or the body of an else statement.
    • Syntax =

    if (condition1)
       {
           if (condition2)
             {
                Statements1 Block;
              }
           else
             {
                Statements2 Block;
              }
         }
    else
        {
           Statements3 Block;
        }
    Statement4 Block;

    (Here, condition 1 is evaluated. If it is false then Statements3 Block is executed and is followed by the execution of Statements4 Block, otherwise if condition1 is true, then condition2 is evaluated. Statements1 Block is executed when the condition2 is true otherwise Statements2 Block is executed and then the control is transferred to Statements4 Block.)

    (d) else-if statement: –
    • To show a multi-way decision based on several conditions, we use the else if statement.
    • This works by cascading several comparisons. As soon as one of the conditions is true, the statement or block of statements following them is executed and no further comparisons are performed.
    • Syntax =
    if (condition1)
      {
         Statements1 Block;
      }
    else if (condition2)
      {
        Statements2 Block;
      }
    – – –
    – – –
    – – –
    else if (condition n)
       {
          Statementsn Block;
       }
    else
         Statements x;
    (Here, the conditions are evaluated in order from top to bottom. As soon as any condition evaluates to true, then the statement associated with the given condition is executed and control is transferred to Statement x skipping the rest of the conditions following it. But if all conditions evaluate false, then the statement following final else is executed followed by the execution of Statements x.)

      (C) Repetition or Looping Statements

      • Repetition/Looping means executing the same section of code more than once until the condition is fulfilled/satisfied.
      • Loop control statements are used when a section of code may either be executed a fixed number of times or while some condition is true.
      • C provides three looping statements:
        1. for loop statement.
        2. while loop statement.
        3. do…while loop statement.
      (i) for loop statement :-
      • The for loop is frequently used, usually where the loop will be traversed a fixed number of times.
      • for statement makes it more convenient to count iterations of a loop and works well where the number of iterations of the loop is known before the loop is entered.
      • This loop is specially designed to perform a repetitive action with a counter.
      • Syntax =

      for (initialization; test condition; increment or decrement)
      {
          Single/Multi line/Statement(s)/Code(s);
      }

      ( Here, first step initialization is executed first, and generally, it is an initial value setting for a counter variable. This is executed only once. In the second step test condition, the given condition is checked, if it is true then the loop continues, otherwise the loop finishes, and the statement is skipped out from the statement boundary. In the third step Statement(s) is/are executed when the condition is satisfied. As usual, it can be either a single line of statement/instruction or a block of statements/instructions enclosed within curly brackets { }. Finally, in the fourth step whatever is specified in the increment or decrement of the control variable field is executed and the loop gets back to the second step for further condition verification.)

      • The three statements inside the braces of a for loop are usually meant for one activity each, however, any of them can be left blank also as per need. More than one control variable can be initialized but must be separated by a comma.
      • Various forms of for-loop statements can be: –
             (a) for(- – – ;condition;increment/decrement)
                               body of code(s);
                    A blank first statement will mean no initialization occurred in the loop.
             (b) for (initialization;condition; – – – )
                               body of code(s);
                    A blank last statement will mean no running increment/decrement.
             (c) for (initialization; – – – ;increment/decrement)
                               body of code(s);
                    A blank second conditional statement means no test condition to control the exit from the loop. So, in the absence of a second statement, it is required to test the condition inside the loop otherwise it results in an infinite loop where the control never exits from the loop.
              (d) for (- – – ; – – – ;increment/decrement)
                              body of code(s);
                    Initialization is required to be done before the loop and the test condition is checked inside the loop.
              (e) for (initialization; – – – ; – – -)
                             body of code(s);
                    Test condition and control variable increment/decrement are to be done inside the body of the loop.
              (f) for (- – – ; condition; – – -)
                             body of code(s);
                     Initialization is required to be done before the loop and control variable increment/decrement is to be done inside the body of the loop.
              (g) for (; – – – ; – – – 😉
                             body of code(s);
                    Initialization is required to be done before the loop, test condition and control variable increment/decrement is to be done inside the body of the loop.

                            NB : Similar cases can be seen for a while and do while loop.

      (ii) while/entry control loop statement :-
      • The while loop keeps repeating an action until an associated condition returns false. This is useful when the programmer does not know in advance how many times the loop will be traversed.
      • When in a program, a single statement or a certain group of statements are to be executed repeatedly depending upon certain test conditions, then a while statement is used.
      • Syntax =
      – – –
      initialization;
      – – –
      while (test condition)
         {
             //source codes
      – – –
            increment or decrement;
         }

      (Here, the test condition is an expression that controls how long the loop keeps running. The body of the loop is a statement or group of statements enclosed in braces and is repeatedly executed till the value of the test condition evaluates to true. As soon as the condition evaluates to false, the control jumps to the first statement following the while statement. If the condition initially itself is false, the body of the loop will never be executed. While loop is sometimes called an entry-control loop, as it controls the execution of the body of the loop depending upon the value of the test condition.)

      • Here, the condition in the while loop is evaluated and the body of the loop is repeated until the condition evaluates to false.
      • In a while loop, the statement doesn’t execute the body of the loop even once, if the condition is false.
      (iii) do-while/exit control loop statement :-
      • The do-while loop is similar, but the condition is checked after the loop body is executed. This ensures that the loop body is run at least once.
      • It is very similar to the while statement, called the do… while statement. The only difference is that the expression that determines whether to carry on looping is evaluated at the end of each loop.
      • Syntax =
      – – –
      initialization;
      – – –
      do
         {
             //source codes
      – – –
             increment or decrement;
         } while (test condition);
      • In the do-while loop, the body of the loop is executed at least once before the condition is evaluated. Then the loop repeats the body as long as the condition is true. That is why the do-while loop is also called an exit-control loop.
      Nested loop
      • C allows any three of the loops to be nested, that is, one loop may be inside another.
      Infinite loop
      • A loop running continuously for an indefinite number of times is called an infinite loop.

            Infinite for Loop : –

                for(- – –  ; – – – ; – – – )
                  {  
                       //source code 
                  }  

            Infinite While Loop : –

                 while(1)
                    {  
                           //source code 
                    }  

            Infinite Do-While Loop:

                do
                   {  
                       //source code 
                    } while(1);  

      (D) switch case Statement : –

      • A switch case statement is a decision-making/conditional statement in ‘C’.
      • A switch case statement is usually the combination of a switch, case, break & default keywords.
      • A switch case statement is used in a program where multiple decisions are present.
      • They are very similar to the if-else statement but there is a problem with the if-else statement i.e. its complexity which increases as the number of logical statements increases. This complexity makes the program difficult to read and comprehend. Sometimes it may also confuse the developer who himself wrote the program. Hence, it is suggested to use a switch case statement in place of an if-else statement i.e. it is an alternative statement of a nested if-else statement.
      • The switch variable/expression and case label must be an integer(not float) or single character(not string) constant.
      • Each ‘case’ keyword of the switch statement should include a ‘break’ keyword for proper functioning and must end with a symbol.
      • The case keyword containing a label must be a constant(single character and numeric value but not String) and unique.
      • The break statement in the switch case statement is optional but should be used in each case statement except default i.e. if there is no break statement then all the cases will be executed after the matched case. It is called a fall through the state of switch statement.
      • The ‘default’ keyword is optional and is normally used at the last of the program. There can be only one default label in the program.
      • A switch case statement can also be nested as per need like if- else statement.
      • Once the switch is executed, the control will go to each case statement for matching, and if matched that case will executed, and if not matched default statement is finally executed.
      • Syntax =

      switch (expression/switch variable)

      {
         case expression 1:
               block of statements 1;
               break;
         case expression 2:
              block of statements 2;
              break;
             .
             .
         default:
             default block of statements; 
      }

      • (Here, expression can be an integer value or expression or single character expression, but not String. An expression may contain switch(3+6), switch(m+n), switch(m>n && m+n>0), switch(m>n), switch(m+n-2), switch(func(m,n)) etc where m and n are integer. 
      • Here, the switch evaluates the expression and checks if it is equivalent to expression 1. If it is, it executes a block of statement1 until it finds the break keyword, the moment it finds the control will go to the end of the switch. If the expression is not equal to expression 1 it will check whether an expression is equivalent to expression 2. If it is, it will execute a block of statement 2 until it finds the break keyword.
        Finally, if the value of the expression has not matched any of the previously specified constants (we may specify as many case statements as values we want to check), the program will execute the instructions included in the default: section, if it exists, as it is an optional statement.)

      (E) goto Statement : –

      • The goto statement is used to alter the normal sequence of program instructions by transferring the control to some other required portion of the program.
      • Syntax =
      – – –
      goto label;
      – – –
      – – –
      label : statement;

      OR

      – – –
      label : statement;
      – – –
      – – –
      goto label;
      (Here, the label is an identifier that is used to uniquely label the statement to which control will be transferred. The targeted statement must be preceded by the unique label followed by a colon.)
      • Although the goto statement is used to alter the normal sequence of program execution its usage in the program should be avoided.
      • The most common applications of goto are: –
        i). To branch around statements under certain conditions in place of the use of if-else statements,
        ii). To jump to the end of the loop under certain conditions bypassing the rest of the statements inside the loop in place of the continue statement,
        iii). To jump out of the loop avoiding the use of a break statement.
      • goto can never be used to jump into the loop from outside and it should be preferably used for forward jump.

      (F) break Statement : –

      • Sometimes, it is required to jump out of a loop irrespective of the conditional test value. A break statement is used inside any loop to allow the control to jump to the immediate statement following the loop.
      • Syntax =
      – – –
      break;
      – – –
      • When nested loops are used, then the break jumps the control from the loop where it has been used.
      • Break statement can be used inside any loop i.e., while, do-while, for, and also in switch statement.
      • It jumps the control out of the loop when the statement is encountered.

      (G) continue Statement : –

      • Unlike a break statement, which is used to jump the control out of the loop, it is sometimes required to skip some part of the loop and to continue the execution with the next loop iteration.
      • The continue statement used inside the loop helps to bypass the section of a loop and passes the control to the beginning of the loop to continue the execution with the next loop iteration.
      • Syntax =
      – – –
      continue;
      – – –

      (H) exit Statement : –

      • Exit statement stops the execution of the entire program forcibly when encountered statement.
      • Syntax =
      – – –
      exit;
      – – –

      Loading

      Categories: C

      0 Comments

      Leave a Reply

      Your email address will not be published. Required fields are marked *

      This site uses Akismet to reduce spam. Learn how your comment data is processed.