Ask a Teacher



Define a user-defined function that can accept two numbers on calling and return the sum of their squares, (For example, if 2 and 3 are passed to the function, it should return 13, which is obtained by 22 + 32).

C allows programmer to define their own function according to their requirement. These types of functions are known as user-defined functions. Suppose, a programmer wants to find factorial of a number and check whether it is prime or not in same program. Then, he/she can create two separate user-defined functions in that program: one for finding factorial and other for checking whether it is prime or not.

#include <stdio.h>
void function_name(){
................
................
}
int main(){
...........
...........
function_name();
...........
...........
}


As mentioned earlier, every C program begins from main() and program starts executing the codes inside main() function. When the control of program reaches to function_name() inside main() function. The control of program jumps to void function_name() and executes the codes inside it. When all the codes inside that user-defined function are executed, control of the program jumps to the statement just after function_name() from where it is called. Analyze the figure below for understanding the concept of function in C programming. 


Advantages of user defined functions

User defined functions helps to decompose the large program into small segments which makes programmar easy to understand, maintain and debug.
If repeated code occurs in a program. Function can be used to include those codes and execute when needed by calling that function.
Programmer working on large project can divide the workload by making different functions.


Example of user-defined function


/*Program to demonstrate the working of user defined function*/
#include <stdio.h>
int add(int a, int b);           //function prototype(declaration)
int main(){
     int num1,num2,sum;
     printf("Enters two number to add\n");
     scanf("%d %d",&num1,&num2);
     sum=add(num1,num2);         //function call 
     printf("sum=%d",sum); 
     return 0;
}
int add(int a,int b)            //function declarator
{             
/* Start of function definition. */
     int add;
     add=a+b;
     return add;                  //return statement of function 
/* End of function definition. */   
}  


comments powered by Disqus