Thursday 5 December 2019

C Tutorial - Function and Recursion with Examples


Function and Recursion

Function Definition

Functions are self contained program segments that carry out some specific well defined task.

In "C" , we include the header files like stdio, conio, string, etc.

These files contain number of library functions which are as follows:

printf( ), scanf( ), getchar( ), putchar( ), getche( ), gets( ), puts( ), strlen( ), getch( ), etc.

In C it is possible for the function to call themselves. we will see how it can be possible through Recursions.

A Function is a self-contained block of statement that perform a coherent task of some kind. Every C program must have a function. One of the function must be main().

Why should we use Function?

a) Using function it becomes easier to write programs and keep track of what they are doing

b) Length of the program can be reduced by using function.

c) Debugging is easier.

d) It facilitates top-down modular programming.

Classification of Function

C function can be classified into two categories:

1. Library function:

They are predefined in the standard library of C. We need to include the Library.

2. User-defined function:

User defined functions are need to be developed by the user at the time of program writing


Function Declaration

Before defining the function, it is desired to declare the function with its prototype.

In function prototype, the return value of function, type, and number of argument are specified.

Function declaration is written in following ways:

return data_type function_name (data_type argument 1, data_type argument 2 ................data_type argument n)
{
local variable declaration;
executable statement 1;
executable statement 2
..................................
................................
executable statement n;
return(expession);
}

Note: An empty pair of parenthesis must follow the function name if the function definition does not include any arguments.

Example:

If it returns a float than command is:

float f1(float arg 1, int arg 2);

if it returns no value or return a character, then replace float by void or char respectively. If no arguments passed into a function than command is:

char fun1 ( );


Function Call

Function can be called either by value or by reference .A function can be called by specifying its name followed by a list of arguments enclosed in parentheses and separated by commas.

From the above example the following line is used as a function call:

sum=add(a,b); /* function call */

Call by value: Call by value means directly pass value within the function.

Example: 


#include
// function prototype, also called function declaration
void swap(int a, int b);          
int main()
{
    int m = 22, n = 44;
    // calling swap function by value
    printf(" values before swap  m = %d \nand n = %d", m, n);
    swap(m, n);                        
}
void swap(int a, int b)
{
    int tmp;
    tmp = a;
    a = b;
    b = tmp;
    printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}


Output:

values before swap m = 22
and n = 44
values after swap m = 44
and n = 22

Call by reference: Call by reference means sending the addresses of the argument to the called function.

In this method the addresses of actual arguments in the calling function are copied into formal arguments of the called function. (later discussed in pointer section)

Example:

#include
// function prototype, also called function declaration
void swap(int *a, int *b);
int main()
{
    int m = 22, n = 44;
    //  calling swap function by reference
    printf("values before swap m = %d \n and n = %d",m,n);
    swap(&m, &n);        
}
void swap(int *a, int *b)
{
    int tmp;
    tmp = *a;
    *a = *b;
    *b = tmp;
    printf("\n values after swap a = %d \nand b = %d", *a, *b);
}

Output:

values before swap m = 22 
and n = 44
values after swap a = 44
and b = 22

The Return Statement

Information is returned from the function to the calling portion of the program via return statement.

General form of return statement:

return;
or
return(expression);

Storage Classes

There are two different ways to characterize variables:

1. By data type
2. By storage Class

Data type refers to the type of information while storage class refers to the life time of a variable and its scope within the program.

A variable in c can have any one of the four storage classes:

1. Automatic Variable:

It is created when the function is called and destroy when the function is exited. Hence the name is Automatic. By default a variable is declared Automatic.

2. External Variable:

It is also known as Global Variable. This variables can be accessed from any function that falls within their scope.

3. Static Variable:

A static variable may be either internal or external type , depending on the place of declaration.

Internal static variable extends up to the function in which they are defined and external static variable is declared outside of all function and is available to all the functions in the program.

4. Register Variable:

We can tell the compiler that a variable should be kept in one of the machine's registers, instead of keeping in the memory (where normal variables are stored ).

Since, a register access is much faster than a memory access and keeping the frequently accessed variables in the register will lead to faster execution of programs.



Recursion

Repetitive calling of the same function is called recursionRecursions are those functions which call itself again and again. Recursive functions can easily become infinite loops.

Example: Sum of Natural Numbers Using Recursion


  1. #include
  2. int sum(int n);
  3. int main() {
  4. int number, result;
  5. printf("Enter a positive integer: ");
  6. scanf("%d", &number);
  7. result = sum(number);
  8. printf("sum = %d", result);
  9. return 0;
  10. }
  11. int sum(int n) {
  12. if (n != 0)
  13. // sum() function calls itself
  14. return n + sum(n-1);
  15. else
  16. return n;
  17. }
Output
Enter a positive integer:3
sum = 6
 Previous Page                        Next Page

More Topics:














100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...