Functions in C Programming

In this tutorial I will explain  you the functions in C.

Basics Of Function

This is our basic code structure :

#include <stdio.h>

int main()
{
    /* code */
    return 0;
}

Now if I want to ask a user input for five times and print it back then the code will be as follows :

PS C:\C> .\a.exe   
Enter no : 3
You entered 3
Enter no : 53
You entered 53
Enter no : 12 
You entered 12
Enter no : 53 
You entered 53
Enter no : 23
You entered 23
PS C:\C>

Then the code will be :

#include <stdio.h>

int main()
{
    int no;

    printf("Enter no : ");
    scanf("%d", &no);
    printf("You entered %d\n", no);

    printf("Enter no : ");
    scanf("%d", &no);
    printf("You entered %d\n", no);

    printf("Enter no : ");
    scanf("%d", &no);
    printf("You entered %d\n", no);

    printf("Enter no : ");
    scanf("%d", &no);
    printf("You entered %d\n", no);

    printf("Enter no : ");
    scanf("%d", &no);
    printf("You entered %d\n", no);

    return 0;
}

 

But I have an alternative. I will create a function. Here is an example of function :

void get_no()
{
    printf("Enter no : ");
    scanf("%d", &no);
    printf("You entered %d\n\n", no);
}

This code will ask the number and print it back to the user when executed. Now to execute it we will modify the code like this :

#include <stdio.h>

void get_no()
{
    printf("Enter no : ");
    scanf("%d", &no);
    printf("You entered %d\n\n", no);
}

int main()
{
    get_no();
    return 0;
}

In main function we have called/executed out function.

Arguments Of Functions

Functions too take arguments in C. For example I want to print

  1. Enter no 1 :
  2. Enter no 2 :
  3. Enter no 3 :
  4. Enter no 4 :
  5. Enter no 5 :

Then I can modify the code like this :

#include <stdio.h>

void get_no(int no)
{
    printf("Enter no %d : ", no);
    scanf("%d", &no);
    printf("You entered %d\n\n", no);
}

int main()
{
    get_no(1);
    get_no(2);
    get_no(3);
    get_no(4);
    get_no(5);
    return 0;
}

We have entered ‘int no‘ in the two round brackets of declaration of our function.

Now to execute in we need to put the argument. Here i have put 1,2,3,4,5 an the arguments.

Leave a Comment