Sunday, December 22, 2013

Chapter 7: Functions



7.1 Introduction and Advantages

What is a function?
A function is a single comprehensive unit containing blocks of statements that performs a specific task. The specific task is repeated each time function is called. So this avoid the need of rewriting the same code again and again. Every program must contain one function named main() where the program always begin execution. When a function is called, the program execution is shifted to the first statement in the called function. After the function returns to the calling function, values can be returned and that value can be used as an operand in an expression.

Why to use function?
·To avoid rewriting of the same code again and again
·Separating the code into modular functions also make the program easier to design, understand and debug
·It helps us create to manageable program development environment.
So it is not good to write a entire program into one function. Instead, break a program into small units and write functions for each of these isolated subdivisions.

7.2 Defining and Declaring a function
Defining a function
A function definition has name, a parenthesis pair containing one or more parameters and a body. For each parameter, there should be a corresponding declaration that occurs before the body.
The general format of the function definition is given as follows

return_type function_name(datatype argument1,datatype argument2,….)
{
            statement1;
                                    ;
                                    ;
            return ;
}

Declaring the type of the function
The function may return varying type of value to the calling portion of the program. Any of the datatype such as int, float, char etc. can be in the function declaration. If a function is not supposed to return value, it can be declared as type void.
Example of i)
void  myfunction ( float  a,char b, int c)
{
                                    ;
                                    ;
}

Example of ii)
void  myfunction ( void)
{
                                    ;
                                    ;
}

Example of iii)
float myfunction ( float  a,char b, int c)
{
                                    ;
                                    ;
}

Example of iv)
int myfunction ( void )
{
                                    ;
                                    ;
}

Function Definition
A function definition is a unit of a function itself with the type of value it returns and its parameters declared   and the statements specified in it,  that are executed when the function is called.
Actual arguments and Formal arguments
Any variable declared in the body of a function is said to be local to that function. If the variables are not declared either or arguments or inside function body are considered “global” to the function and must be defined externally. Arguments defined inside the function are called formal arguments where as the argument from which the arguments have been passed to a function is known as actual arguments.

#include <stdio.h>
void line(void);  //function prototype or function declaration

void line(void)   //function definition
{
    int j;
    for(j=1;j<=42;j++)
        printf("*”);
}
void main(void)
{
    clrscr();
    printf("Welcome to the world of  C programming \n)";
    line();    //function call
}
return statement
The return() statement has two purposes. First, executing it immediately transfers control from the function back to the calling program. And second, whatever is inside the parentheses following return is returned as a value to the calling program. The return statement may or may not include an expression. If return contains no parameters then this return is used to transfer the control used only with void else if return has got argument having bracket or without bracket then this return is returning value to the calling portion of the program. There is no restriction on the number of return statements that may be present in a function. Also the return statement need not be always be present at the end of the called function.
Note: Using a return statement, only one value can be returned by a function

Syntax:
return ;
return (expression);
Example:
A program to return  value from a function.
#include<stdio.h>
#include<conio.h>

float max_value(float,float);  //function prototype or function declaration
void main(void)
{
            float x,y,max;
            printf("Enter the two numbers");
            printf(“%d %d”,&x,&y);
            max=max_value(x,y);
            printf("The maximum value is  %d",max);
            getch();
}

float max_value(float a,float b)
{
            if(a>b)
                        return a;
            else
                        return b;
}

7.3 Library functions and User Defined Functions

There are basically two types of c functions - library functions and userdefined functions. Library functions are predefined in the header files and are not required to be written by the user at the time of writing a program. Example of some library functions are getch(), getche(); (For more  Chapter 4 section 4.6)

User defined functions may be classified in the following three ways based on formal arguments passed and the usage of the return statement.

a) A function is invoked without passing any formal arguments from the calling portion of a program and doesn’t return any value back to the calling function.

#include<stdio.h>
#include<conio.h>
void main()
{
   void display(void);  //function declaration or function prototype
   display();
   getch();
}
void display(void)  //Function definition
{
  int x,y,sum;
  printf("Enter the value of x and y:");
  scanf("%d%d",&x,%y);
 sum=x+y;
 printf("Sum=%d",sum); 
}

b) A function is invoked with formal arguments from the calling portion of a program but the function doesn’t return any value back to the program.

#include<stdio.h>
#include<conio.h>
void square(int);
void main()
{
            int max;
            printf("Enter the value for n:");
            scanf(“%d”,&max);
            for(int i=1;i<=max;++i)
                        square(i);
            getch();
}
void square(int n)
{
            int value;
            value=n*n;
            printf("Square of i is %d\n”,value);
}

c)Function is invoked with formal arguments from the calling portion of a program which returns a value back to the calling environment.

//Program to calculate factorial using function
#include<stdio.h>
#include<conio.h>

int fact(int);
void main(void)
{
            int x,n;
            printf(“enter the number");
            scanf(“%d”,&n);
            x=fact(n);
            printf("The factorial is %d",&x);
            getch();
}

int fact(int n)
{
            int i,value=1;
            if(n==1)
            {
                        return value;
            }
            else
            {
                        for(i=1;i<=n;i++)
                        {
                                    value=value*i;
                        }
                        return value;
            } //else ends here
} //function fact ends here



Rules that must be remembered while defining function

·A function prototype declaration must appear at the beginning of the program following the #include statement. In a function prototype the type of the function and the type of each formal argument must be specified. The variable names used for formal arguments in a function prototypes are arbitrary; they may even be blanks. Each function prototype must be terminated by a semicolon.
·A function name may be any valid identifier. The type of the function specifies the type of the quantity which will be returned to the calling program.
·The formal arguments used in defining a function may be scalars or arrays. Each formal arguments type must be specified. For example int add(float a,b,c) is invalid and should be in the form int add(float a,float b,float c)
·Within a function definition other variables may be declared and used. Such variables are local to the function and are not known outside the body of the function.
·Within a function definition one cannot define another function.

Rules that must be remembered while calling a function

·The actual arguments in the calling function must agree in number, order and type with the formal arguments in the function declaration.
·Copies of the values of actual arguments are sent to the formal arguments and the function is computed. Thus the actual arguments remain unchanged.
·If the formal arguments is an array name the corresponding actual arguments in the calling function must also be an array name of the same type.
·A return statement in the body of the function returns a value to the calling function. The type of expression used in return statement must match with the type of the function declared. There may be functions without return statement. In such a case the function must be declared as void.
·A function can return only one value.

7.4 Recursion or Recursive function

A function which calls itself directly or indirectly again and again is known as recursive function. Recursive functions are useful while constructing the data structures like linked list etc. There is distinct difference between normal and recursive functions. A normal function will be invoked by the main function whenever a function call is made, whereas the recursive function will be invoked itself directly or indirectly as long as the given condition is satisfied.

Recursion is the process of defining something in terms of itself, and is sometimes called circular definition.
Recursion has many negatives:
It repeatedly invokes the mechanism, and consequently increases the overhead of function calls. This repetition can be expensive in terms of both processor time and memory space. Each recursive call causes another copy of the function, these set of copies can consume considerable memory space.

#include<stdio.h>
#include<conio.h>
long fact(int);
void main()
{
            int n;
            long y;
            clrscr();
            printf("Enter the factorial number");
            scanf(“%d”,&n);
            y=fact(n);
            printf("The factorial number is %d and the factorial of the given number is
%ld",n,y);
            getch();
}
long fact(int z)
{
             long value;
             if(z==1)
                        return 1;
             else
                        value= z*fact(z-1); //function recursion occurs here.
             return value;
}
555                                                                 
sequence of recursive calls


Recursion Vs. Iteration
1Both Iteration and recursion are based on control statements: Iteration uses a repetition statement (such as for, while, do-while); Recursion uses a selection statement such as (if, if-else, or switch).
2Both Iteration and Recusrsion involves repetition: Iteration explicitly uses a repetition statement; Recursion achieves repetition through repeated function calls.
3Both Iteration and Recursion each involve a termination test: Iteration terminates when the loop continuation condition fails; Recursion terminates when a base case is recognized.
4Both Iteration and Recursion can occur infinitely: An infinite loop occurs in the iteration if the loop continuation test never becomes false(e.g. for(i=1;i>0;i++)); Infinite recursion occurs if the recursion step does not reduce the problem each time in a manner that converges on the base case.

7.5 Use of Array in Function (Array and Functions)


The entire array can be passed on to a function in C. No subscript or brackets are required to invoke a function using arrays.

Example
Program using array to do sorting in ascending and descending order

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

/*function  prototypes*/
void getdata(int array[10],int);
void showdata (int array[10],int);
void descending_sort (int array[10],int);
void ascending_sort (int array[10],int n);

/*function definition*/
void descending_sort (int array[10],int n)
{
            int temp,i,j;
            for ( i=0;i<n-1;++i)
            {
                        for (j=i+1;j<n;++j)
                        if (array [j]>array[i])
                        {
                                    temp=array[i];
                                    array[i]=array[j];
                                    array[j]=temp;
}
            }
   showdata(array,n);
}
void ascending_sort (int array[10],int n)
{
            int temp,i,j;
            for ( i=0;i<n-1;++i)
            {
                        for (j=i+1;j<n;++j)
                        if (array [i]>array[j])
                        {
                                    temp=array[i];
                                    array[i]=array[j];
                                    array[j]=temp;

                        }
            }
   showdata(array,n);
}
void getdata(int array[10],int n)
{
            int i;
            for(i=0;i<n;i++)
            {
                        printf("enter the elements in an array[%d]=",i);
                        scanf("%d",&array[i]);
            }

}

void showdata(int array[10],int n)
{
            int i;
            printf("the data in the array are \n");
            for (i=0;i<n;i++)
                        printf("%d\t",array[i]);
}
main()
{
int x[100];
int n,choice;
printf("Enter how many elements in the array:\n");
scanf("%d",&n);
getdata(x,n);
do
{
printf("*Bubble sort Operation*");
printf("\n1. Ascending Order");
printf("\n2.Decsending Sort");
printf("\n3. Exit");
printf("\n Enter your choice:");
scanf("%d",&choice);
switch (choice)
{
 case 1:
ascending_sort(x,n);
            break;
case 2:
            descending_sort(x,n);
            break;
case 3:
            exit(0);
}
} while(choice>=1 || choice<=3);
}



7.6 Passing By value and Passing By address (Call By Value and Call By Reference)
Arguments can be passed in function in one of the following two ways
·Passing by value( Sending the values of the arguments)
·Passing by reference(Sending the address of the arguments)

When arguments are passed by values the "value" of each actual argument in the calling function is copied into corresponding formal argument of the called function. With this method, changes made to the formal arguments in the called function have no effect on the values of the actual arguments in the calling function. As we noted the function doesn’t have to access the original variable in the function definition. In fact, this provides security such that the function cannot harm the original variable.

Program illustrating Call by value

#include<stdio.h>
#include<conio.h>
void swap(int ,int);
void main()
{
              int m=5;
              int n=10;
              clrscr();
              swap(m,n);
              printf("m=%d\tn= %d”,m,n);
              getch();
}

void swap(int a,int b)
{
              int t;
              t=a;
              a=b;
              b=t;
             printf("a=%d\tb=%d",a,b);
}
 Output: a=10   b=5      m=5     n=10
In the above case when the function is called, it gets a copy of the arguments ("Call By Value"). The function can not affect the value that was passed to it, only its own copy.
If it is necessary to change the original values, the addresses of the arguments can be passed as shown below, which is called Call By Reference.
Passing arguments by reference uses a different mechanism. Instead of a value being passed to a function, a reference of the original variable, in the function definition is passed. In this case the address of actual arguments in the calling function are copied into formal arguments of the called function
The primary advantage of passing by reference is that the function can access the actual variables in the calling program. The other benefit  is that it provides a mechanism for returning more than one value from the function back to the calling program.

Program illustrating Call By Reference. (The concept will be clear after reading pointer concept)
#include<stdio.h>
#include<conio.h>
void swap(int *,int *);
void main()
{
              int m=5;
              int n=10;
              clrscr();
              swap(&m,&n);
              printf("The value of m and n after swapping is %d and %d”,m,n);
              getch();
}
void swap(int *a,int *b)
{
              int t;
              t=*a;
              *a=*b;
              *b=t;
}

7.7 Macros
We have already seen that the #define statement can be used to define symbolic constants within a program. At the beginning of a compilation process, all symbolic constants are replaced by their equivalent text. Thus, symbolic constants provide a form of shorthand notation that can simplify the organization of a program.
The #define statement can be used to define macros; i.e., single identifiers that are equivalent to expressions, complete statements or group of statements.
Example
#include<stdio.h>
#include<conio.h>
#define area length*breadth
main()
{
   int length,breadth;
   printf("Enter Length and Breadth:\n");
   scanf("%d%d",&length,&breadth);
   printf("Area=%d",area);
   getch();
}

Though macro calls are like function calls, they are not really the same thing. In a macro call the preprocessor replaces the macro template with its macro expansion. Whereas, in a function call the control is passed to a function along with certain arguments, some calculations are performed in the function and a useful value is returned back from the function. Usually macros make the program run faster but increases the program size, whereas the function make the program smaller and compact.
If we use macro hundred times in a program, the macro expansion goes into our source code at hundred different places, thus increasing the program size. On the other hand, if a function is used, then even if it is called from hundred different places in the program, it would take the same amount of space in the program.
So, if the macro is simple and sweet like in our examples, it makes a nice shorthand and avoids the overheads associated with function calls. On the other hand, if we have a fairly large macro and it is used fairly often, replace macro with a function.


End of Chapter Seven
[ Note: If you have any problems regarding this then you can post the problem in comment box. we will try to solve this here. Or if you know any solution, you can also help :) ]

No comments:

Post a Comment