Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/articles/c-tutorials/)
-   -   C Functions (http://www.go4expert.com/articles/c-functions-t29953/)

msfq17a 30Dec2013 19:41

C Functions
 
Function is a block of statements that performs a specific task. It is reusable portion of the code and a very effective way to modularize your program.

For example, you may need to perform different arithmetic operations in your program like addition, subtraction, multiplication and division. To implement it in a modular way, you can define four different functions to perform this individual task.

There are two type of functions:
  1. Library function
  2. User defined function
1. Library function:

Every language is accompanied by a collection of library function which is used to perform some common, frequently used operations. For example, we have seen the frequent use of printf() and scanf() function in our C programs. These two are library functions of C and are defined in header file stdio.h.
Code:

#include <stdio.h>
int main()
{
    printf("Hello world");
}

2. User defined function:

Sometimes we need to modularize our program according to our requirement, which is not available in library. So, we need to define function ourselves, which is called user defined function. For example, you may want to greet user at the start of the program. This is how you can do this:
Code:

void greeting()
{
    printf("Hello Friend");
}
int main()
{
    greeting();
    return 0;
}

Parts of Function

  1. Function prototype
  2. Function definition
  3. Function call
1. Function prototype:

Code:

dataType functionName (parameter list)
Example of function prototype:
Code:

void func()
int func()
void func(int )
int func(int , int )

Explanation for each is provided as follows:

void func() - You cannot return any value from this function to caller function, as return type is void. If you try to return any value, error will occur. No parameter can be received by this function, as parameter list is empty.

int func() You can return only integer value from this function to caller function. Trying to return value of any other data type will cause some error. No parameter can be received by this function, as parameter list is empty.

void func(int a) - Look at the parameter in the function. It means the function receives one parameter, the data type of which is integer. While calling this function, you must send only one parameter of integer type. This function returns no value to the caller.

int func(int , int ) - You can send more than one parameter while calling a function. Look at the function stated above. It receives two parameter of type integer. It also returns an integer value to the caller function.

double func(int , double) - You can send different types of parameter in one function. In the above function, two parameters can be received. The first one should be of integer type and second one of double type. After doing all operations, according to prototype of this function, a double value must be
returned to the caller function.

2. Function definition:

Function definition is the body of the function.
Code:

void greeting()
{
    printf("Hello Friend");
}

Here, void greeting() is the prototype of the function. Function body is the statement(s) between two curly braces{}.

3. Function call

You can call a function by function name and parameter list, like this:

Code:

functionName(parameter1,…parameterN)
Function calling statement must match with the function prototype.

Function Parameters



When a function is called with parameter(s), it can pass the parameters in two way:
  1. By Value
  2. By pointer
1. By Value

In this type of calling, called function get the value of parameters from caller function and receive it with some variable. This variable works like local variable for the called function. So, any changes made in this variable is valid only for the called function, the caller does not get the change.
Code:

void changeVal(int a,int b)
{
    if(a >= b)
        b = 0;
    else
        a = 0;
}
int main()
{
    int x,y,bigger;
    printf("Enter x:");
    scanf("%d",&x);
    printf("Enter y:");
    scanf("%d",&y);

    changeVal(x,y);
    printf("After returning from changeVal function:\n");
    printf("x = %d, y = %d",x,y);
}

Output:
Code:

Enter x:25
Enter y:40
After returning from changeVal function:
x = 25, y = 40

In the above example, changeaVal function get called from main function with x and y value. This values are received by changeaVal with variable a and b. Then values of this variable get changed by changeaVal . But after returning to main function, value of x and y remains the same. The changes made by changeaVal function are local to this function.

2. By Pointer

In this type of calling, called function gets the memory of parameters from caller function and receives it with some pointers to that addresses. So, when any change is made, value of the memory address gets changed. So, the caller function also gets the effect of changed value.
Code:

void changeVal(int *a,int *b)
{
    if(*a > *b)
        *b = 0;
    else
        *a = 0;
}
int main()
{
    int x,y,bigger;
    printf("Enter x:");
    scanf("%d",&x);
    printf("Enter y:");

    scanf("%d",&y);

    changeVal(&x,&y);
    printf("After returning from changeVal function:\n");
    printf("x = %d, y = %d",x,y);

}

Output:
Code:

Enter x:25
Enter y:40
After returning from changeVal function:
x = 0, y = 40

Here we can see that main function also get the changes which is made by changeVal function.

Nested function call



Sometimes while one function calls another one, the called function also calls another function to perform its task. It works like this:

http://imgs.g4estatic.com/articles/c...ested_func.png

The example given below illustrates the whole picture. Here, main function calls the getArea function. But to calculate area, you need to know length and width. So, before returning to main , getArea calls getLength and getWidth. getLength and getWidth function individually returns length and width to getArea function. getArea then calculates the area and returns the area to main .
Code:

int getWidth()
{
    int wd=0;
    printf("Enter width:");
    scanf("%d",&wd);
    return wd;
}

int getLength()
{
    int len =0;
    printf("Enter length:");
    scanf("%d",&len);
    return len;
}
int getArea()
{
    int length, height =0;
    length = getLength();
    height = getWidth();
    return length*height;
}
int main()
{
    int area;
    area = getArea();
    printf("Area is: %d",area);
}

Return from function:

By executing return statement, execution returns from the called function to caller function. If there are multiple return statements, only one out of them is executed and the rest are ignored.

Code:

int getBigger(int a,int b)
{
    if(a > b)
        return a;
    else
        return b;
}
int main()
{
    int x,y,bigger;
    printf("Enter x:");
    scanf("%d",&x);
    printf("Enter y:");
    scanf("%d",&y);

    bigger = getBigger(x,y);
    printf("bigger num is: %d",bigger);

}

Here, in getBigger function, we can see two return statements. When any return statement is executed, no other statements are executed. Execution returns to the caller.

Recursive function



When a function is called by itself, then it is called recursive function. Recursive function has two parts:
  1. Base case
  2. Recursive case
General concept of recursive function is like this: it will call itself with some parameters until the base case is true.
Code:

int recursiveAdd(int num)
{
    if(num < 1)
        return num;
    else
        return (num+recursiveAdd(num-1));
}

int main()
{
    int input, sum = 0;
    printf("Enter number: ");
    scanf("%d",&input);

    sum = input + recursiveAdd(input-1);

    printf("Sum of number from 1 to %d is %d",input,sum);
}

The base case is:
Code:

if(num < 1)
    return num;

And the recursive case is:
Code:

else
    return (num+recursiveAdd(num-1));

As long as the number is greater or equal to 1, the function continues to call itself. When the number is less than 1, then base case is executed the recursion is stopped.

Most popular example of recursive function is to find out the factorial.
Code:

int getFactorial(int num)
{
    if(num <= 1)
        return 1;
    else
        return (num * getFactorial(num-1));   
}
int main()
{
    int input, factorial = 0;
    printf("Enter number: ");
    scanf("%d",&input);

    factorial = input * getFactorial(input-1);

    printf("Factorial of number  %d is %d",input,factorial);
}

Infinite recursion:

What if any recursive function doesn’t have any base case?
Code:

int recursiveFunc(int num)
{
    recursiveFunc(num-1);
}

Here, no base case exists for recursiveFunc. So every time it is called by itself, it never exits. It results an infinity loop.

Another scenario: Let, you wrote a base case that will never be executed. What will happen?
Code:

int recursiveFunc(int num)
{
    if(num < 1)
        return num;
    else
        recursiveFunc(num+1);
}
int main()
{
    int input, result = 0;
    printf("Enter number: ");
    scanf("%d",&input);

    result =  recursiveFunc(input-1);
}

If user gives a positive number as input, what will happen? In recursiveFunc, an integer with positive value will be passed. First time, base case will be false, so it will make a recursive call with(n+1). And if you have a closer look, every time the value of parameter will be increased by 1. So it will never be less than 1. Every time the base case fails, results an infinite recursion.

Direct and indirect recursion:

When a function calls itself, it is called direct recursion. But if two function individually call one another, what will happen?
Code:

int getX()
{
    getY();
}
int getY()
{
    getX();
}

Here, getX() calls getY(). When execution comes in getY(), it again calls getX(), and getX() calls getY(). This process continues, resulting an recursion. Sometimes, this type of indirect recursion also results an infinite recursion.

Benefits of using function:
  1. Program can be modularized into small parts
  2. Different function can be independently developed according to the requirement
  3. Increases readability and re-usability

10dial 30Aug2014 14:52

Re: C Functions
 
Thanks for posting.. really helpful..
Regards
10dial


All times are GMT +5.5. The time now is 10:34.