DEV Community

ritwin59
ritwin59

Posted on

User Defined Function In C

C programming language allows coders to define functions to perform special tasks. As functions are defined by users, they are called user-defined functions.

user-defined functions have contained the block of statements which are written by the user to perform a task

function has three related elements, in order to establish the function

Function declaration
function call
Function definition

EXAMPLE:
include
include
int sumNum(int x,int y); //function declaration
int main()
{
int i,j,sum;
printf("Please enter 2 numbers for find sum\n");
scanf("%d %d",&i,&j);
sum=sumNum(i,j); //function call
printf("The result of sum is :%d",sum);
getch();
return 0;
}
int sumNum(int x, int y)//function definition
{
int result;
result=x+y;
return result; //return statements
}

Declaration of the user-defined function.

A function declaration is a frame (prototype)of function that contains the function’s name, list of parameter and return type and ends with the semicolon. but it doesn’t,t contain the function body

Syntax

return_Type function_Name(parameter1,parameter2,......);

Example

int sum_Num(int x, int y,.........);

Calling a function

Syntax

function_Name(Argument list);

Example

sum_Num(argument_1, argument_2,.......);

Function Definition

The function definition is an expansion of function declaration. It contains codes in the body part of the function for execution program by the compiler – it contains the block of code for the special task

Syntax:

return_Type function_name(parameter_1, parameter_2,....){
//statements
//body of the function
}

Return statements:

Return statements terminate the execution of the function and return value to calling the function. Also, return statements control of the program control and moved to the calling function.

Syntax

return (expression);

Example

return (result);
return (x+y);

Example

include
include
int division(int x,int y); //function declaration or prototype
int main()
{
int i,j,div;
printf("Please enter 2 numbers for division\n");
scanf("%d%d",&i,&j);
div=division(i,j); //function call
printf("The result of division is :%d",div);
getch();
return 0;
}
int division(int i, int j)
{
int result;
result=i/j;
return result; //return statements
}

Top comments (0)