C Functions

In c, we can divide a large program into the basic building blocks known as function. The function contains the set of programming statements enclosed by {}. A function can be called multiple times to provide reusability and modularity to the C program. In other words, we can say that the collection of functions creates a program. The function is also known as procedureor subroutinein other programming languages.


Types of Functions

There are two types of functions in C programming:

  1. Library Functions: are the functions which are declared in the C header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc.
  2. User-defined functions: are the functions which are created by the C programmer, so that he/she can use it many times. It reduces the complexity of a big program and optimizes the code.

C Function

Example for Function without argument and with return value

Example 1

  1. #include<stdio.h>  
  2. int sum();  
  3. void main()  
  4. {  
  5.     int result;   
  6.     printf("\nGoing to calculate the sum of two numbers:");  
  7.     result = sum();  
  8.     printf("%d",result);  
  9. }  
  10. int sum()  
  11. {  
  12.     int a,b;   
  13.     printf("\nEnter two numbers");  
  14.     scanf("%d %d",&a,&b);  
  15.     return a+b;   
  16. }  

Output:-

Going to calculate the sum of two numbers:

Enter two numbers 10 
24 

The sum is 34

Example 2: program to calculate the area of the square

  1. #include<stdio.h>  
  2. int sum();  
  3. void main()  
  4. {  
  5.     printf("Going to calculate the area of the square\n");  
  6.     float area = square();  
  7.     printf("The area of the square: %f\n",area);  
  8. }  
  9. int square()  
  10. {  
  11.     float side;  
  12.     printf("Enter the length of the side in meters: ");  
  13.     scanf("%f",&side);  
  14.     return side * side;  
  15. }  

Output

Going to calculate the area of the square 
Enter the length of the side in meters: 10 
The area of the square: 100.000000