Functions

In programming, set of statements that solves a particular task is called function or module.

Every C program should have at least one function that is main function.


Example

Write a function to check whether a given number is positive or negative.


Example

void check(int num)
{
    if(num == 0)
        printf("Neither positive nor negative\n");
    else if(num > 0)
        printf("Positive\n");
    else
        printf("Negative\n");
}

where,

void - return type of a function

check - function name

int num - function parameter. We can give many parameters.

Statements between two curly braces {..} - function body

We will discuss more about above topics in upcoming tutorials.




Why do we need functions?

1.Improve Modularity

We can divide a large program into multiple small modules.

If we write programs using modules, it very easy to understand the program.

And it's also easy to debug (say, which part doesn't work properly) the program.

2.Code Reusability

Lets take an example,

Get two integer from user and check whether the two numbers are positive or negative.

Program without functions

Example

#include<stdio.h>

int main()
{
    int num;

    //for first number
    scanf("%d",&num);

    if(num == 0)
        printf("Neither positive nor negative\n");
    else if(num > 0)
        printf("Positive\n");
    else
        printf("Negative\n");

    //for second number
    scanf("%d",&num);

    if(num == 0)
        printf("Neither positive nor negative\n");
    else if(num > 0)
        printf("Positive\n");
    else
        printf("Negative\n");

    return 0;
}

Here, we are writing the same piece of code again and again.

This is not a good program practice!

Lets rewrite it with functions.

Program with function

Example

#include<stdio.h>

void check(int num)
{
    if(num == 0)
        printf("Neither positive nor negative\n");
    else if(num > 0)
        printf("Positive\n");
    else
        printf("Negative\n");
}

int main()
{
    int num;

    //for first number
    scanf("%d",&num);
    check(num);

    //for second number
    scanf("%d",&num);
    check(num);

    return 0;
}

Here, we wrote a logic one time and re-using it wherever it needed again.

This is how function improves code re-usability in programming.