Subscribe Twitter

Sunday, November 14, 2010

Functions Part -I

DEFINITION 

A function is a self-contained program segment that carries out some specific, well-defined task. Every C program consists of one or more functions. One of these functions must be called 'main ( )'. Execution of program will always begin by carrying out the instructions in 'main ( )'. Additional functions will be subordinate to 'main ( )', and perhaps to one another. If a program contains multiple functions, their definition may appear in any order, though they must be independent of one another. That is, one function cannot be embedded within another. A function will carry out its intended action whenever it is called or accessed from some other portion of the program. Once the function has carried out its intended action, control will be returned to the point from which the function was accessed. Generally, a function1 will process information that is passed to it from the calling portion of the program and returns a single value. Information is passed to the function via special identifiers called 'arguments' and also called 'parameters' and returned via the return statement.

TYPES OF FUNCTIONS

Functions are broadly classified into two types :
  1. Library functions (built-in functions)
  2. User defined functions

  • Library Functions
There are several mathematical functions that are used quite frequently, such as square root, logarithms, exponentials etc. These functions are written and predefined in the compiler and are grouped in special library files. Rather than each user writing these subprograms, C compiler provides these built-in library functions as a convinience. Arguments to certain library functions are limited by the definition of the function. For example, the square root of a negative number is mathematically undefined and therefore not permitted. Before using any of the built-in library functions the programmer have to include the header file in his program, in which that particular function is defined. For example, library functions for manipulating strings are defined in string. h such as strcpy ( ), strcmp ( ), strlen ( ), strrev ( ), etc. Library functions for manipulating performing DOS services are defined in DOS.h.
  • User Defined Functions
These are those functions which are defined by user itself. These functions are not predefined in any library file. These functions carry out some specific, well defined task specified by the user. No function can work independently on their own. They need to be called in the main ( ) function for working.

WHY DO WE NEED FUNCTIONS?

Functions have many uses. For example, a programmer may have a block of code that he has repeated forty times throughout the program. A function to execute that code would save a great deal of space, and it would also make the program more readable. Also, having only one copy of the code makes it easier to make changes. Another reason for functions is to break down a complex program into logical parts. For example, take a menu program that runs complex code when a menu choice is selected. The program would probably best be served by making functions for each of the actual menu choices, and then breaking down the complex tasks into smaller, more manageable tasks, which could be in their own functions. In this way, a program can be designed that makes sense when read. And has a structure that is easier to understand quickly.

Functions are used in the programs because of the following advantages:
  • Repetition of the same block of code is avoided thus saving both    time and   space.
  • Programs become easy to write.
  • Debugging of programs becomes faster and easier.
  • By using functions, portability of program is very easy.
  • Functions reduce the length of the program.
  • Memory is properly utilized.
FUNCTION DEFINITION

The function definition has two principal components
  • Function declaration or prototype
  • Body of the function.
Syntax                                                                                 

<return type> <function name> (argument 1, argument 2    )
{
statement block;
return (argument) ;
}


Here,
  • <return type> specifies the datatype of the value to be returned. It can be either int, long int, char, float, double etc.
  • <function name > specifies the name of the function. The name of the function follows the same rules as that are for naming an identifier.
  • (argument 1, argument 2    ) this is the list of arguments along with their data types, which the function is supposed to take as parameter.
  • statement block- this defines the action to be performed by the function. This is a compound statement, which is sometimes referred to as the body of the function.
  • return statement- This statement returns the control back to the main program. Whenever the compiler executes the return statement the control shifts back to the calling program. The 'value' present in the pair of parenthesis is returned to the calling program.

FOR EXAMPLE                                                                
int biggest (jnt 0, int b)
{
if (0 > b)
return (0) ;
else
return (b) ;
}


Above is the definition of a function that is used to find the biggest of the two numbers 0 and b.
Here
  • int specifies that the function returns on integer value
  • biggest specifies the name of the function.
  • (jnt 0, int b) specifies that the function takes two integer arguments.
  • The body of the function compares '0' and 'b' and returns the appropriate value.
  •  Function declaration or prototype
This is the first line of a function definition. It contains the data type of the value returned by the function, followed by the function name and a set of arguments separated by commas and enclosed in parenthesis. Each argument is preceded by its da~type. The function declaration ends up with a semicolon.

Syntax                                                                   

<datatype> <function name> (datatype arg 1, datatype arg 2    ) ;

If the pair of parenthesis is empty, it specifies that the function does not take any argument. The arguments that a function has are also called 'formal arguments' . These formal arguments represent the data items that are transferred into the function from the calling portion of the program. They are also known as 'parameters' or 'formal parameters'
The names of the formal arguments are not required to be the same as the names of the actual arguments, in the calling portion of the program. But it is necessary that each formal argument must be of the same datatype, as the data item it receives from the calling portion of the program. The user can also just write the datatype of the formal argument in the argument list as shown:

int biggest (int, int) ;
or
int biggest (int a, int b) ;
  • 'Return' Statement
Return statement is used to return the value from the function to the calling program. The 'return' statement can be written as :


Syntax                                                                

return (value) ;
or
return (expression) ;


The value of the expression is returned to the calling program. The expression is optional. In this case, the return statement simply causes the control back to the calling portion of the program, without any transfer of information. This is shown below:
return ;
A function can return only one value to the calling program. But a function definition can include multiple return statements, each containing different expression. 

The two functions performed by the return statement are :

  • Transfer of control from the function back to the calling program or function.
  • Returning the value to the calling function.
There is no restriction for the return statement to be at the end of the function. It can be used anywhere in the function.

  • FUNCTION CALL
A function can be called by specifying its name followed by list of arguments separated by commas enclosed in parenthesis. The syntax of the function call is very similar to that of the declaration except that return type and datatype of the arguments is not used.

function name (arguments) ;
var = function name (arguments) ;

The arguments enclosed in parenthesis are called 'actual arguments' because it represents the names of those data items that have to be actually transferred. If the function call does not require any arguments, an empty pair of parenthesis must follow the name of the function. For example,

c = biggest (x, y) ;
or
c = sum ( ) ;


The arguments are also called actual parameters. It should be noted that datatype is not included in a function call. On execution of the function call statement the control transfers to the function; the statements in the function definition are executed and on executing the return statement, the control is returned to the statement following the function call. For example,
   
void main ( )
    {
       intx, y;
           func (x, y) ;
           printf ("Hello') ;
           //(1) control shifted to func ( )
        }
      void func (int a, int b)
       {

                                                 //(2) statements in func ( ) are executed
        return ;                            //(3) Transfer of control back
        }


Note:- The user must make sure that, the actual arguments, if any, must correspond in number, type and order with formal arguments. The actual arguments can be constants, variable names, subscripted variables or expressions.


CATEGORIES OF FUNCTION

A function may belong to one of the following categories depending on whether arguments are present or not, whether a value is returned or not .

  • Functions with no arguments and no return values.
  • Functions with arguments and no return value.
  • Functions with arguments and return values.
  • Functions' with no arguments but return values.

  • FUNCTION WITH NO ARGUMENTS AND NO RETURN VALUES

A function takes no arguments, when it does not receive any value or data item from the calling function. A function can also not return any value to the calling function. For example, consider the following program with no arguments and no return value.
 
# include <stdio.h>
{
void print ( ) ;
print ( );
}

void print ( )
{
char name [20] ;
printf ("Enter your name") ; 
scanf ("%s", name) ;
printf ("\nname is %s", name) ; 
}

Output:

Enter your name: ABC
Name is ABC

In this category of functions the argument list is empty but the parenthesis must follow the function name during function definition or function prototype. Since these functions do not return any value to the calling program, the return type is taken as 'void' . These functions mayor may not contain a return statement.

  • FUNCTION WITH ARGUMENT AND NOT RETURN VALUE

In this category the function receives arguments from the calling function. But the calUng function does not receive any data from the called function. For example,

# include <stdio.h>
#include<conio.h>
void main ( )
{
int p,r,t ;
void SI (int x, int y, int z) ;
clrscr ( ) ;
printf ("enter p, r, t") ;
scanf ("%d%d", &p, &r, &t) ; SI (p, r, t) ;
getch () ;
}

 
void SI (int x, int y, int z)
{
float s ;
s = (x * y * z)/100 ;
printf ("Simple Interest: %f", s) ;

}
 
In the above program, the main program is passing three arguments x, y, z to the function SI. The function SI receives these values in its formal arguments and computes the value in 's' and hence prints the result in the function only. Since the function is not returning value, its return type is taken as 'void'.



  • FUNCTION WITH ARGUMENT AND WITH RETURN VALUE

In this category, main program or calling program will send actual parameters or actual arguments to the function. The called function will apply processing on these values and then returns some     value to the main program or the calling program.

For example                                                                       

#include<stdio.h>
#include<conio.h>
 
void main ( )
{
 int p, r, t, si ;
 int SI (int x, int y, int z)
 clrscr ( ) ;
 printf ("Enter values of p, r, t") ;
 scanf ("%d %d %d", &p, &r, &t) ; 

 si = SI (p, r, t) ;
 printf ("Simple Interest is : %d", si) ;
 getch ( );
}

int SI (int x, int y, int z)
{
 int s;
 s = (x * y * z)/100 ;

return (s) ;
}


In the above program, the main program or the calling function passes three actual arguments - p, r, t to the function SI. The function SI receives these arguments in its three formal parameters- x, y, z. The simple interest is calculated in 's' and returned to the calling function or main program.

  • FUNCTIONS WITH NO ARGUMENTS BUT RETURNS A VALUE

In this category, the main or calling function does not send any arguments but the called function does return a value to the calling function or main program

For example                                                                          

#include<stdio.h>
#include <conio.h>

void main ( )
{

 float si ; float SI ( );

si = SI ();
printf ("\n simple interest is : %f", si) ; 
getch () ;

}

float SI ( )
{
 float p, r, t, s ;
 printf ("\n enter p, r, t, ") ;

scanf (" %f %f" %f, &p, &r, &t) ;
s = (p* r* t)/100 ;
 return (s) ;
}


In the above program, the main( ) does not pass any arguments to the called function. The called function requests for -p, r, t from the user computes the simple interest in's' and returns the value in 's' to the main program. In the main program the value of 's' is copied to 'si'.