Page 56 - Programming Microcontrollers in C
P. 56

Program Flow and Control       41

                          s[i++] = ‘0’ + n % 10;
                          n /=10;
                       } while ( n != 0);
                       s[i]=0; /* make the array a string */


                       /* but it is backwards in the array — reverse
                   t*/

                       i—–; /* don’t swap the NULL */
                       while( i > j)
                       {
                          temp = s[j];
                          s[j++] = s[i];
                          s[i--] = temp;
                       }
                   }
                              The function uses three integer variables. The variables i and j
                          are both initialized to zero, and the variable temp does not need to
                          be initialized. The first portion of the program contains a do-while
                          loop. Within this loop, the number is converted into a string. The
                          statement
                   s[i++] = ‘0’ + n % 10;

                          first calculates the value of the integer modulo 10. This value is the
                          number of 1s in the number. Adding that value to the character ‘0’
                          will create the character that corresponds to the number of 1s. This
                          value is stored in the location s[i] with i=0 and then i is
                          incremented.
                              The second statement in the loop replaces n with n divided by
                          10. This code removes any 1s that were in the number originally,
                          and now the original 10s are in the 1s position. Since this division is
                          an integer division, if the result is between 0 and 1 it will be rounded
                          to 0. Therefore, the test in the while argument allows the above two
                          statements to repeat until the original number n is exhausted by re­
                          peated divisions by 10.
                              When the do-while loop is completed, s[i] will be the charac­
                          ter immediately following the string of characters. A string is created
                          by placing a 0 or a null in this location of the array.
   51   52   53   54   55   56   57   58   59   60   61