This is part four of the notes for the C programming course provided
online in the BCPPDOS forum of CompuServe, during January 1995.  The first
part is called NOTEC1.TXT, please read the message in NOTEC1.TXT as to the
use of these notes.

(c)  Terry Hawkes 1995




                           C++ Programming Beginners

                                   Chapter 4


Control Structures

Every programming language has some form of mechanism to allow a block of code
to be repeated a number of times.  C is no exception and provides three different
loop control structures.  These are the 'for' loop, which causes one or more
statements to be executed for a fixed number of incremental steps.  The 'while'
loop is executed while a controlling condition is true and continues with the
following statements once the condition is false.  The 'do while' loop, the C
equivalent of the repeat loop, and is similar to the 'while' loop.  The main
difference being that the 'while' loop tests the control condition at the start
of the loop, whereas the 'do while' loop tests the condition after the last
statement in the loop code.


The For Loop


The for loop steps through a series of values, performing the specified action
once for each value.

The format of the for statement is:


      for( <expression 1>; <expression 2>; <expression 3> )

      /* (starting values), ( condition ),  (  changes  )*/

      {
        statement or group of statements;
      }



e.g.  
      for (i=0; i<10; i++)
            printf("The value of i is: %d\n", i);

where       'i=0;' is the starting statement
            'i<10;'is the controlling condition
            'i++' is the change statement


The starting and change statements are optional, if a "part" is omitted the ';'
must still be used. If any part is omitted, then the control variable must be
given a value before the loop statement and the change must take place within the
loop body.


EXAMPLE PROGRAM: for1.c

      /* for1.c */
      /* A program to show the use of the for statement */

      #include <stdio.h>

      void main (void)
      {     /* main */
        int count;

            printf("Table of squares\n\n");

            for (count =1; count <=10; count++)
              printf("Number: %d square : %d\n", count, count * count);
                  /* only this one line is included in the loop body */

            return 0;
      }     /* end main */

Type in, compile and run for1.c.  Place the variable 'count' in the watch window
(Ctrl & F7 to add a watch).  Then single step (F8 key) through the program and
watch the value in 'count' change each time the loop is executed, what value of
'count' ends the loop.  Remember the control condition is, 'count less than or
equal to ten', so a value greater than ten is required to end the loop.


Load and run the example program intro17.c

This example prints the ascii characters from decimal 32, for all values less
than 256, using a for loop.  In the for loop control the starting condition is
32, the loop continues for all values less than 256, and ascii_val is incremented
each time the loop is repeated.

In the loop printf statement each character is separated by a Tab ("\t"), if the
ascii value is divided by 9 a new line is started, "if(ascii_val %9 == 0)".

This program is useful to find the ascii values of all the printable characters
on your system.  If you would like to see the number for each character, modify
the program to print the integer value of ascii_val each time it prints a
character.




There are many variations of the for loop.  The body of the loop can have only
one statement, in which case the braces are optional but recommended for clarity.

ie.
      for(; count <= 10;)

where the starting value for count is set prior to the for loop statement, and
the modifier for count will be in the loop body.

A for loop can have no body at all, with all the work being done in the change
part of the control statement. The initialisation and termination sections in a
for loop can comprise of more than one C statement.

e.g.


for (number=1, total=0.0; number < 11; total += number, number++);
   /*starting condition*/ /*control*/  /*modifying statements*/


Thus multiple statements separated by a comma can be put into any of the
expressions. For example load and run intro18.c

intro18.c

This example gives the total value of counting all the numbers from 1 to 10. 
Notice that the starting values for both 'number' and 'total' are set at the
beginning of the loop.  The loop continues for all values of 'number' less than
11.  The modifying statement "total += number" adds number to total, then
'number' is incremented by one with the increment operator '++'.

The printf statement is after the closing semicolon (;), so the printf statement
is outside of the loop and is only executed once the for loop has finished. 
Single step the program, watching the value of 'number' for each step.The While Loop


The while loop executes one or more statements as long as a specified condition
is true.  The syntax is:


  while (condition)
      statement or group of statements;



The while loop tests the condition first, therefore a while loop may never run
at all if the condition fails the first time.
e.g.


      while (c!=10)  /*while c does not equal 10*/
        {
          c=getchar();
          printf("%c",c);
        }


if c=10 no statement will be executed.

If c equals 10 then the loop is not executed and the program continues with the
next statement following the loop.


EXAMPLE PROGRAM: while1.c


/* Copy the input stream to the output stream char by char */

      #include <stdio.h>

      void main(void)
            {         /* main */
              int c;   /* declare c as an int to check for EOF */
              while((c=getch()) !=EOF) /*read ch, store in c and test*/
                  putchar(c);
            }         /* end main */



In this example 'getch' reads a character from the keyboard and assigns it to the
variable c.  Then the value in c is tested for inequality (not equal to) to EOF.
EOF is a 'C' constant which indicates if the end of a file has been reached, the
value may vary on different systems.

See example program INTRO15.c


Intro15.c

This example takes the input of a series of numbers, outputs the total and
average values.  The first 'gets' reads the first value entered as a string,
'sscanf' formats this value in to an integer and stores it in the variable
'number'.  If the first value is not a zero the loop is entered.  The statement
"total += number" adds the value in number to the value in total.

The next value is read from the keyboard and formatted by sscanf as an integer. 
If it equals zero, the printf statement is executed, else 'count' is incremented
and the loop is executed again.  If zero had been entered the program would
continue with the statements following the loop body and the 'total' and
'average' would be output.

Single step the program to watch how the statements are executed, especially when
zero is entered.  Remember you still have to type in the values when the 'gets'
statement is executed.The do while loop


The do while loop is very similar to the while loop.  It takes the form


      do statement or group of statements
      while (condition true)



There is one important difference between the two types of while loop.  The do
while loop is always performed at least once, even if the test turns out to be
false, as the test of the condition is at the end of the loop body.


A good use of the do while loop is processing a menu, as in the following
example:


/* INTRO16.C */

      #include <conio.h>
      #include <ctype.h>
      #include <stdio.h>

      int main(void)
      {           /* main */
         char cmd;

         do {
            printf("Chart desired: Pie  Bar  Scatter  Line  Three-D  Exit");
            printf("\nPress first letter of the chart you want: ");
            cmd = toupper(getch());
            printf("\n");

            switch (cmd)
            {
               case 'P': printf("Doing pie chart\n"); break;
               case 'B': printf("Doing bar chart\n"); break;
               case 'S': printf("Doing scatter chart\n"); break;
               case 'L': printf("Doing line chart\n"); break;
               case 'T': printf("Doing 3-D chart\n"); break;
               case 'E': break;
               default : printf("Invalid choice. Try again\n");
            }
         } while (cmd != 'E');

         return 0;
      }           /* main */The active part of the program, including the statements that display the menu
and get a character as well as the switch statement, have been enclosed in a do
while loop.  The menu case, E, allows the user to exit the program.  This case
has just a break with it, if any other character is typed, the while condition
causes the menu to be re-displayed.  But if E (or e via the function toupper) is
typed, the condition  cmd != 'E' is false, and control drops out of the bottom
of the loop.  The program then terminates. 

Place the variable 'cmd' in the watch window and single step the program and
watch which statements are executed.  Try running the program without the break
statements, remember how they are used from chapter 3.

Break and Continue


Sometimes it is necessary to leave a loop before you test the controlling
condition again.  The break statement can be used to exit a while, do while, or
for loop immediately, without performing the rest of the statements enclosed in
the loop.  e.g.

Suppose you don't want to launch a space rocket if any warning lights are on:


/* INTRO20.C */

      #include <stdio.h>

      #define WARNING -1

      int main(void)
      {
         int count = 10;
         while (count-- > 1)
         {
            if (get_status() == WARNING)
               break;
            printf("%d\n", count);
         }
         if (count == 0)
            printf("Shuttle launched\n");
         else
         {
            printf("Warning received\n");
            printf("Count down held at t - %d", count);
         }

         return 0;
      }
      int get_status(void)
      {
         return WARNING;
      }A while loop runs the countdown, each time checking the function get_status to
see if it returns a value of -1, which has been defined as WARNING.  If
get_status returns -1, the break stops the countdown.

To make the program a little more interactive, use a scanf statement to input a
value for the function 'get_status' to return.  Input a 1 to let the countdown
continue, -1 to stop the countdown.


The continue statement like break, causes all remaining statements in the loop
to be skipped.  But while break completely exits the loop, continue simply skips
the loop's test condition.  e.g.


/* INTRO21.C */
/* Displays even numbers up through 10 */

#include <stdio.h>

      int main(void)
      {
         int num = 0;
         while (num++ <= 10)
         {
            if (num % 2 != 0)
               continue;      /*step over printf if not divide by 2*/
            printf("%d\n", num);
         }

         return 0;
      }

Single step this program and see which values in 'num' cause the step over.  If
the number is odd, the continue statement causes the printf statement to be
skipped.


(c) Terry Hawkes 1995