DEFINTION OF A FUNCTION

A function  is a self- contained block of executable code that can be called from any other function. In many programs, a set 0f statements are to be executed repeatedly at various places in  the program and may with different sets of data, the idea of functions  comes in mind. You keep those repeating statements in a function and call them as  and when required .When a function is called, the control transfers to the called function, which will  be executed, and then transfers the control back to the calling function.
Example
 Program to illustrate a function

#include <stdio.h>

main()

{
 void sample( );
  printf("/n You are in main");
}
vold sample( )
{
pirintf ("\n You are in sample");
 }


OUTPUT 
You are in sample
 You are in main

 Here we are calling a function sample ( ) through main( ) i.e. control of execution transfers from main( ) to sample( ) , which means main( ) is suspended for some time and sample() is executed. After its execution the control returns back to main( ), at the statement following function call and the execution of main( ) is resumed.


The syntax of a function is:
return data type function_name (list of arguments)
{
datatype declaration of the arguments;
executable statements;
 return (expression);
}
where,
1) return data type is the same as the data type of the variable that is returned by the function using return statement.
2) a function_name is formed in the same way as variable names identifiers are formed.
3)the list of arguments or parameters are valid variable names as shown below. separated by commas: (data type1 var I .data type2 var2,  data type n var n)
 for example (int x, float y, char z).
4)arguments give the values which are passed from the calling function.
5)the body of function contains executable statements.
6)the return statement returns a single value to the calling function .

Example

Let us write a simple function that calculates the square of an integer .
/* Program to calculate the square of given integer*/

/* square( ) function */
 {
int square (int no)
 int result ;
 result=no*no;
 return (result);
}

main(){
 int n .sq;
printf(Enter a number to calculate square value");
scanf("%d",&n);
sq=square(n);
printf("\n square of the number is : %d",sq) ;
}

OUTPUT
Enter a number to calculate square value 5
 Square of the number is : 25


0 comments:

Post a Comment