C Functions Explanation

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 11

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.

C functions can be classified into two categories,

1. Library functions
2. User-defined functions

Library functions are those functions which are already defined in C library, example printf(), scanf(),
strcat() etc. You just need to include appropriate header files to use these functions. These are already
declared and defined in C libraries.

A User-defined functions on the other hand, are those functions which are defined by the user at the time of
writing program. These functions are made for code reusability and for saving time and space.

Benefits of Using Functions

1. It provides modularity to your program's structure.


2. It makes your code reusable. You just have to call the function by its name to use it, wherever
required.
3. In case of large programs with thousands of code lines, debugging and editing becomes easier if you
use functions.
4. It makes the program more readable and easy to understand.

Function Declaration
1
General syntax for function declaration is,

returntype functionName(type1 parameter1, type2 parameter2,...);

Like any variable or an array, a function must also be declared before its used. Function declaration informs
the compiler about the function name, parameters is accept, and its return type. The actual body of the
function can be defined separately. It's also called as Function Prototyping. Function declaration consists
of 4 parts.

 returntype
 function name
 parameter list
 terminating semicolon

returntype

When a function is declared to perform some sort of calculation or any operation and is expected to provide
with some result at the end, in such cases, a return statement is added at the end of function body. Return
type specifies the type of value(int, float, char, double) that function is expected to return to the program
which called the function.

Note: In case your function doesn't return any value, the return type would be void.

functionName

Function name is an identifier and it specifies the name of the function. The function name is any valid C
identifier and therefore must follow the same naming rules like other variables in C language.

parameter list

The parameter list declares the type and number of arguments that the function expects when it is called.
Also, the parameters in the parameter list receives the argument values when the function is called. They are
often referred as formal parameters.

Time for an Example

Let's write a simple program with a main() function, and a user defined function to multiply two numbers,
which will be called from the main() function.

#include<stdio.h>

int multiply(int a, int b); // function declaration

int main()
{
int i, j, result;

2
printf("Please enter 2 numbers you want to multiply...");
scanf("%d%d", &i, &j);

result = multiply(i, j); // function call


printf("The result of muliplication is: %d", result);

return 0;
}

int multiply(int a, int b)


{
return (a*b); // function defintion, this can be done in one line
}

Function definition Syntax

Just like in the example above, the general syntax of function definition is,

returntype functionName(type1 parameter1, type2 parameter2,...)


{
// function body goes here
}

The first line returntype functionName(type1 parameter1, type2 parameter2,...) is known as function
header and the statement(s) within curly braces is called function body.

Note: While defining a function, there is no semicolon(;) after the parenthesis in the function header, unlike
while declaring the function or calling the function.

functionbody

The function body contains the declarations and the statements(algorithm) necessary for performing the
required task. The body is enclosed within curly braces { ... } and consists of three parts.

 local variable declaration(if required).


 function statements to perform the task inside the function.
 a return statement to return the result evaluated by the function(if return type is void, then no return
statement is required).

Calling a function

When a function is called, control of the program gets transferred to the function.

functionName(argument1, argument2,...);

In the example above, the statement multiply(i, j); inside the main() function is function call.

Passing Arguments to a function

3
Arguments are the values specified during the function call, for which the formal parameters are declared
while defining the function.

It is possible to have a function with parameters but no return type. It is not necessary, that if a function
accepts parameter(s), it must return a result too.

While declaring the function, we have declared two parameters a and b of type int. Therefore, while calling
that function, we need to pass two arguments, else we will get compilation error. And the two arguments
passed should be received in the function definition, which means that the function header in the function
definition should have the two parameters to hold the argument values. These received arguments are also
known as formal parameters. The name of the variables while declaring, calling and defining a function
can be different.

Returning a value from function

4
A function may or may not return a result. But if it does, we must use the return statement to output the
result. return statement also ends the function execution, hence it must be the last statement of any
function. If you write any statement after the return statement, it won't be executed.

The datatype of the value returned using the return statement should be same as the return type mentioned
at function declaration and definition. If any of it mismatches, you will get compilation error.

In the next tutorial, we will learn about the different types of user defined functions in C language and the
concept of Nesting of functions which is used in recursion.

Different aspects of function calling


A function may or may not accept any argument. It may or may not return any value. Based on these facts,
There are four different aspects of function calls.

 function without arguments and without return value


 function without arguments and with return value
 function with arguments and without return value
 function with arguments and with return value

Example for Function without argument and return value

Example 1

1. #include<stdio.h>  
2. void printName();  
3. void main ()  
4. {  
5.     printf("Hello ");  
6.     printName();  
7. }  
8. void printName()  
5
9. {  
10.     printf("Javatpoint");  
11. }  

Output

Hello Javatpoint

Example 2

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

Output

Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

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. }  

6
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

Example for Function with argument and without return value

Example 1

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

Output

Going to calculate the sum of two numbers:


7
Enter two numbers 10
24

The sum is 34

Example 2: program to calculate the average of five numbers.

1. #include<stdio.h>  
2. void average(int, int, int, int, int);  
3. void main()  
4. {  
5.     int a,b,c,d,e;   
6.     printf("\nGoing to calculate the average of five numbers:");  
7.     printf("\nEnter five numbers:");  
8.     scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);  
9.     average(a,b,c,d,e);  
10. }  
11. void average(int a, int b, int c, int d, int e)  
12. {  
13.     float avg;   
14.     avg = (a+b+c+d+e)/5;   
15.     printf("The average of given five numbers : %f",avg);  
16. }  

Output

Going to calculate the average of five numbers:


Enter five numbers:10
20
30
40
50
The average of given five numbers : 30.000000

Example for Function with argument and with return value

Example 1

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

8
Output

Going to calculate the sum of two numbers:


Enter two numbers:10
20
The sum is : 30

Example 2: Program to check whether a number is even or odd

1. #include<stdio.h>  
2. int even_odd(int);  
3. void main()  
4. {  
5.  int n,flag=0;  
6.  printf("\nGoing to check whether a number is even or odd");  
7.  printf("\nEnter the number: ");  
8.  scanf("%d",&n);  
9.  flag = even_odd(n);  
10.  if(flag == 0)  
11.  {  
12.     printf("\nThe number is odd");  
13.  }  
14.  else   
15.  {  
16.     printf("\nThe number is even");  
17.  }  
18. }  
19. int even_odd(int n)  
20. {  
21.     if(n%2 == 0)  
22.     {  
23.         return 1;  
24.     }  
25.     else   
26.     {  
27.         return 0;  
28.     }  
29. }  

Output

Going to check whether a number is even or odd


Enter the number: 100
The number is even

C Library Functions
Library functions are the inbuilt function in C that are grouped and placed at a common place called
the library. Such functions are used to perform some specific operations. For example, printf is a library
function used to print on the console. The library functions are created by the designers of compilers. All C
standard library functions are defined inside the different header files saved with the extension .h. We need
to include these header files in our program to make use of the library functions defined in such header files.
9
For example, To use the library functions such as printf/scanf we need to include stdio.h in our program
which is a header file that contains all the library functions regarding standard input/output.

10
The list of mostly used header files is given in the following table.

Header
SN Description
file
This is a standard input/output header file. It contains all the library functions regarding
1 stdio.h
standard input/output.
2 conio.h This is a console input/output header file.
3 string.h It contains all string related library functions like gets(), puts(),etc.
4 stdlib.h This header file contains all the general library functions like malloc(), calloc(), exit(), etc.
5 math.h This header file contains all the math operations related functions like sqrt(), pow(), etc.
6 time.h This header file contains all the time-related functions.
7 ctype.h This header file contains all character handling functions.
8 stdarg.h Variable argument functions are defined in this header file.
9 signal.h All the signal handling functions are defined in this header file.
10 setjmp.h This file contains all the jump functions.
11 locale.h This file contains locale functions.
12 errno.h This file contains error handling functions.
13 assert.h This file contains diagnostics functions.

11

You might also like