Course Content
Programming in C
About Lesson

Functions divide large computing tasks into smaller ones, enabling people to build on each other’s work. Appropriate functions hide details of the operation, making programming simpler, efficient and less error-prone.
Each function definition has the form

return-type function-name (argument declarations)
{
  declarations and statements
}

A program is a set of definitions of variables and functions. Communication between functions is by arguments and values returned by the functions, and through external variables. The functions can occur in any order in the source file and the source program can be split into multiple files, as long as no function is split.

The return statement is used to return a value from the function to its caller. Any expression can follow return:

return expression;

The expression will be converted to the return type of the function, if needed. The calling function is free to ignore the returned value.

Let’s look at the following code, which calculates permutation, ^nP_r = \dfrac{n!}{(n-r)!}

#include <stdio.h>

int permute(int, int);
int factorial(int);

int main()
{
  printf("%dP%d = %dn", 4, 2, permute(4, 2));
  printf("%dP%d = %dn", 3, 2, permute(3, 2));
  printf("%dP%d = %dn", 3, 1, permute(3, 1));
  return 0;
}

int permute(int n, int r)
{
  return factorial(n) / factorial(n - r); 
}

int factorial(int n)
{
  int res = 1;
  for (; n > 0; n--)
    res *= n;
  return res;
}

Separating the code to calculate permutation and factorial into different functions makes the code readable, debuggable, reusable and maintainable.
We could also put these into separate files. For example, main function could go to main.c, permute to permute.c and factorial to factorial.c. Note that you need to include

int factorial(int);

in permite.c.
We could compile the three files using:

cc main.c permute.c factorial.c

This places the resulting object codes in main.o, permute.o and factorial.o, then loads them all into an executable file called a.out. We could change the name of the executable file to anything we want by using -o option at compile time and passing the name we want, as shown below:

cc main.c permute.c factorial.c -o output

We could then run the code using:

./output
Scroll to Top