Back to Study material
PPS


UNIT 4


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 procedure or sub routine in other programming languages.

Advantage of functions in C

There are the following advantages of C functions.

  • By using functions, we can avoid rewriting same logic/code again and again in a program.
  • We can call C functions any number of times in a program and from any place in a program.
  • We can track a large C program easily when it is divided into multiple functions.
  • Reusability is the main achievement of C functions.
  • However, Function calling is always a overhead in a C program.

Function Aspects

There are three aspects of a C function.

  • Function declarationA function must be declared globally in a c program to tell the compiler about the function name, function parameters, and return type.

 

  • Function call Function can be called from anywhere in the program. The parameter list must not differ in function calling and function declaration. We must pass the same number of functions as it is declared in the function declaration.

 

  • Function definitionIt contains the actual statements which are to be executed. It is the most important aspect to which the control comes when the function is called. Here, we must notice that only one value can be returned from the function.

 

SN

C function aspects

Syntax

1

Function declaration

Return_typefunction_name (argument list);

2

Function call

Function_name (argument_list)

3

Function definition

Return_typefunction_name (argument list) {function body;}

The syntax of creating function in c language is given below:

  1. Return_type function_name(data_type parameter...){  
  2. //code to be executed  
  3. }  

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

Return Value

A C function may or may not return a value from the function. If you don't have to return any value from the function, use void for the return type.

Let's see a simple example of C function that doesn't return any value from the function.

Example without return value:

  1. Void hello(){  
  2. Printf("hello c");  
  3. }  

If you want to return any value from the function, you need to use any data type such as int, long, char, etc. The return type depends on the value to be returned from the function.

Let's see a simple example of C function that returns int value from the function.

Example with return value:

  1. Int get(){  
  2. Return 10;  
  3. }  

In the above example, we have to return 10 as a value, so the return type is int. If you want to return floating-point value (e.g., 10.2, 3.1, 54.5, etc), you need to use float as the return type of the method.

  1. Float get(){  
  2. Return 10.2;  
  3. }  

Now, you need to call the function, to get the value of the function.

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

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:

 

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

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

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

SN

Header file

Description

1

Stdio.h

This is a standard input/output header file. It contains all the library functions regarding 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.

 


There are two methods to pass the data into the function in C language, i.e., call by value and call by reference.

call by value and call by reference in c

Let's understand call by value and call by reference in c language one by one.

Call by value in C

  • In call by value method, the value of the actual parameters is copied into the formal parameters. In other words, we can say that the value of the variable is used in the function call in the call by value method.
  • In call by value method, we can not modify the value of the actual parameter by the formal parameter.
  • In call by value, different memory is allocated for actual and formal parameters since the value of the actual parameter is copied into the formal parameter.
  • The actual parameter is the argument which is used in the function call whereas formal parameter is the argument which is used in the function definition.

Let's try to understand the concept of call by value in c language by the example given below:

  1. #include<stdio.h>  
  2. Void change(int num) {    
  3.    Printf("Before adding value inside function num=%d \n",num);    
  4.    Num=num+100;    
  5.    Printf("After adding value inside function num=%d \n", num);    
  6. }    
  7. Int main() {    
  8.    Int x=100;    
  9.    Printf("Before function call x=%d \n", x);    
  10.    Change(x);//passing value in function    
  11.    Printf("After function call x=%d \n", x);    
  12. Return 0;  
  13. }    

Output

Before function call x=100

Before adding value inside function num=100

After adding value inside function num=200

After function call x=100

Call by Value Example: Swapping the values of the two variables

  1. #include <stdio.h>  
  2. Void swap(int , int); //prototype of the function   
  3. Int main()  
  4. {  
  5.    Int a = 10;  
  6.    Int b = 20;   
  7.    Printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main  
  8.    Swap(a,b);  
  9.    Printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual parameters do not change by changing the formal parameters in call by value, a = 10, b = 20  
  10. }  
  11. Void swap (int a, int b)  
  12. {  
  13.    Int temp;   
  14.    Temp = a;  
  15.    a=b;  
  16.    b=temp;  
  17.    Printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameters, a = 20, b = 10   
  18. }  

Output

Before swapping the values in main a = 10, b = 20

After swapping values in function a = 20, b = 10

After swapping values in main a = 10, b = 20 

Call by reference in C

  • In call by reference, the address of the variable is passed into the function call as the actual parameter.
  • The value of the actual parameters can be modified by changing the formal parameters since the address of the actual parameters is passed.
  • In call by reference, the memory allocation is similar for both formal parameters and actual parameters. All the operations in the function are performed on the value stored at the address of the actual parameters, and the modified value gets stored at the same address.

Consider the following example for the call by reference.

  1. #include<stdio.h>  
  2. Void change(int *num) {    
  3.    Printf("Before adding value inside function num=%d \n",*num);    
  4.    (*num) += 100;    
  5.    Printf("After adding value inside function num=%d \n", *num);    
  6. }      
  7. Int main() {    
  8.    Int x=100;    
  9.    Printf("Before function call x=%d \n", x);    
  10.    Change(&x);//passing reference in function    
  11.    Printf("After function call x=%d \n", x);    
  12. Return 0;  
  13. }    

Output

Before function call x=100

Before adding value inside function num=100

After adding value inside function num=200

After function call x=200

Call by reference Example: Swapping the values of the two variables

  1. #include <stdio.h>  
  2. Void swap(int *, int *); //prototype of the function   
  3. Int main()  
  4. {  
  5.    Int a = 10;  
  6.    Int b = 20;   
  7.    Printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the value of a and b in main  
  8.    Swap(&a,&b);  
  9.    Printf("After swapping values in main a = %d, b = %d\n",a,b); // The values of actual parameters do change in call by reference, a = 10, b = 20  
  10. }  
  11. Void swap (int *a, int *b)  
  12. {  
  13.    Int temp;   
  14.    Temp = *a;  
  15.    *a=*b;  
  16.    *b=temp;  
  17.    Printf("After swapping values in function a = %d, b = %d\n",*a,*b); // Formal parameters, a = 20, b = 10   
  18. }  

Output

Before swapping the values in main a = 10, b = 20

After swapping values in function a = 20, b = 10

After swapping values in main a = 20, b = 10 

Difference between call by value and call by reference in c

No.

Call by value

Call by reference

1

A copy of the value is passed into the function

An address of value is passed into the function

2

Changes made inside the function is limited to the function only. The values of the actual parameters do not change by changing the formal parameters.

Changes made inside the function validate outside of the function also. The values of the actual parameters do change by changing the formal parameters.

3

Actual and formal arguments are created at the different memory location

Actual and formal arguments are created at the same memory location

 

Text Books

(i) Byron Gottfried, Schaum's Outline of Programming with C, McGraw-Hill

(ii) E. Balaguruswamy, Programming in ANSI C, Tata McGraw-Hill

Reference Books

(i) Brian W. Kernighan and Dennis M. Ritchie, The C Programming Language, Prentice Hall of India.

 


Index
Notes
Highlighted
Underlined
:
Browse by Topics
:
Notes
Highlighted
Underlined