Function

Function :-

              A Funtion is a self containing block of repetitive statements used to perform a specific task . In other words a function is a collection of repeated statements of a program packed in a single unit and has a unique identification called function_name .

In ‘C’ programming, we generally see that a set of instructions is repeating, its OK if it repeats two or three times and is small in size BUT if programmer needs that particular set of statements more times and at different locations , so it is preferred to use a function which contains that particular set of statements and can be used from simply calling that function from anywhere in program .

 

The main purpose/advantages of using functions are:-

  • Using functions avoids the repetition , so it reduces the length of program code and saves memory
  • Using functions , we can make a program small , which increases clarity , efficiency , and takes less time to modify
  • Functions support modular programming, as we can divide a big and complex problem into small problems and more programmers can work on a single project and can make small modules, which can be unite in the main big program.
  • Using function , we can make a library of modules which can be use for future help
  • As functions are irrespective to the machine , so it support portability
  • Functions also support Recursive approach , which helps to solve a complex programming problem in itself , [Latter discuss]


                      Functions can be classified in two ways:-

  1. Library Functions
  2. User-Defined Functions

Let’s discuss them in details.

Library Functions:-

                                 These are also called in-build functions. These are predefined and precompiled functions which are designed, compiled and saved in C Library. These functions can be used from simply calling them from there names. But before using any library function, it is necessary to include the corresponding header file in that program

i.e.   #include< name. h >  

Here

name     :-   is the name of the header file to which the function belong

. h           :-   is the extension of header file

The header file is the file which contains the declaration of functions , which belongs to it

Example:

  • printf() ;     stdio.h
  • scanf() ;       stdio.h
  • sqrt() ;         math.h

 

User Defined Functions :-

                                            The functions which are defined from user to meet its requirements are called User defined functions.

                                          In programming, during the designing of complex programs the use may want some specific task to be done repeatedly and if there is no library function available for that, so the user can design its own function as per its requirement which can be easily modified and used from the programmer itself . In user defined functions there is no need to include any particular header file because function definition is itself present in the program. 

Every C program must contain at least one function, which is mostly main() function


Function Defination:                                       A function definition is a part where the actual code of function is written .

 Syntax :-

                 return_type name(argument_list)

                 {

                Statement_block ;

                 return( __ ) ;

                       }

 The first line of function definition is same as of its prototyping/declaration

 Here

 return_type :- It tells us data_type of value the function is returning like integer(int), character(char) etc

                          If the function is not returning no value so it is ‘ void ‘

 Name   :- It is simply the name of the function

 argument_list   :- It is the list of arguments/parameters , which are passed from the calling function to the called function .

 After the first line , there is the Statement_block which contain two things

      Declaration of local variables

  •       Actual function Code

 One more important is the return() ; statement , If the function is returning any value so there must be a retuning statement in the last line of statement_block , which takes the execution control back to the calling function .

Point to remember :

The arguments used in the function are formal arguments and there scope is local to that function . And the changes maid to them are not reflected back .

 

Function Declaration :

                                  It is nothing but the Prototyping of the function. As we need to declare a variable before we can use it , same in case of functions we firstly need to declare the function then we can use that variable .

Syntax:

            Return_type name( argument list) ;

 Example:        int func( int , char ) ;

 Here

 Return_type        is the data type of that value which that function is returning

 name                    is simple name of that function

 argument_list    is the list of arguments to be passed to that function

 the main difference between the function declaration and the first line of function definition is that , in declaration we use semicolon ; at the end But there is no semicolon needed in function definition

 The main purpose of using function declaration is that , it informs the compiler in advance about the data types passed between the calling and called functions , and to show the existence of that function , so that we can put the function definition code anywhere in the program .

Function Call:-

                          A function which is declared and defined must need to be used in the program therefore in order to use that function there is a need to call that function . Calling a function is a simple process in which we mention the name of the function followed by the list of arguments/parameters inclosed in brackets , and at the end there is a semicolon which tells the end of function call .

Syntax:

         Name(arguments); // its for that function which does not return any value

         Var = Name(arguments); // its for that function which return some value back to the calling function

Here Var is the name of variable , which excepts the returned value

Example:-

      Sum(10,5);

        Ans = Sum(10,5);


Categories of functions: 

Functions can be categories in four ways .

  1. Function with NO Arguments with NO Return
  2. Function with Arguments with NO Return
  3. Function with NO Arguments with Return
  4. Function with Arguments with Return

 

Function with NO Arguments with NO Return :

                                                                         These are functions which does not take any arguments from the calling function and also not return any value back to the calling function .

So in this case there is no transfer of data between called and calling function .

Syntax:-

Declaration :

void name() ;

Defination :  

Void name()

                                        {

                                        Statement_block ;

                                         }

Function Call :

                      name() ;

 Program to show the concept of function which does not accept arguments and not return any value

       // Sum of two numbers

 #include<stdio.h>

 #include<conio.h>

 void main()

{

                void sum(); // function declaration

                sum() ;       // function call

                getch() ;

}       

void sum()   // function definition       

{

                int a,b , Ans;

                printf(“\n Enter two numbers A and B”);

                scanf(“%d %d ”, &a , &b) ;

                Ans = a + b ;

                printf(“\n Sum of A and B = %d”, Ans) ;

}

Function with Arguments with NO Return :

                                                                              These are functions which take some arguments from the calling function But not return any value back to the calling function . So there is one way transfer of data which is from calling function to the called function .,

 Syntax:-

 Declaration :

                              void name(argument_list) ;

 Defination :  

                               void name(argument_list)

                       {

                       Statement_block ;

                        }

 Function Call :

                        name(arguments) ;

 Program to show the concept of function which accept arguments But does not return any value

              // Sum of two numbers

 #include<stdio.h>

 #include<conio.h>

 void main()

 {

                         void sum(int , int); // function declaration

                       int a , b ;

                            printf(“\n Enter two numbers A and B”);

                       scanf(“%d %d ”, &a , &b) ;

                       sum(a , b) ;       // function call

                       getch() ;

 }

 void sum(int x int y)   // function definition

 {

                        int Ans;

                        Ans = x + y ;

                       printf(“\n Sum of A and B = %d”, Ans) ;

 }

 Function with NO Arguments with Return :

                                                                     These are functions which does not take any arguments from the calling function But return some value back to the calling function , with the help of return statement . So there is also one way transfer of data which is from called function to the calling function .

 Syntax:-

 Declaration :

                               return_type name() ;

 Defination :  

                                return_type name()

                        {

                        Statement_block ;

                          }

 Function Call :

                         Variable = name() ;

    Program to show the concept of function which does not accept any arguments but return some value

                               // Sum of two numbers

 #include<stdio.h>

 #include<conio.h>

 void main()

 {

                             int sum(); // function declaration

                              int Ans ;

                           Ans = sum() ;       // function call

                               printf(“\n Sum of A and B = %d”, Ans) ;

                                    getch() ;

 }

 void sum()   // function definition

 {

                         int a,b , Ans;

                           printf(“\n Enter two numbers A and B”);

                           scanf(“%d %d ”, &a , &b) ;

                           Ans = a + b ;

                           return(Ans) ;

 }

 Function with Arguments with Return :

                                                              These are functions which takes some arguments from the calling function and also return some value back to the calling function , with the help of return statement . So there is Two way transfer of data between calling and called function .

 Syntax:-

 Declaration :

                                 return_type name(argument_list) ;

 Defination :  

                                  return_type name(argument_list)

                          {

                          Statement_block ;

                           }

 Function Call :

                           Variable = name(argument_list) ;

              Program to show the concept of function which accept arguments and return some value

                                 // Sum of two numbers

 #include<stdio.h>

 #include<conio.h>

 void main()

 {

                                 int sum(int , int); // function declaration

                                 int a , b , Ans ;

                                  printf(“\n Enter two numbers A and B”);

                                   scanf(“%d %d ”, &a , &b) ;

                                  Ans = sum(a , b) ;       // function call

                                   printf(“\n Sum of A and B = %d”, sum) ;

                                    getch() ;

 }

int  sum(int x , int y)   // function definition

 {

                              int Ans;

                                    Ans = x + y ;

                                  return (Ans) ;

  }


 Argument/Parameter Passing Techniques :

                                                                       An Argument passing is a simple process of transferring data form calling function to the called function .

 There are two techniques of passing arguments in C language , these are :-

  • Call from Value
  • Call from Refrence

         Call from Value :-

                              This is the default method of argument passing , in which a copy of actual arguments is made and is passed to the newly created formal arguments in the called function .Since the formal arguments contains only the copy of actual arguments which are stored at separate memory location therefore any changes made to these are not reflected back to the actual variables/arguments . One more thing is, the changes made to the formal arguments are local to block , which are lost once the control is shifted back to the calling function .

Syntax :-

Function Definition :-

return_type name(argument_list)

{

                            statement_block ;

                             return( __ ) ;

 }

 Function Declaration :-

                                      return_type name( argument list) ;

 Function Calling :-

                                      name(arguments); // its for that function which does not return any value

                 var = name(arguments); // its for that function which return some value back to the calling function

 Call from Address/Pointers :-

                                          This is another technique of passing arguments but instead of passing the value , we pass the address of that argument . If a programmer wants to reflect back the modifications made in formal arguments to the actual arguments so he must need to use pass from address method for argument passing .

              In this we use ‘&’ operator with the name of the variable to send the address of that variable , and to receive that address of arguments special variables are used called pointer variables [Read Pointers in C]

 . So I explain this with the help of syntax and you will able to see what is the actual difference between pass from value and pass from Address techniques .

 Syntax :-

 Function Defination :-

                                 return_type name(int *var1 , int *var2)

                                 {

                                    Statement_block ;

                                    }

 Function Declaration/Prototyping :-

                                   return_type name(int * , int *) ;

 Function Call :-

                                    name(&var1 , &var2) ;

 Here *var1 , *var2 are pointer variable , we are using   &var_name to pass the address of that variable .

         Call from Value

#include<stdio.h>

#include<conio.h>

void main()

{

void swap(int , int) ;

int a=10 , b=20 ;

printf(“Before Swapping are A=%d B=%d”,a,b) ;

swap(a,b) ;

printf(“\nAfter Swapping are A=%d B=%d”,a,b) ;

getch() ;

}

void swap(int x , int y)

{

int temp ;

temp = x ;

x = y ;

y = temp ;

}

           Call from Address

#include<stdio.h>

#include<conio.h>

void main()

{

void swap(int * , int *) ;

int a=10 , b=20 ;

printf(“Before Swapping are A=%d B=%d”,a,b) ;

swap(&a,&b) ;

printf(“\nAfter Swapping are A=%d B=%d”,a,b) ;

getch() ;

}

void swap(int *x , int *y)

{

int temp ;

temp = *x ;

*x = *y ;

*y = temp ;

}

  Here we see that there are two programs first is using call from value , second is call from Address . 

  • In call from value The output is :-

Before Swapping are A=10 B=20

After Swapping are A=10 B=20

  • In call from Address The output is :-

Before Swapping are A=10 B=20

After Swapping are A=20 B=10

 This is because in pass from value only the copy of actual arguments is passed therefore the changes made to formal arguments is not reflected back to the original arguments

 But in case of pass from Address , the address of actual arguments is passed therefore the changes made to formal arguments is also made to the actual arguments


Recursion :-

                  Recursion is a process in which a function call itself one or more times .

It is a powerful approach which lets a problem to be defined in itself , in this a function call itself until a soluble problem is arrived and the function which call itself is called recursive function .

If I logically speak , recursion is of two phases : winding phase , unwinding phase

 In winding phase a problem(P) is redefined in terms of sub-problems P1 , P2 , P3 , … , Pn .At Pn , there is a soluble problem which leads to the end of winding phase and the unwinding phase start in which the solution of Pn is feed back to Pn-1 , .. , P3 , P2 , P1 , P , i.e. until the P is solved , this is the end of unwinding phase .

  

 Now lets come to the programming , if you derive a recursive logic it contain two cases

 Base case , which is a non recursive definition which terminates the recursion[which ends winding phase and starts the unwinding phase ]

 General case , it specifies the recursive part of the solution .

I try to explain it with the help of an example . Let we want to find the factorial of a number .

As we know factorial of ‘n’ = n! = n*(n-1)*(n-2)* ….. 4*3*2*1

And factorial of 0 i.e. 0! = 1! = 1

Now in this case

factorial(n) =

                 1                                if n = 0 , 1

                  n * factorial(n-1)          if n > 1

       Now we write its C_language code

#include<stdio.h>

#include<conio.h>

void main()

{

 int fact(int) ;

 int Ans , n ;

 printf(“Enter a number to find Factorial”) ;

 scanf(“%d”, &n) ;

 Ans = fact(n) ;

 printf(“\n The factorial of %d is = %d ”, n , Ans) ;

 getch() ;

 }

 int fact(int n )

 {

       if(n == 0)

       return(1) ;

       else

       return( n * fact( n-1 ) ) ;

 }

 Output :-

         Enter a number to find Factorial 5

         The factorial of 5 is = 120

         I explain that how it works

As I have entered n=5 , it work like

Now n = 5 ,

if n== 0     NO

return(5 * fact(4) )                               5*24= 120

Now n = 4

if n== 0   NO

return(4 * fact(3) )                               4*6= 24

Now n = 3

if n== 0   NO

return(3 * fact(2) )                               3*2=   6

Now n = 2

if n== 0    NO

return(2 * fact(1) )                               2*1=   2

Now n = 1

if n== 0   NO

return(1 * fact(0) )                               1*1=   1

       Now n = 0 
                                               if n== 0     YES

return(1)                               

 After the last return(1) , the unwinding phase starts , in which the result of one stage is feed back to its upper level and atlast we get the result which is 5! = 120 

In this way we conclude that Recursion is a powerful concept which make a problem easy to define in itself , But I suggest to use Recursion for some difficult and complex programming problems , not for easy problems .

 

Who's online

We have 7 guests and no members online

About Us

Harsimran Singh

Hello

This website is a special gift for Programming Lovers , which want to learn basic Programming Languages and want to develop there skills Read More....

Our work

Find Us

This email address is being protected from spambots. You need JavaScript enabled to view it.

Harsimran Singh(Facebook)

Harsimran Singh(about.me)

Harsimran Singh(G+)