each parameter before you define the function. For example, a prototype for the sum function would be:

int sum(int,int);

meaning sum is an int function which takes two int parameters. Obviously, if you are in the habit of declaring functions then this is a small modification. The only other major change is that you can declare parameter types along with the function as in:

 

int sum(int a, int b);

{

rather than:

 

int sum(a,b)

int a,b;

{

was used in the original K&R C. Again, you can see that this is just a small change. Notice that even if you are using an ANSI compiler you don't have to use prototypes and the K&R version of the code will work perfectly well.


The Standard Library Functions

Some of the "commands" in C are not really "commands" at all but are functions. For example, we have been using printf and scanf to do input and output, and we have used rand to generate random numbers - all three are functions.

There are a great many standard functions that are included with C compilers and while these are not really part of the language, in the sense that you can re-write them if you really want to, most C programmers think of them as fixtures and fittings. Later in the course we will look into the mysteries of how C gains access to these standard functions and how we can extend the range of the standard library. But for now a list of the most common libraries and a brief description of the most useful functions they contain follows:

  • stdio.h: I/O functions:
    • getchar() returns the next character typed on the keyboard.
    • putchar() outputs a single character to the screen.
    • printf() as previously described
    • scanf() as previously described
  • string.h: String functions
    • strcat() concatenates a copy of str2 to str1
    • strcmp() compares two strings
    • strcpy() copys contents of str2 to str1
  • ctype.h: Character functions
    • isdigit() returns non-0 if arg is digit 0 to 9
    • isalpha() returns non-0 if arg is a letter of the alphabet
    • isalnum() returns non-0 if arg is a letter or digit
    • islower() returns non-0 if arg is lowercase letter
    • isupper() returns non-0 if arg is uppercase letter
  • math.h: Mathematics functions
    • acos() returns arc cosine of arg
    • asin() returns arc sine of arg
    • atan() returns arc tangent of arg
    • cos() returns cosine of arg
    • exp() returns natural logarithim e
    • fabs() returns absolute value of num
    • sqrt() returns square root of num
  • time.h: Time and Date functions
    • time() returns current calender time of system
    • difftime() returns difference in secs between two times
    • clock() returns number of system clock cycles since program execution
  • stdlib.h:Miscellaneous functions
    • malloc() provides dynamic memory allocation, covered in future sections
    • rand() as already described previously
    • srand() used to set the starting point for rand()

Throwing The Dice

As an example of how to use functions, we conclude this section with a program that, while it isn't state of the art, does show that there are things you can already do with C. It also has to be said that some parts of the program can be written more neatly with just a little more C - but that's for later. All the program does is to generate a random number in the range 1 to 6 and displays a dice face with the appropriate pattern.

The main program isn't difficult to write because we are going to adopt the traditional programmer's trick of assuming that any function needed already exists. This approach is called stepwise refinement, and although its value as a programming method isn't clear cut, it still isn't a bad way of organising things:

 

main()

 {

   int r;

   char ans;

 

   ans = getans();

 

   while(ans== 'y')

    {

      r = randn(6);

      blines(25);

      if (r==1) showone();

      if (r==2) showtwo();

      if (r==3) showthree();

      if (r==4) showfour();

      if (r==5) showfive();

      if (r==6) showsix();

      blines(21);

      ans = getans();

    }

 

   blines(2);

 }

 

If you look at main() you might be a bit mystified at first. It is clear that the list of if statements pick out one of the functions showone, showtwo etc. and so these must do the actual printing of the dot patterns - but what is blines, what is getans and why are we using randn()? The last time we used a random number generator it was called rand()!

The simple answers are that blines(n) will print n blank lines, getans() asks the user a question and waits for the single letter answer, and randn(n) is a new random number generator function that produces a random integer in the range 1 to n - but to know this you would have written the main program. We decided what functions would make our task easier and named them. The next step is to write the code to fill in the details of each of the functions. There is nothing to stop me assuming that other functions that would make my job easier already exist. This is the main principle of stepwise refinement - never write any code if you can possibly invent another function! Let's start with randn().

This is obviously an int function and it can make use of the existing rand() function in the standard library

 

int randn(int n)

 {

   return rand()%n + 1;

 }

 

The single line of the body of the function just returns the remainder of the random number after dividing by n - % is the remainder operator - plus 1. An alternative would be to use a temporary variable to store the result and then return this value. You can also use functions within the body of other functions.

Next getans()

 

char getans()

 {

   int ans;

 

   printf("Throw y/n ?");

   ans = -1;

   while (ans == -1)

    {

      ans=getchar();

    }

   return ans;

}

 

This uses the standard int function getchar() which reads the next character from the keyboard and returns its ASCII code or -1 if there isn't a key pressed. This function tends to vary in its behaviour according to the implementation you are using. Often it needs a carriage return pressed before it will return anything - so if you are using a different compiler and the program just hangs, try pressing "y" followed the by Enter or Return key.

The blines(n) function simply has to use a for loop to print the specified number of lines:

 

void blines(int n)

  {

    int i;

 

    for(i=1 ; i<=n ; i++) printf("\n");

  }

 

Last but not least are the functions to print the dot patterns. These are just boring uses of printf to show different patterns. Each function prints exactly three lines