User Defined Function in C Language
As functions are sub part of the program in any language, those can be called at any point in your main execution. Before going a head we should focus on some words related to function.
Return Type : Return type in function is the data type of return value (final answer of function). Return type in function may be any primitive data type like int,float,double, char or user defined data type like Structure, Union or Derived Data Type like array. But if your function is returning nothing then void is used as return type. Some of the examples :
int add(int x,int y)
{
int z;
z=x+y;
return z;
}
Here return value is addition of two integers so obviously return type is int here.
float average(int x,int y)
{
float avg= (x+y)/2.0;
return avg;
}
In above function we are getting average of two numbers, so return type is float.
void showSquare(int x)
{
int z=x*x;
printf("Square is :%d",z);
}
void showline()
{
printf("\n======================================");
}
In above two examples, we are not returning anything. These functions are used for processing (procedures) so that void is used as return type. When any function encounter return statement then it is the exit point of the function. Means no more than one return statement can be executed in a single call.
Parameter : Parameters are the variables those are passed with function call. Means Input to the functions. Para
int add(int x,int y)
{
return x+y;
}
In above example x and y are parameters. Parameters could be in any numbers of may be zero (no-parameter function). They can be of any data type (do not concern with return type).
Now we will explain an full example in C Language for a function to find factorial of given number.
#include<stdio.h>
#include<conio.h>
long fact(int n) //long is return type and int n is parameter
{
int i;
long ans=1;
for(i=1;i<=n;i++)
{
ans= ans * i;
}
return ans;
}
void main()
{
int n;
long f;
clrscr();
printf("\nEnter a Number");
scanf("%d",&n);
f=fact(n); // function calling with argument n
printf("\nFactorial is %ld",f);
getch();
}
Here fact() is a function, long is return type, int n is parameter.