Page 66 - Programming Microcontrollers in C
P. 66

Functions      51

                          actly this operation for us. When a C program encounters a break,
                          it jumps to the end of the current block. Therefore, the breaks
                          following the executable statements above will cause the program to
                          jump out of the executing sequence and return to get the next charac­
                          ter from the input stream.
                              When all options have been exhausted without a match, the state­
                          ments following the default line will be executed. It is not necessary
                          to have a default line.

                          EXERCISES
                          1. Write a program that counts the number of lines, words, and char­
                            acters in an input stream.

                          2. Extend the program from the exercise above to calculate the per­
                            centage usage of each character in the alphabet.

                          3. A prime number is a number that cannot be evenly divided by any
                            number. For example, the numbers 1, 2, and 3 are all prime num­
                            bers. Write a program that will calculate and print out the first 200
                            prime numbers.

                            Write this program without the use of either a modulo or a divide
                            operation.


            Functions
                              The function is the heart of a C program. In fact, any C program
                          is merely a function named main. The purpose of a function is to
                          provide a mechanism to allow a single entry of a code sequence that
                          is to be repeated many times. A function is the most reusable element
                          in the C language. Properly written and debugged functions can be
                          collected into a program when needed. Therefore, the use of func­
                          tions will allow the programmer to write smaller programs and it is
                          not necessary to rewrite common functions that are used often.
                              A function can have many arguments or none whatsoever. Func­
                          tion arguments are contained in parentheses following the function
                          name. The values of the arguments are the parameters needed to
                          execute the function. A function can return a value, or perhaps it will
                          not have a return value. An example of a function that returns a value
                          is getchar() which returns a character from the input stream.
   61   62   63   64   65   66   67   68   69   70   71