Showing posts with label function. Show all posts
Showing posts with label function. Show all posts

Tuesday, August 25, 2020

Gentle Introduction to C : Recursion

Originally Posted on SeedBx


Welcome to the eight part of the Gentle Introduction to C series. As said before this series aims to provide you a brief introduction to C language.

In this post, we will be talking about the concept of recursion.


Recursion

Recursion is the process in which a function calls itself directly or indirectly and the corresponding function is called a recursive function.

Example :

void func() {

    // some code...

    func();

    // some code...

}

The above function func() calls itself in the function, so this is an instance when a function calls itself directly in a recursion.

void func1() {

    // some code...

    func2();

    // some code...

}

void func2() {

    // some code...

    func1();

    // some code...

}  

In the above code functions func1() and func2() calls itself, however unlike the previous code both the functions func1() and func2() calls itself indirectly.


Each recursion function consists of two parts :

1.    General (Recursive) Case: The part of the recursive functions which expresses the solution in terms of smaller version of itself.

2.    Base Case: The part of the recursive function for which the solution can be stated non-recursviely.

Let us understand about these parts through an example,

int fact(int n) {

    if(n==1)                // - (i)

        return 1;

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

}

In the above program, a function fact() has been described which calculates the factorial of a given number. Here line -(i) is the base case where as line -(ii) is the general case.

Typically to solve a problem using recursion, we often try to break the problem statement in terms of smaller version/ inputs of the given statement and think of a base case for which the solution can be calculated easily.


Note : If the base case is not defined or not reached then a stack overflow error/ problem arises.


Example :

int fact(int n) {

    return n*fact(n-1);

}

The above function will never terminate and hence a stack overflow error occurs.


Memory Allocation to Different Function Calls

Whenever a function is called from main(), a portion of memory is allocated to it on the memory stack. So following the same pattern, whenever a recursive function calls itself a portion of the memory stack is allocated to that particular call on top of the previous call. This process continues until the base case is reached, after which the function calls are popped from the stack in a Last-In-First-Out (LIFO) manner.

For example, the call stack for fact(4) will be,


Note : Stack overflow error also occurs when a lot of function calls/ data are being pushed onto the stack, so that the total calls exceed the memory/ capacity of the stack.


Comparison with Iterative Method

The fact that every recursive solution has an iterative counterpart makes them direct candidates for comparison.

Example :

int fact(int n) {

    int res=1;

    for(int i=1;i<=n;i++)

    res=res*i;

    return res;

}

In the above code, fact() function described earlier is written in an iterative fashion.

Advantages of Recursion over Iteration

Recursive programs are often clean and easy to read and understand.

Disadvantages of Recursion over Iteration

·       Recursion requires higher space requirements as all the function calls remain in the memory stack until the base case is reached.

·       Recursion programs are slow, with respect to time, compared to their iterative counterparts due to all the function calls and returns overhead.


Recursion is a programming concept that is not only limited to C and expands to every programming language. Using recursion is one of the many ways to efficiently use computational powers to do difficult tasks and problems.


Thanks for reading.

Also See : Function, main() Function 

Monday, June 22, 2020

Gentle Introduction to C : Call by Value and Reference

Originally Posted on SeedBx


Welcome to the fourth part of the Gentle Introduction to C series. As said before this series aims to provide you a brief introduction to C language.

In this part we will be looking at call by value and call by reference.


Before talking about call by value and call by reference let’s get some more terminologies under our belt.

Function Call : It is a request made by the program by using the function name and a list of parameters (if any) enclosed in braces.

Formal Parameters :  These are the parameters which are defined in the function.

Actual Parameters : These are the parameters that the caller location passes to the function.

Interesting Fact : C is case-sensitive

 

Call By Value

Call by Value is a function calling technique in which the formal parameters and actual parameters are different independent variables, more so the formal parameters are separate variables which share the same value. Internally what happens is when a function is called by value the values of the actual parameters are copied to the formal parameters (dummy variables). As the formal parameters and actual parameters are different, any changes made to formal parameters are not reflected in actual parameters.

Example-

    Code :

    #include<stdio.h>
    void callByValue(int a)
    {
        a=3;
        printf("Value of Formal Parameter = %d\n", a);
    }
    int main()
    {
        int a;
        a=2;
        callByValue(a);
        printf("Value of Actual Parameter = %d", a);
        return 0;
    }

    Output :

        Value of Formal Parameter = 3
        Value of Actual Parameter = 2

As you can notice above, the value of 'a' in the main() function is not affected by the change in the value of 'a' in callByValue() function.

 

Call By Reference

Call by reference is a function calling technique in which the formal parameters and actual parameters are actually identical variables, i.e. they share the same memory location internally. Call by reference can be initiated by passing either pointers to the variable or passing reference to the variable. As the formal and actual parameter share the same memory location, any changes to the formal parameters is actually reflected in the actual parameters.

Example-

    Code :

    #include<stdio.h>
    void callByReference(int &a)
    {
        a=3;
        printf("Value of Formal Parameter = %d\n", a);
    }
    int main()
    {
        int a;
        a=2;
        callByReference(a);
        printf("Value of Actual Parameter = %d", a);
        return 0;
    }

    Output :

        Value of Formal Parameter = 3
        Value of Actual Parameter = 3

 

As you can notice above, the value of 'a' in the main() function is affected by the change in the value of 'a' in callByReference() function.

Both of these function calling techniques have their fair share of uses in actual applications, however the calling technique to be used totally depends on the use case.

 

As always your suggestions are welcome. 

Do comment out what are some interesting ways in which you use these calling techniques.

 

Wednesday, June 17, 2020

Gentle Introduction to C : main() Function

Originally Posted on SeedBx


Welcome to the third part of the Gentle Introduction to C series. As said before this series aims to provide you with a brief introduction to C language.

In this part we are going to look at one of the most important function in C, the main() function.

 

main()

The main() function, as many like to say, is the entry point of a C program. It is the function that is executed at the beginning of any program. Intuitively you can also understand the main() function as an user-defined function.

 

Note : Technically the main function is not the actual entry point as the entry point is compiler depended.

 

At the basic level, the main() function is similar to a normal function, having its own return value, parameters and definition. But unlike any other function, the main function is called by the operating system ( all other functions are actually called by the main function or any other function). This happens primarily because whenever a program runs, the operating system has to pass the control of the computer over to the program. The main() function is just what the operating system looks for in a C program to pass its control to. So technically if any parameter that’s needed to be passed on to the main() function must be passed during runtime. Also as the main() function is the part that receives the operating system’s control it is required to be present in the program (some exceptions do occur).

 

Interesting Fact : Despite its importance, main is not a keyword in C.

 

Example -

      Code :

    #include<stdio.h>

    // Defining a main function with int return type

    int main()

    {

        printf("Hello you are in the main function");

        return 0;

     }

      Output : 

     Hello you are in the main function

 

Lastly main() function is an important component of almost every C program and writing a good main() function is a very crucial and important step.

 

Thanks for reading. 

As always your valuable comments and suggestions are welcome.

Also See : Function, Call by Value and Reference, Recursion

 

Saturday, June 13, 2020

Gentle Introduction to C : Function

Originally Posted on SeedBx


Welcome to the second part of the Gentle Introduction to C series. As said before this series aims to provide you a brief introduction to C language.

In this part we will look into the one of the basic components of C, namely functions and how using it can improve your programming experience.

Function

Function is a block of statements that performs a specific functionality. Mainly its aim is to divide a complex routine in hand to simpler subroutines which can then be later combined to perform the more complex routine.

There are basically two types of function :

  1. Standard-library functions
  2. User-defined functions

We will delve more into these types at a later part, but for now you can intuitively understand them as predefined and as the name suggests user-defined functions respectively.

Interesting Fact : C is the only programming language to have not lost its popularity even after such a long duration.


Given below are some basic components related to functions.

Common Terminologies

Function Name : It is the name/identity of the function which is used to call the function.

Parameters/Arguments : It is the list of data items (variables, pointers, references etc.) that the function take as input in its block of statements to either do computation on it or to facilitate the computation. The number of parameters can be any finite integer (possibly zero). The process of passing the parameters can be done in two ways : by value or by reference.

 Function Declaration : It is an introductory statement which is used to inform the compiler of the number of the parameters and the type of each individual parameter associated with the given function name. It also specifies about the type ( int, char, float, double, void)  of the return value of the function.

Function Definition : It is a sequence of statements that define the functionality of the function along with all details such as the names of parameter variables. It starts with a statement like a function declaration (except that it is now also compulsory to provide with parameter's name)  and followed by curly braces which contain the function in itself.

Return Value : The return value is a data item (possibly void) that the functions returns to the caller. The value is returned using the return keyword

Example : Let us consider a function add which will return the sum of the two parameters.

    int add(int,int);   ---------------------> Function Declaration

    /* some code */

    int add(int num1,int num2)  -------------> Function Definition

    {

        int sum;

        sum = num1 + num2;

        return sum;

    }

Note :

1.     The use of function declaration can be skipped if the function definition comes before the statement(s) in which it is called. However it is a good practice to include function declaration (and is a must when the calling statement(s) precedes the function definition).

2.     The return statement is optional in case of void return type.

3.     The parameters should be separated by commas.

4.      It is not necessary to provide with parameter name in the function declaration.

So you may be wondering why will you ever use a function in the first place. However there are following advantages which you shouldn't overlook :

1.     It improves readability and makes the code look cleaner.

2.     This saves you from writing a block of code multiple times

Although for now you might be wondering these advantages are not at all significant but as you will start designing bigger and complex code these advantages of functions will save you a lot of time while debugging. Also as C is a relatively low level programming language in comparison to C++ or python, functions becomes a powerful tool to do low level stuff like memory management etc.

 

There is still more to be said about functions but I will keep them for different parts.

 

Side Note : 

People also often classify functions on the basis of arguments and return type.

1.     Functions with no arguments and no return type.

2.     Functions with arguments and no return type.

3.     Functions with no arguments and return type.

4.     Functions with arguments and a return type.

 

Do write in comments what other advantages you see of using functions.

Your suggestions as always are welcome.