Unit 5
Unit 5
Prepared by:
1
Ms. Himani Parekh
Assistant professor,
Computer Engineering,
CGPIT, UTU
INTRODUCTION
A function is a block of statements that performs
a specific task.
Suppose you are building an application in C
language and in one of your program, you need to
perform a same task more than once. In such
case you have two options –
Use the same set of statements every time you want
to perform the task
Create a function to perform that task, and just call it
every time you need to perform that task.
Second option is a good practice and a good
programmer always uses functions while writing
codes in C. 2
TYPES OF FUNCTIONS
1) Predefined standard library functions – such as
puts(), gets(), printf(), scanf() etc – These are the
functions which already have a definition in header
files (.h files like stdio.h), so we just call them
whenever there is a need to use them.
2) User Defined functions – The functions that we
create in a program are known as user defined
functions.
3
NEED OF USER-DEFINED FUNCTIONS
1) To improve the readability of code.
2) Improves the reusability of the code, same function can be
used in any program rather than writing the same code
from scratch.
3) Debugging of the code would be easier if you use
functions, as errors are easy to be traced.
4) Reduces the size of the code, duplicate set of statements
are replaced by function calls.
4
ELEMENTS OF USER-DEFINED FUNCTIONS
Function definition
Function call
Function declaration
5
FUNCTION DEFINITION
The general form of a function definition in C
programming language is as follows:
.
EXAMPLE 1:
#include <stdio.h>
void f1() //definition
{
printf("HELLO\n");
printf("GOOD MORNING\n");
}
void main()
{
f1(); //calling
printf("WELCOME\n");
}
Output:
HELLO
GOOD MORNING 9
WELCOME
EXAMPLE 2:
/* function returning the max between two numbers */
int max(int num1,int num2)
{
/* local variable declaration */
int result;
if(num1 >num2)
result =num1;
else
result =num2;
return result; 10
}
FUNCTION DECLARATIONS
A function declaration tells the compiler about a
function name and how to call the function. The
actual body of the function can be defined
separately.
Syntax:
return_type function_name(parameter list );
11
For the above defined function max() in EXAMPLE 2,
following is the function declaration:
int max(int num1,int num2);
Valid declaration:
int max(int ,int);
12
CALLING A FUNCTION
When a program calls a function, program
control is transferred to the called function. A
called function performs defined task, and when
its return statement is executed or when its
function-ending closing brace is reached, it
returns program control back to the main
program.
13
#include <stdio.h>
/* function declaration */ prototype
int max(int num1, int num2); O/P:
void main ()
Max value is : 200
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
/* calling a function to get max value */
ret = max(a,b);
printf( "Max value is : %d\n", ret );
}
/* function returning the max between two
numbers */
int max(int num1, int num2)
{
/* local variable declaration */
int result; 14
if (num1 > num2)
result = num1;
FUNCTION ARGUMENTS
Actual arguments/parameters are parameters
as they appear in function calls.
Formal parameters are parameters as they
appear in function declarations.
15
FUNCTION CALL BY VALUE
/* function definition to swap the #include <stdio.h>
values */ /* function declaration */
void swap(int x, int y) //x and y void swap(int x, int y);
are Formal arguments void main ()
{ {
int temp; /* local variable definition */
temp = x; /* save the value of x */ int a = 100;
x = y; /* put y into x */ int b = 200;
y = temp; /* put x into y */ printf("Before swap, value of a :
%d\n", a );
printf("After swap, value of a : printf("Before swap, value of b :
%d\n", a ); %d\n", b );
printf("After swap, value of b : /* calling a function to swap the values
%d\n", b ); */
} swap(a, b); //a and b 16
are
Actual arguments
FUNCTION CALL BY REFERENCE
The call by reference method of passing
arguments to a function copies the address of an
argument into the formal parameter. Inside the
function, the address is used to access the actual
argument used in the call. This means that
changes made to the parameter affect the passed
argument.
17
/* function definition to swap the values */
void swap(int *x, int *y)
{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into y */
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b ); }
18
#include <stdio.h>
void swap(int *x, int *y); /* function declaration */
void main ()
{
int a = 100;
int b = 200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
21
FUNCTION WITH NO ARGUMENT AND NO
RETURN VALUE.
24
FUNCTION WITH ARGUMENT AND
RETURNS A VALUE.
25
RECURSION
A function that calls itself is known as a recursive function.
And, this technique is known as recursion.
The recursion continues until some condition is met to prevent
it.
O/P:
27
Factorial of 5 is 120
FIBONACCI SERIES FOR A GIVEN NUMBER
USING A RECURSIVE FUNCTION
#include <stdio.h>
int fibonacci(int I) O/P: 0 1 1 2 3 5 8 13 21 34
{
if(i == 0) a=0,b=1 c=a+b printf(c )a=b b=c
{
return 0;
}
if(i == 1)
{
return 1;
}
return fibonacci(i-1) + fibonacci(i-2); fib(1)+fib(0)=1+0 fib(2)+fib(1)=1+1
fib(3)+fib(2)=2+1=3
}
void main()
28
{ int i;
for (i = 0; i < 10; i++)
PASSING ARRAY TO FUNCTION IN C
In C, there are various general problems which requires passing
more than one variable of the same type to a function. For
example, consider a function which sorts the 10 elements in
ascending order. Such a function requires 10 numbers to be
passed as the actual parameters from the main function. Here,
instead of declaring 10 different numbers and then passing into
the function, we can declare and initialize an array and pass that
into the function. This will resolve all the complexity since the
function will now work for any number of values.
As we know that the array_name contains the address of the
first element. Here, we must notice that we need to pass only
the name of the array in the function which is intended to
accept an array. The array defined as the formal parameter will
automatically refer to the array specified by the array name
defined as an actual parameter.
29
Second way:
return_type function(type arrayname[SIZE])
Third way:
return_type function(type *arrayname)
30
// Program to calculate the sum of array elements by passing to a
function
#include <stdio.h>
float calculateSum(float age[]); //function declaration/prototype
int main()
{
float result, age[] = {23.4, 55, 22.6, 3, 40.5, 18};
// age array is passed to calculateSum()
result = calculateSum(age); //function call
printf("Result = %.2f", result);
return 0;
}
float calculateSum(float age[]) //->[23.4,55,22.6,40.5,18]
{
float sum = 0.0;
for (int i = 0; i < 6; ++i)
{
sum += age[i];
}
31
return sum;
}
Result = 162.50
PASSING ARRAY TO FUNCTION IN C
#include<stdio.h>
void printStr(char str[])
{
printf("String is : %s",str);
}
void main()
{
// declare and initialize string
char str[] = "GeeksforGeeks";
// print string by passing string
// to a different function
printStr(str); 32
}
SCOPE, VISIBILITY AND LIFETIME OF
VARIABLE
Scope:
Scope is defined as the area in which the declared
variable is ‗available‘. There are five scopes in C:
program, file, function, block, and prototype. Let
us examine a dummy program to understand the
difference (the comments indicate the scope of
the specific variable):
33
34
The foo function has program scope. All non-static functions
have program scope, and they can be called from
anywhere in the program. Of course, to make such a call, the
function needs to be first declared using extern, before being
called, but the point is that it is available throughout the
program.
The function bar has file scope — it can be called from
only within the file in which it is declared. It cannot be
called from other files, unlike foo, which could be called after
providing the external declaration of foo.
The label print has function scope. Remember that labels are used
as a target for jumps using goto in C. There can be only one print
label inside a function, and you can write a goto print statement
anywhere in the function, even before the label appears in the
function. Only labels can have function scope in C.
The variable i has block scope, though declared at the same
level/block as print. Why is that so? The answer is, we can
define another variable with the same name i inside
another block within the bar function, whereas it is not
possible for print, since it is a label.
The variable j has prototype scope: you cannot declare any
other parameter with the same name j in the function baz. 35
Note that the scope of j ends with the prototype declaration: you
can define the function baz with the first argument with any
name other than j.
Lifetime
The lifetime of a variable is the period of time in which
the variable is allocated a space (i.e., the period of time
for which it ―lives‖). There are three lifetimes in C:
static, automatic and dynamic. Let us look at an
example:
36
In this code, the variable count has a static lifetime,
i.e., its lifetime is that of the program. The variable
counter has an automatic lifetime — its life is till
the function returns; it points to a heap-allocated
memory block — its life remains till it is
explicitly deleted by the program, which is not
predictable, and hence it has a dynamic lifetime.
37
Visibility
Visibility is the ―accessibility‖ of the variable declared.
It is the result of hiding a variable in outer scopes.
Here is a dummy example:
38