Control Flow



  • The control-flow of a language specify the order in which computations are performed.


  • Statements and Blocks :


    1. An expression such as x = 0 or i++ or printf(...) becomes a statement when it is followed by a semicolon. In C, the semicolon is a statement terminator, rather than a separator as it is in languages like Pascal.


    2. x = 0;
         i++;
         printf(...);

    3. Braces { and } are used to group declarations and statements together into a compound statement, or block, so that they are syntactically equivalent to a single statement.


    4. There is no semicolon after the right brace that ends a block.


  • If-Else :


    1. The if-else statement is used to express decisions. Formally the syntax is 
         if (expression)
             statement1
         else
             statement2
      where the else part is optional. 

    2. The expression is evaluated; if it is true (that is, if expression has a non-zero value), statement1 else part, statement2 is executed. If it is false (expression is zero) and if there is an is executed instead.


    3. Since an if tests the numeric value of an expression, certain coding shortcuts are possible. The most obvious is writing if (expression) instead of if (expression != 0)


    4. Because the else part of an if-else is optional,there is an ambiguity when an else if omitted from a nested if sequence. This is resolved by associating the else with the closest previous else-less if.


    5. if (n > 0)
             if (a > b)
                 z = a;
             else
                 z = b;

    6. In above example, the else goes to the inner if, as we have shown by indentation. If that isn't what you want, braces must be used to force the proper association.


  • Else-If


    1.    if (expression)
             statement
         else if (expression)
             statement
         else if (expression)
             statement
         else if (expression)
             statement
         else
             statement

    2. This sequence of if statements is the most general way of writing a multi-way decision. The expressions are evaluated in order; if an expression is true, the statement associated with it is executed, and this terminates the whole chain.


    3. As always, the code for each statement is either a single statement, or a group of them in braces.


    4. The last else part handles the ``none of the above'' or default case where none of the other conditions is satisfied. Sometimes there is no explicit action for the default; in that case the trailing else can be omitted, or it may be used for error checking to catch an ``impossible'' condition.


  • Switch :


    1. The switch statement is a multi-way decision that tests whether an expression matches one of a number of constant integer values, and branches accordingly.


    2. switch (expression) {
             case const-expr: statements
             case const-expr: statements
             default: statements
         }

    3. Each case is labeled by one or more integer-valued constants or constant expressions.


    4. If a case matches the expression value, execution starts at that case. All case expressions must be different.


    5. The case labeled default is executed if none of the other cases are satisfied. A default is optional; if it isn't there and if none of the cases match, no action at all takes place. Cases and the default clause can occur in any order.




Q. Program to demonstrate nested if-else : binary search function that decides if a particular value x occurs in the sorted array v.


  • The elements of v must be in increasing order. The function returns the position (a number between 0 and n-1) if x occurs in v, and -1 if not.


  • Binary search first compares the input value x to the middle element of the array v. If x is less than the middle value, searching focuses on the lower half of the table, otherwise on the upper half. In either case, the next step is to compare x to the middle element of the selected half.


  • This process of dividing the range in two continues until the value is found or the range is empty.


  • /* binsearch:  find x in v[0] <= v[1] <= ... <= v[n-1] */
       int binsearch(int x, int v[], int n)
       {
           int low, high, mid;
           low = 0;
           high = n - 1;
           while (low <= high) {
               mid = (low+high)/2;
               if (x < v[mid])
                   high = mid + 1;
               else if (x  > v[mid])
                   low = mid + 1;
               else    /* found match */
                   return mid;
           }
           return -1;   /* no match */
       }



Q. Program to demonstrate Switch case (to count the occurrences of each digit, white space, and all other characters)


  • #include 
       main()  /* count digits, white space, others */
       {
           int c, i, nwhite, nother, ndigit[10];
           nwhite = nother = 0;
           for (i = 0; i < 10; i++)
               ndigit[i] = 0;
           while ((c = getchar()) != EOF) {
               switch (c) {
               case '0': case '1': case '2': case '3': case '4':
               case '5': case '6': case '7': case '8': case '9':
                   ndigit[c-'0']++;
                   break;
               case ' ':
               case '\n':
               case '\t':
                   nwhite++;
                   break;
               default:
                   nother++;
                   break;
               }
           }
           printf("digits =");
           for (i = 0; i < 10; i++)
               printf(" %d", ndigit[i]);
           printf(", white space = %d, other = %d\n",
               nwhite, nother);
           return 0;
       }

  • The break statement causes an immediate exit from the switch.


  • Because cases serve just as labels, after the code for one case is done, execution falls through to the next unless you take explicit action to escape. break and return are the most common ways to leave a switch.


  • A break statement can also be used to force an immediate exit from while, for, and do loops.



Loops - While and For


  • while (expression)
           statement

  • The expression is evaluated. If it is non-zero, statement is executed and expression is reevaluated. This cycle continues until expression becomes zero, at which point execution resumes after statement.


  • The for statement :


  •    for (expr1; expr2; expr3)
           statement

  • Above code is equivalent to


  •  expr1;
       while (expr2) {
           statement
           expr3;
       }

  • Grammatically, the three components of a for loop are expressions. Most commonly, expr1 and expr3 are assignments or function calls and expr2 is a relational expression. Any of the three parts can be omitted, although the semicolons must remain. If expr1 or expr3 is omitted, it is simply dropped from the expansion.


  • If the test, expr2, is not present, it is taken as permanently true.




Q. Program to demonstrate for loop - converting a string to its numeric equivalent


  • The structure of the program reflects the form of the input:


  • skip white space, if any
      get sign, if any
      get integer part and convert it 

  • #include 
       /* atoi:  convert s to integer; version 2 */
       int atoi(char s[])
       {
           int i, n, sign;
           for (i = 0; isspace(s[i]); i++)  /* skip white space */
               ;
           sign = (s[i] == '-') ? -1 : 1;
           if (s[i] == '+' || s[i] == '-')  /* skip sign */
               i++;
           for (n = 0; isdigit(s[i]); i++)
               n = 10 * n + (s[i] - '0');
           return sign * n;
       }


Q. Program to demonstrate for loop - Shell sort for sorting an array of integers


  • The basic idea of this sorting algorithm, which was invented in 1959 by D. L. Shell, is that in early stages, far-apart elements are compared, rather than adjacent ones as in simpler interchange sorts.


  • This tends to eliminate large amounts of disorder quickly, so later stages have less work to do. The interval between compared elements is gradually decreased to one, at which point the sort effectively becomes an adjacent interchange method.


  •  /* shellsort:  sort v[0]...v[n-1] into increasing order */
       void shellsort(int v[], int n)
       {
           int gap, i, j, temp;
           for (gap = n/2; gap > 0; gap /= 2)
               for (i = gap; i < n; i++)
                   for (j=i-gap; j>=0 && v[j]>v[j+gap]; j-=gap) {
                       temp = v[j];
                       v[j] = v[j+gap];
                       v[j+gap] = temp;
                   }
       }

  • There are three nested loops. The outermost controls the gap between compared elements, shrinking it from n/2 by a factor of two each pass until it becomes zero. The middle loop steps along the elements.


  • The innermost loop compares each pair of elements that is separated by gap and reverses any that are out of order. Since gap is eventually reduced to one, all elements are eventually ordered correctly.





Comma Operators (,)



  • A pair of expressions separated by a comma is evaluated left to right, and the type and value of the result are the type and value of the right operand.


  • The commas that separate function arguments, variables in declarations (int c, i, j;), etc., are not comma operators, and do not guarantee left to right evaluation


  • The most suitable uses are for constructs strongly related to each other and in macros where a multistep computation has to be a single expression


  • for (i = 0, j = strlen(s)-1; i < j; i++, j--)
               c = s[i], s[i] = s[j], s[j] = c;



Loops - Do-While



  • The while and for loops test the termination condition at the top. By contrast, the third loop in C, the do-while, tests at the bottom after making each pass through the loop body; the body is always executed at least once.


  • The syntax of the do is


  • do
           statement
           while (expression);

  • The statement is executed, then expression is evaluated. If it is true, statement is evaluated again, and so on. When the expression becomes false, the loop terminates.



Q. Program to demonstrate Do While loop - to generate the string backwards, then reverse it


  • /* itoa:  convert n to characters in s */
       void itoa(int n, char s[])
       {
           int i, sign;
           if ((sign = n) < 0)  /* record sign */
               n = -n;          /* make n positive */
           i = 0;
           do {      /* generate digits in reverse order */
               s[i++] = n % 10 + '0';  /* get next digit */
           } while ((n /= 10) > 0);    /* delete it */
           if (sign < 0)
               s[i++] = '-';
           s[i] = '\0';
           reverse(s);
       }

  • The do-while is necessary, or at least convenient, since at least one character must be installed in the array "s", even if "n" is zero.





Break and Continue



  • It is sometimes convenient to be able to exit from a loop other than by testing at the top or bottom.


  • The break statement provides an early exit from for, while, do and switch. A break causes the innermost enclosing loop or switch to be exited immediately.


  • The continue statement is related to break, but less often used; it causes the next iteration of the enclosing for, while, or do loop to begin.


  • In the while and do, this means that the test part is executed immediately; in the for, control passes to the increment step. The continue statement applies only to loops, not to switch. A continue inside a switch inside a loop causes the next loop iteration.



Q. Program to demonstrate "Break"


  • The following function, trim, removes trailing blanks, tabs and newlines from the end of a string, using a break to exit from a loop when the rightmost non-blank, non-tab, non-newline is found.


  • /* trim:  remove trailing blanks, tabs, newlines */
       int trim(char s[])
       {
           int n;
           for (n = strlen(s)-1; n >= 0; n--)
               if (s[n] != ' ' && s[n] != '\t' && s[n] != '\n')
                   break;
           s[n+1] = '\0';
           return n;
       }


Q. Program to demonstrate "Continue"


  • This fragment processes only the non-negative elements in the array "a"; negative values are skipped.


  • for (i = 0; i < n; i++)
           if (a[i] < 0)   /* skip negative elements */
               continue;
           ... /* do positive elements */




Goto and labels



  • C provides the infinitely-abusable goto statement, and labels to branch to. Formally, the goto statement is never necessary, and in practice it is almost always easy to write code without it.


  • The most common use of goto is to abandon processing in some deeply nested structure, such as breaking out of two or more loops at once. The break statement cannot be used directly since it only exits from the innermost loop.


  • A label has the same form as a variable name, and is followed by a colon. It can be attached to any statement in the same function as the goto. The scope of a label is the entire function.



Q. Program to demonstrate "goto"


  •    for ( ... )
               for ( ... ) {
                   ...
                   if (disaster)
                       goto error;
               }
           ...
       error:
           /* clean up the mess */

  • This organization is handy if the error-handling code is non-trivial, and if errors can occur in several places.