0% found this document useful (0 votes)
578 views

UNIT III Functions

The document discusses different aspects of functions in C including function prototypes, definitions, calls, parameter passing methods, return statements, and recursion. It provides examples of functions without and with arguments and return values and explains recursion as a process where a function calls itself.

Uploaded by

Sivasathiya G
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
578 views

UNIT III Functions

The document discusses different aspects of functions in C including function prototypes, definitions, calls, parameter passing methods, return statements, and recursion. It provides examples of functions without and with arguments and return values and explains recursion as a process where a function calls itself.

Uploaded by

Sivasathiya G
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

EASWARI ENGINEERING COLLEGE

(AUTONOMOUS)
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND
DATA SCIENCE

191GES204T – PROGRAMMING IN C

Unit III –Notes

(Functions in C)

PREPARED BY APPROVED BY

G.SIVASATHIYA, AP/AIADS HOD/AIADS


Functions: Introduction - Function prototype - function definition -function
call – Return statement - Recursion. Parameter passing: Pass by value - Pass
by reference.

FUNCTIONS: INTRODUCTION

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 subroutine 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: FUNCTION PROTOTYPE - FUNCTION DEFINITION -


FUNCTION CALL

A function prototype in C is a function declaration specifying the function's


return type, name, and the number and types of its parameters. It acts as a contract
between the function definition and its callers, providing information about the
expected inputs and outputs of the function.

.
The three aspects of a C function are :

 Function declaration A 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 definition It 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_type function_name (argument


list);

2 Function call function_name (argument_list)

3 Function definition return_type function_name (argument list)


{function body;}

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

return_type function_name(data_type parameter...)


{
//code to be executed
}

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

Function without argument and without return value


#include<stdio.h>
void sum();
void main()
{
printf("\nGoing to calculate the sum of two numbers:");
sum();
}
void sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
printf("The sum is %d",a+b);
}

Output
Going to calculate the sum of two numbers:

Enter two numbers 10


24

The sum is 34

Function without argument and with return value

Example – 1 : Addition of two numbers

#include<stdio.h>
int sum();
void main()
{
int result;
printf("\nGoing to calculate the sum of two numbers:");
result = sum();
printf("%d",result);
}
int sum()
{
int a,b;
printf("\nEnter two numbers");
scanf("%d %d",&a,&b);
return a+b;
}

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


#include<stdio.h>
int sum();
void main()
{
printf("Going to calculate the area of the square\n");
float area = square();
printf("The area of the square: %f\n",area);
}
int square()
{
float side;
printf("Enter the length of the side in meters: ");
scanf("%f",&side);
return side * side;
}

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

Function with argument and without return value

Example – 1 : Addition of two numbers

#include<stdio.h>
void sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
sum(a,b);
}
void sum(int a, int b)
{
printf("\nThe sum is %d",a+b);
}

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.

#include<stdio.h>
void average(int, int, int, int, int);
void main()
{
int a,b,c,d,e;
printf("\nGoing to calculate the average of five numbers:");
printf("\nEnter five numbers:");
scanf("%d %d %d %d %d",&a,&b,&c,&d,&e);
average(a,b,c,d,e);
}
void average(int a, int b, int c, int d, int e)
{
float avg;
avg = (a+b+c+d+e)/5;
printf("The average of given five numbers : %f",avg);
}

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
Function with argument and with return value

Example 1 - Addition of two numbers

#include<stdio.h>
int sum(int, int);
void main()
{
int a,b,result;
printf("\nGoing to calculate the sum of two numbers:");
printf("\nEnter two numbers:");
scanf("%d %d",&a,&b);
result = sum(a,b);
printf("\nThe sum is : %d",result);
}
int sum(int a, int b)
{
return a+b;
}

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

#include<stdio.h>
int even_odd(int);
void main()
{
int n,flag=0;
printf("\nGoing to check whether a number is even or odd");
printf("\nEnter the number: ");
scanf("%d",&n);
flag = even_odd(n);
if(flag == 0)
{
printf("\nThe number is odd");
}
else
{
printf("\nThe number is even");
}
}
int even_odd(int n)
{
if(n%2 == 0)
{
return 1;
}
else
{
return 0;
}
}

Output

Going to check whether a number is even or odd


Enter the number: 100
The number is even

RETURN STATEMENT

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:

void hello(){
printf("hello c");
}
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:

int get(){
return 10;
}

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.

RECURSION

Recursion is the process which comes into existence when a function calls a copy of
itself to work on a smaller problem. Any function which calls itself is called recursive
function, and such function calls are called recursive calls.

Recursion involves several numbers of recursive calls. However, it is important to


impose a termination condition of recursion. Recursion code is shorter than iterative code
however it is difficult to understand.

Recursion cannot be applied to all the problem, but it is more useful for the tasks
that can be defined in terms of similar subtasks. For Example, recursion may be applied to
sorting, searching, and traversal problems.

Generally, iterative solutions are more efficient than recursion since function call is
always overhead. Any problem that can be solved recursively, can also be solved iteratively.
However, some problems are best suited to be solved by the recursion, for example, tower of
Hanoi, Fibonacci series, factorial finding, etc.

In the following example, recursion is used to calculate the factorial of a number.

#include <stdio.h>
int fact (int);
int main()
{
int n,f;
printf("Enter the number whose factorial you want to calculate?");
scanf("%d",&n);
f = fact(n);
printf("factorial = %d",f);
}
int fact(int n)
{
if (n==0)
{
return 0;
}
else if ( n == 1)
{
return 1;
}
else
{
return n*fact(n-1);
}
}

Output
Enter the number whose factorial you want to calculate?5
factorial = 120

We can understand the above program of the recursive method call by the figure given
below:
Recursive Function

A recursive function performs the tasks by dividing it into the subtasks. There is a
termination condition defined in the function which is satisfied by some specific subtask.
After this, the recursion stops and the final result is returned from the function.

The case at which the function doesn't recur is called the base case whereas the instances
where the function keeps calling itself to perform a subtask, is called the recursive case. All
the recursive functions can be written using this format.

Pseudocode for writing any recursive function is given below.

if (test_for_base)
{
return some_value;
}
else if (test_for_another_base)
{
return some_another_value;
}
else
{
// Statements;
recursive call;
}

In the following example, recursion is used to calculate the Fibonacci series

#include<stdio.h>
int fibonacci(int);
void main ()
{
int n,f;
printf("Enter the value of n?");
scanf("%d",&n);
f = fibonacci(n);
printf("%d",f);
}
int fibonacci (int n)
{
if (n==0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return fibonacci(n-1)+fibonacci(n-2);
}
}

Output
Enter the value of n?12
144

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

CALL BY / PASS BY VALUE AND CALL BY/ PASS BY REFERENCE IN C

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

Call by Value Example: Adding the number


#include<stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
return 0;
}

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
#include <stdio.h>
void swap(int , int); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b); // printing the val
ue of a and b in main
swap(a,b);
printf("After swapping values in main a = %d, b = %d\n",a,b); // The value of actual p
arameters do not change by changing the formal parameters in call by value, a = 10, b =
20
}
void swap (int a, int b)
{
int temp;
temp = a;
a=b;
b=temp;
printf("After swapping values in function a = %d, b = %d\n",a,b); // Formal parameter
s, a = 20, b = 10
}

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 addition example for call by reference.

#include<stdio.h>
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
return 0;
}

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


#include <stdio.h>
void swap(int *, int *); //prototype of the function
int main()
{
int a = 10;
int b = 20;
printf("Before swapping the values in main a = %d, b = %d\n",a,b);
// printing the value of a and b in main
swap(&a,&b);
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
}
void swap (int *a, int *b)
{
int temp;
temp = *a;
*a=*b;
*b=temp;
printf("After swapping values in function a = %d, b = %d\n",*a,*b);
// Formal parameters, a = 20, b = 10
}

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 An address of value is passed into the
function function

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

3 Actual and formal arguments are Actual and formal arguments are
created at the different memory created at the same memory location
location

You might also like