This blog is under construction

Saturday, 12 May 2012

Introduction to functions in C

Functions are subroutines or set of statements which are used to perform specific task. We need to define functions before calling them.  Any C program should have at least one function named main().  Because, the execution of the C program starts from the main() function.

How to declare a function?
Function declaration consists of three parts.
1. Return type
2. Function name
3. Arguments

Syntax for function declaration:
return_type function_name(arguments_list);

What is function prototype?
Function prototype is the declaration of a function that provides information about the return type, parameters and function name.

What are the various types of function prototypes?
Below are the various function prototype available in C language.
1. function with no argument and no return value
2. function with no argument and with return value
3. function with argument and return value
4. function with argument and no return value

Function definition:
Below is the standard form for any function definition.
return_type function_name (argument_list) {
       set_of_statements
}

Any function definition has function name, return type, argument and a set of statements in its function body.  Consider the following example,

int product(int a, int b) {
       return (a * b);
}

function name - product
argument      - a and b(both are integers)
return value  - integer

Here, the function product() computes the product of the arguments a and b, then returns the resultant value(product of a and b).

Calling function - How to call a function?
Let us see how to call the above defined function.  A function is called using its name with the needed arguments inside parenthesis as shown below.

function_name(arguments);

Example:
int product(int a, int b) { // called function
       return (a * b);
}

int main() {
     int res;
   res = product(10, 20);  // calling function
   return 0;
}

Here, the function product() is called from main() and we have passed two integers arguments(10 and 20).  So, the function product() computes and returns the product of 10 and 20.  The return value from product() will be assigned to the variable res.


Example C program using functions
 
  #include <stdio.h>

  int product(int a, int b) { // called function
        return (a * b);
  }

  int main() {
        int res;
        res = product(10, 20); // calling function
        printf("Product of 10 & 20 is %d\n", res);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Product of 10 & 20 is 200



No comments:

Post a Comment