Function


  • A function is a self contained block of statements that performs some task. Every C program can be thought as a collection these function . Using a function is something like calling a person to do some specific job for you.
    lets learn it by example,
    										
     #include<stdio.h>
    	  void quote();   //function prototype declaration
    	  void main(){
    		quote();    //function is called 
    		printf("\nThis line executes after quote function.");
    	  }
    	  void quote()   //This is called function definition
    	  {
    		printf("This line is inside quote function.\n");
    	  }
    										
    										

    output:

    										
    This line is inside quote function.
    This line executes after quote function.
    										
    										

Here, we have defined two functions namely , quote() and main() function . We have used the word quote at 3 positions . Lets get the meaning of each of them.

  • The first is function prototype and is written as
    void quote();
    This prototype indicates that quote() is a function which after completing its execution does not return anything . To represent does not return anything we use "void" keyword .
    It is necessary to define prototype of every function that we intend to use in our program .

  • At second is as function prototype.This is called function definition. Currently we have printf() only inside quote but we may use while() , for() , if , else as per need of the program.

  • in this program function quote is being called by main function.what do we mean when we say 'called' . by calling we mean control of the program passes quote(),and activity of main() function stops temporarily until the execution of quote completes.
  • Sometimes we need to do more operations by functions than to just print.In such circumstances We may pass values between functions and those values are called as "arguments". The values which is to be passed is written inside parenthesis. consider example of addition of two numbers using function :
  • 
    #include<stdio.h>
    	int addition(int,int); /*int denotes datatypes of arguments . the return type is int because it will return sum of two numbers which will be integer*/
    		void main(){	
    			int a=5;
    			int b=10;
    			int sum;
    			sum=addition(a,b);
    			printf("Addition of %d and %d is %d",a,b,sum);
    		}
    		int addition(int x,int y){
    		 int z=x+y;
    		 return (z); //returned value will be stored in sum variable
    		}
    
    

    Output:

    
    Addition of 5 and 15 is 15
    
    

  • Print Page