Page 53 - Programming Microcontrollers in C
P. 53

38     Chapter 1  Introduction to C

                       guess = (i + (10000/i))/2;
                   }
                          This calculation is known as a Newton loop. It states that if i is a
                          guess at the square root of 10000, then (i+(10000/i))/2 is a
                          better guess. The loop will continue to execute until  i is exactly
                          equal to guess. At this time the compound statement will be skipped.
                              When the statement following the while is skipped, program
                          control is passed to the statement

                   printf(“The square root of 10000 is %d\n”,guess);
                          This statement prints out the value of the last guess, which will be
                          the square root of 10000.

            The For Loop

                              Many times, a sequence of code like

                   statement1;
                   while(statement2)
                   {
                       .
                       .
                       .
                       statement3;
                   }

                          will be found. This exact sequence was seen in the above example.
                          There is a shorthand version of this sequence that can be used. It is as
                          follows:

                   for(statement1;statement2;statement3)
                          The for construct takes three arguments, each separated by semi­
                          colons. In operation, the for construct is compiled exactly the same
                          as the above sequence. In other words, statement1 is executed
                          followed by a standard while with statement2 as its argument.
                          The compound statement that follows will have statement3 placed
                          at its end, so that statement3 is executed just prior to completion
                          of the statement following the while construct. The for construct
                          can be used to write the above program in the following manner:

                   #include <stdio.h>
   48   49   50   51   52   53   54   55   56   57   58