Friday 26 November 2010

FUNCTION | Fundamentals of Programming (FOP)

          DEFINING A FUNCTION


A function has three principal components :
the first line, 
the argument declarations
the body of the function

The first line of a function definition contains the byte specification of the value returned byte the function, followed by the function name and (optionally) a set of parameters separated by comas and enclosed in parenthesis. The type specification can be omitted if the function returns an integer or a character, in entry pair of parenthesis must follow the function name if the function definition does not include any arguments. In general terms, the first line can be
written as :

Data-type name(formal arg1, arg2, argn) 

Where data type represents the data type of the value, which is returned, and name represents
the function name. 
The formal argument allows information to be transferred from the calling portion of the program to the function. They are also known as parameter on formal parameters.(the corresponding arguments in the functions reference are called actual arguments since they define the information actually being transferred. The identifiers used as formal argument are local in the sense that they are not recognized outside of the function. Hence, the names of the formal arguments may be same as the names of the other identifiers that appear outside the function definition.

The argument declaration follows the first time. All format arguments must be declared at the point in the function. Each format argument must have the same data type as its corresponding actual arguments. That is each formal argument must be of the same data type as the data items it receives from the calling portion of the program.

The remainder of the function definition is a compound statement that defines the action to be taken by the function. This command statement is sometimes referred to as the body of the function. It must follow the formal argument declarations. Like any other compound statements, the statement can contain expression statements. Other compound statement, control statements, and so on. As a result it can even access itself. This process is known as
recursion.

For example,



Low-to-up(Char el)
{
char c2
c2 = c1>=’a’ && c1<=’z’) ? (‘A’+cl-‘a’) : cl;
 return c2;
}



Where data type represents the data type of the quantity returned by the function, name represents the function name and argument type 1 argument type 2  argument type n refers to argument data types of the first argument, second argument and so on. Remember  that the argument data type are optional even in the situations that requires a function declaration. Most C compilers supports the use of the keyword void in function definition as a return data type indicating that the function does not return anything. Function declaration may also include void for the same purpose. In addition void may appear in an argument list, in both function definition and function declarations, to indicate that a function does not require arguments. In the later case, void appears by itself in the area normally used for argument specifications.

CATEGORY OF FUNCTION :

A function, depending and where argument are present or not and where a value is returned or
not, may belong to one of the following categories.

No arguments and not return values:

When a function has no arguments, it does not receive a data from the calling function.
Similarly, when it does not return a value, the calling function does not receive any data from
calling function. In fact, there is not data transfer between the calling function and the called
function.

We would ensure that the function call has matching arguments. In case, the actual arguments
are more than the formal arguments, extra actual arguments are discarded. On the hand, if the
actual arguments are less than the formal arguments, the unmatched formal arguments are
initialized to some garbage values. Any mismatch in data type may also result in passing of
garbage value. Remember no error message will be generated. 

While the formal arguments must be void variable names; the actual arguments may be
variable name expression or constants. The variable used in actual arguments may be assigned
values before the function call is made. 

Arguments with return values :

When function is called with arguments, then called function will receive the arguments. Then
the statement included within the body at the called function will be executed.

RECURSION :
Recursion is a process by which a function calls itself repeatedly, until some specified  condition has been satisfied. The process is used for repetitive computation in which each action is stated on forms of previous result. The process is used for repetitive computation in which each action in terms of a previous result. Many iterative problems can be written in this form.

In order to solve a problem recursively, two condition must be satisfied. First, the problem must be written in recursive form and second the problem example, we wish to calculate the factorial of a positive integer quantity. We would normally express this problem as n1=1 x 2 x 3 x 4 .. x n where n is the specified positive integer. However, we can also express in another  way, by writing n=1 = n*(n-1). This is a recursive statement of the problem, in which last expression provides a stopping condition for the recursion.

When a recursive program is executed the recursive function calls are not executed
mmediately. Rather, they are placed on a stack until the condition that terminates the recursion
s encountered. The function calls are then executed in reverse order, as they are popped off the
tack.
f a recursive function contains local variables, a different set of local variables will be created
during each call. The name of the local variables, will be cause always be the same, as declared
within the function. However, the variables will represent a different set of values each time
he function is executed. Each set of values will be stored on the stack, so that they will be
vailable as the recursive process unwinds i.e. as the various function calls are popped off
he stack and executed. 

THE SCPOE AND LIFETIME OF VARIABLES IN FUNCTION :
A variable in C can have any one of the four storage classes :

Automatic variables : 
Automatic variables are declared inside a function in which they are to be utilized. They are
reated when the function is called and destroyed automatically when the function is exited,
hence the name automatic. Automatic variables are therefore private to the function in which
hey are declared. Because of this property, automatic variables are also referred to as local or
internal variable. A variable declared inside a function without storage class specifications, by default, an
automatic number in the example below is automatic.

One important feature of automatic variable is that their value cannot be changed accidentally. This assures that we may declare and use the same variable name in different function in the ame program without causing any confusion to the compiler. There two consequences of the cope and longevity of auto variables. First any variable local to main will normally live hroughout the whole program, although, it is active only in main. Secondly, during recursion, he nested variables are unique auto variables, a situation similar to function, nested auto variable with identical names.

Automatic, variable can also be defined within a set of braces known as blocks they are
meaningful only inside the block where they are defined. 

External variables :
Variables that are both alive and active throughout the entire program are known as external
variables. They are also known as global variables. Unlike function in the program external
variables are declared outside a function. For example the external declaration of integer
number and float length might appear is :

Int number;
Float length = 7.5;
Main()
{
 ---
 ---
}

function1()
{
 ---
 ---
}
function2()
{
 ---
 ---
}

the variables number and length are available for use in all the three functions. In case a local
variable and a global variable have the same name, the local variable will have preceded over
the global variable in the function where it is declared.

Once a variable has been declared as global, any function can use it and change its value. Then
subsequent function can reference only that new value. Because of this property, we should try
to use global variables only for tables of for variables shard between functions when it is
inconvenient to pass them as parameters. 

One other aspect of a global variable is that it is visible only form the point of  declaration to
the end of the program.

Note that the extern declaration does not allocate storage space for variables. In case of arrays,
the definition should include their size as well.

An extern within a function provides the type information to just that one function. We can
provide type information to all function within a file by placing external declaration before any
of them, as shown below.



Extern float height []
 Main ()
 {
   int t;
   void printout();
   ---
   ---
   printout();
 }
  void printout ()
 {
   int t;
   ---  
   ---
}

float height(size);



MULTIFILE PROGRAMS :
Multiple source files can share a variable provided it is declared as an external variable
appropriately variable that are shared by two or more files are global variables and therefore
must declared them according in one file and then explicitly define them with extern in other
files. The extern specifies tells the compiler that the following variables types and names have
already been declared elsewhere and now need to create storage space for them. For example,

File 1.c
Main()
{
  extern int m;
 int l;
 ---
 ---
}
function1()
{
 int j;
 ---
 ---
}

file 2.c
int m;
function2()
{
 int il;
 ---
 ---
}
function3()
{
 int count;
 ---
 ---
}





the extern, declaration in place where secondary reference are made, if we declare a variable as
global in two different files used by a single, program then the linker will have a conflict as to
which variable to use and therefore, is use a warning. When a function is defined in one file
and accessed in other, the later file must include a function declaration. The declaration
identifies the function we usually place such declarations at the beginning of the file, before all
function. Although all functions are assumed to be external, it would be good practice to
explicitly declare such functions with the storage class extern.

Static variables :
As the name suggest, the value of static exist until the end of the program. A variable can be
declared static using the keyword static like:    
    Static int x;
    Static float y;
A static variable may be either an internal type or an external type depending on the piece of
declaration. Internal static variables are those which are declared inside a function. The scope 
of internal static variable extend up to the end of the function in which they are defined.
Therefore, internal static variable are similar to auto variables, except that they remain in
existence throughout the remainder of the program. Therefore, internal static variables can be
used to retain values between function calls.

A static variable is initialized only once, when the program is compiled. It is never initialized
again. An external static variable is declared outside that program. The difference between a
static external variable and simple external variable is that the static external variable is
available only within the file where it is defined while the simple external variables can be
accessed by other files. 

It is possible to control the scope of the function. For example, we would like a particular
function accessible only to the function in the file in which it is defined. And not to function in
other files. This can be accomplished by defining that function with the storage class static.

Register variable:
We can tell the compiler that a variable should be kept in one of the machine’s register instead
of keeping in the memory where normal variables are stored. Since a register access is much
faster than a memory access. Keeping frequently accessed variables in the register will lead to
faster execution of program. This is done as follows :
  Register int count;

Since only a few variables can be placed in the register, it is important to carefully select the
variable for the purpose.


PASSING ARRAYS TO A FUNCTION:

An array name can be used as an argument to a function, thus permitting the entire array to be
passed to the function. The manner in which the array is passed differs mainly. However, from
that of an ordinary variable.

To pass an array to a function, the array name  must appear by itself without brackets or
subscripts as an actual argument within the function call. The corresponding format argument
is written in the same manner, though it must be declared as an array within the formal
argument declaration. When declaring array as a format argument, the array name is written
with a pair of empty square brackets. The size of the array is not specified within the format
argument declaration.

The following program outline illustrates the passing of an array from the main portion of the
program to the function :

Main()
{
 int n;
 float avg;
 float list[100];
  float average(int a, float x[]);
  ---
  ---
  avg = average(n,list);
  ---
}
float average(n,x)
{
 int a;
 float x[];
 --- 
 ---
 }



within main we see a call to the function average. This function call contains two actual
argument the integer variable n and the one-dimensional floating-point array list. Notice that
list appears as an ordinary variable within the function call.

In the first line of the function definition we see two formal arguments, called a and x. the
formal argument declarations establish a as an integer variable and x as an one-dimensional
floating point array. Thus there is a correspondence between the actual argument list and the
formal argument x. note that the size of x is not specified within the formal argument.

If the first line of a function definition includes the formal argument declaration, each array
name appearing as a formal argument must be followed by an empty pair of square braces. We
can pass the elements of array to the function in two ways :
 
•  pass by value approach
•  pass by reference approach

PASSING BY VALUE APPROACH

When each element of array is passed one by one to the functions as an actual argument, at that
time element behaves as an ordinary variable. This manner of passing array value is called pass
by value approach.
In such cases, formal argument need not be an array. It may be any ordinary variable. That
element then be accessed throughout the function and then control returns to the calling
function, that alteration can not be recognized in the calling portion of the program because
passing element process will make a copy of original element to the formal argument.


PASS BY REFERENCE APPROACH

When an array is passed to a function, however the values of the array elements are not passed
to the function. Rather the array name is interpreted as address of the first array element (i.e.
the address of the memory location containing the first array element). This address is assigned
to the corresponding format argument when function is called. The formal argument therefore
becomes a pointer to the first array element. Argument passed in this manner are said to be
passed by reference.

When a reference is mad to an array element within the function, the value of the element
subscript is added to the value of the pointer to indicate the address of the specified array
element. Therefore any array element can be accessed from within the function, alteration will
be recognized in the calling portion of the program.

The return statement cannot be used to return an array. Therefore, if the elements of an array
are to be passed back to the calling portion of the program, the array must either be defined as
an external array whose scope includes both the function and the calling portion of the
program, or it must be passed to the function as a formal arguments. 

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Grants For Single Moms