as

Wednesday 12 November 2014

Functions In C


Functions are a block of statements which can be reused.
As shown in below image, each function takes input, does the processing on that input and then produces the output.

Uses of C functions

  •          C functions are used to avoid rewriting same logic/code again and again in a program.
  •          There is no limit in calling C functions to make use of same functionality wherever required.
  •          We can call functions any number of times in a program and from any place in a program.
  •          A large C program can easily be tracked when it is divided into functions.
  •          The core concept of C functions is re-usability and dividing a big task into small pieces.

Built in VS user defined

There are 2 types of functions.
  1.       Built-in functions.
  2.       User Defined functions.

Built-in functions are defined in the standard c library while user defined functions are created by user.

For example –

printf is a built-in function that can be used to print the data to standard output console.
We will see how to define the user defined functions in next 2 sections.

Function Declaration

Each function takes input and produces output.
Input can be of any data type.

Example –

int sum (int a, int b)

In above statement, we have declared function with name sum which takes input in the form of 2 arguments a and b of type int and returns the output in the form of integer type.

Function definition:

Sample example on function is given below. We have defined one function with name add
Add function takes 2 inputs p1 and p2 and returns one variable with int data type.


#include<stdio.h>               

int add( int p1,int p2 );

void main()
{
   int a=10;
   int b=20, c;
   //we are calling add function here
   //a and b are actual arguments
   c = add( a, b );
   printf("sum of a and b is %d \n", c);
}

int add( int p1,int p2 )
{
    int t;
    t=p1+p2;
    return t;
}


 


No comments:

Post a Comment

Leave your valuable feedback. Your thoughts do matter to us.

Sponsored Links

Popular Posts

Comments

ShareThis