Reviewing Functions

First, what is a function? A function is a self-contained unit of program code designed to accomplish a particular task. A function in C plays the same role that functions, subroutines, and procedures play in other languages, although the details might differ. Some functions cause an action to take place. For example, printf() causes data to be printed on your screen. Some functions find a value for a program to use. For instance, strlen() tells a program how long a certain string is. In general, a function can both produce actions and provide values.
 
Why should you use functions? For one, they save you from repetitious programming. If you have to do a certain task several times in a program, you only need to write an appropriate function once. The program can then use that function wherever needed, or you can use the same function in different programs, just as you have used putchar() in many programs. Also, even if you do a task just once in just one program, using a function is worthwhile because it makes a program more modular, hence easier to read and easier to change or fix. Suppose, for example, that you want to write a program that does the following:

  1. Read in a list of numbers
  2. Sort the numbers
  3. Find their average
  4. Print a bar graph

Lets consider and simple example of function which calculates square of a number

Example

#include<stdio.h>
int main( ) 
{ 
    int num;
    printf("Enter number ");
    scanf("%d",&num);
    printf("%d",square(num)); // calling function
    getchar();
    return 0;

}
int square(int number)
{
    // returning a value from function to the calling block
    return number*number; 
}

Here, main( ) itself is a function and through it we are calling the function square(any number). What do we mean when we say that main( ) ‘calls’ the function square(number)? We mean that the control passes to the function square( ). The activity of main( ) is temporarily suspended; it falls asleep while the square( ) function wakes up and goes to work. When the square( ) function runs out of statements to execute, the control returns to main( ), which comes to life again and begins executing its code at the exact point where it left off. Thus, main( ) becomes the ‘calling’ function, whereas square( ) becomes the ‘called’ function.