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

Functions

1) Functions allow breaking programs into reusable blocks of code to perform specific tasks. Functions improve readability, reusability, and debuggability of code. 2) There are three aspects to C functions: the function declaration specifies the name, parameters, and return type. The function call transfers control to the function. The function definition contains the code that is executed. 3) Functions can have arguments and return values of different data types like int, float, char etc. Local variables are accessible only within the function while global variables can be accessed throughout the program.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

Functions

1) Functions allow breaking programs into reusable blocks of code to perform specific tasks. Functions improve readability, reusability, and debuggability of code. 2) There are three aspects to C functions: the function declaration specifies the name, parameters, and return type. The function call transfers control to the function. The function definition contains the code that is executed. 3) Functions can have arguments and return values of different data types like int, float, char etc. Local variables are accessible only within the function while global variables can be accessed throughout the program.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

CHAPTER:

FUNCTIONS

1
What is C Function?
•A function is a block of statements, which is used to perform 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. So in such scenario you have two options –
• A) Use the same set of statements every time you want to perform the
task.
• B) Create a function, which would do the task, and just call it every time
you need to perform the same task.
• Using option (b) is a good practice and a good programmer always
uses functions while writing codes.
•C function contains set of instructions enclosed by “{  }” which
performs specific operation in a C program.

2
Uses of C Function
• To improve the readability of code.
• Improves the reusability of the code, same function can be used in
any program rather than writing the same code from scratch.
• Debugging of the code would be easier if you use functions as errors
are easy to be traced.
• Reduces the size of the code, duplicate set of statements are replaced
by function calls.

3
Types of Functions
• 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.

• User Defined functions – The functions which we can create by


ourselves.

4
3 Aspects of each C Function
• Functiondeclaration or prototype  – This informs compiler about the
function name, function parameters and  return value’s data type.
• Function call – This calls the actual function
• Function definition – This contains all the statements to be executed.

C functions aspects syntax
Return_type function_name (arguments list)
function definition
{ Body of function; }
function call function_name (arguments list);
function declaration return_type function_name (argument list);

5
Function prototype (declaration)
• Every function in C programming should be declared before they are
used. These type of declaration are also called function prototype.
Function prototype gives compiler information about function name,
type of arguments to be passed and return type.
• Syntax of function prototype
return_type function_name (type(1) argument(1),...., type(n)
argument(n));
• In
the above example, int add(int a, int b); is a function prototype
which provides following information to the compiler:
• 1. name of the function is add()
• 2. return type of the function is int.
• 3. two arguments of type int are passed to function.
• Function prototype are not needed if user-definition function is
written before main() function.
6
Function call
• Control of the program cannot be transferred to user-defined
function unless it is called invoked.
• Syntax of function call
function_name (argument(1),....argument(n));
• Inthe above example, function call is made using statement
add(num1,num2); from main(). This make the control of program
jump from that statement to function definition and executes the
codes inside that function.
• A function can be called with or without an argument.

7
Function definition
return_type function_name (argument list)
{
Set of statements – Block of code
}
• return_type: Return type can be of any data type such as int, double,
char, void, short etc.
• function_name: It can be anything, however it is advised to have a
meaningful name for the functions so that it would be easy to
understand the purpose of function just by seeing it’s name.
• argument list: Argument list contains variables names along with
their data types. These arguments are kind of inputs for the function.
For example – A function which is used to add two integer variables,
will be having two integer argument.
• Block of code: Set of C statements, which will be executed8
whenever a call will be made to the function.
Sample Program
• As you know,
functions should be
declared and defined
before calling in a C
program.
• Function “square” is
called from main
function.
• The value of “m” is
passed as argument to
the function “square”.
This value is
multiplied by itself in
this function and
answer is printed.
9
return statement
• Return statement is
used for returning a
value from function
definition to calling
function.
• Syntax of return
statement
return (expression);
• For example:
• return a;
• return (a+b);

10
return statement
• Inthis example, value of variable add in add() function is returned
and that value is stored in variable sum in main() function. The data
type of expression in return statement should also match the return
type of function.

11
Types of parameters
• With respect to function, two types of parameters used are:
• 1. Actual Parameters – Parameters specified in function call
• 2. Formal Parameters – Parameters specified in function definition
void main()
{
int num1;
display(num1); //num1 is actual parameter
}
void display(int para1) //para1 is formal parameter
{
}

12
Types of user defined functions
• Forbetter understanding of arguments and return type in functions,
user-defined functions can be categorised as:
• Function with no arguments and no return value
• Function with no arguments and return value
• Function with arguments but no return value
• Function with arguments and return value.

13
Function with no arguments and no
return value

14
Function with no arguments and
return value

15
Function with arguments and no
return value

16
Function with arguments and
return value

17
Scope and lifetime of variables
• Scope of variables: It means in what part of the program the variable is
accessible. In what part of the program the variable is accessible is
dependent on where the variable is declared.
• Two types:
• Local variables
• Global variables
• Lifetime of variables: Life time of any variable is the time for which
the particular variable exists in memory during running of the program.
Local variables
• Declared inside the body of the function are called local variables for
that function.
• Cannot be accessed outside the function in which they are declared.
• Thus, local variables are internal to the function in which they are
defined.
• Variables declared in main( ) function or any user defined function are
local for the corresponding function.
• Not initialized automatically.
• Scope:
• Local variable can be used only in the function in which they declared.
• Lifetime:
• Lifetime of a local variable starts when control enters the function in which it
is declared and it is destroyed when control exists from the function.
Global variables
• Declared outside any function definition is called as global variable.
• Are accessible by all the functions in the program, i.e., all the functions
in the program can share global variable.
• Initialized automatically by default value.
• Scope:
• These variables are globally accessed from any part of the program. They are
declared before main function.
• Lifetime:
• Global variables exist in the memory as long as the program is running. These
variables are destroyed from the memory when the program terminates. These
variables occupy memory longer than local variables.
Local Variables
• Local Variables /* Compute Area and Perimeter of a circle */
#include <stdio.h>
• These variables are declared float pi = 3.14159; /* Global */
inside some functions. main() {
• Life time of a local variable is float rad; /* Local */

the entire execution period of printf( “Enter the radius “ );


the function in which it is scanf(“%f” , &rad);

defined. if ( rad > 0.0 ) {


float area = pi * rad * rad;
• Cannot be accessed by any float peri = 2 * pi * rad;
other function.
printf( “Area = %f\n” , area );
• In general variables declared printf( “Peri = %f\n” , peri );
}
inside a block are accessible else
only in that block. printf( “Negative radius\n”);

printf( “Area = %f\n” , area );


}
Global Variables
• Global Variables /* Compute Area and Perimeter of a circle */
#include <stdio.h>
• These variables are declared float pi = 3.14159; /* Global */
outside all functions. main() {
• Life time of a global variable is float rad; /* Local */

the entire execution period of printf( “Enter the radius “ );


the program. scanf(“%f” , &rad);

• Can be accessed by any if ( rad > 0.0 ) {


float area = pi * rad * rad;
function defined below the float peri = 2 * pi * rad;
declaration, in a file.
printf( “Area = %f\n” , area );
printf( “Peri = %f\n” , peri );
}
else
printf( “Negative radius\n”);

printf( “Area = %f\n” , area );


}
Initializing Local and Global
Variables
• When a local variable is defined, it is not initialized by the system, you
must initialize it yourself. Global variables are initialized automatically by
the system when you define them as follows −
Data Type Initial Default Value
int 0
char '\0'
float 0.000000
double 0.000000

• It is a good programming practice to initialize variables properly,


otherwise your program may produce unexpected results, because
uninitialized variables will take some garbage value already available at
their memory location.
23
Difference
Local Variable Global Variable
Local variables are declared inside a Global Variables are declared outside any
function, even as arguments. function.
Local Variables cannot be accessed Global Variables can be accessed in any
outside the function. function.
Local Variables are alive only for a Global Variables are alive till the end of
function. the program.
Local Variables are not automatically Global Variables are automatically
initialized. initialized to their default values.
Modification in local variable can be Modification in global variable can be
done only inside the function in which done from anywhere.
it is declared.
An added advantage of the local One cannot be sure in which function it
variable is that it makes it easier to will be modified or when the variable
debug and maintain the applications, values will be modified, so difficult to
there is nothing to trace. trace.

24
Recursion
• A functionthat 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.


25
Recursion
Program to find sum of n natural numbers.

26
Recursion
• Initially,
the sum() is called
from the main() function with
number passed as an
argument.
• Suppose, the value of num is 3
initially. During next function
call, 2 is passed to the sum()
function. This process
continues until num is equal to
0.
• When num is equal to 0, the if
condition fails and the else
part is executed returning the
sum of integers to the main()
function. 27
Recursion

28
Recursion
• The factorial of a positive number n is given by:
• factorial of n (n!) = 1*2*3*4....n
• The factorial of a negative number doesn't exist. And the factorial of
0 is 1.
• Suppose the user entered 6.
• Initially,
the factorial() is called from the main() function with 6
passed as an argument.
• Then, 5 is passed to the factorial() function from the same function
(recursive call). In each recursive call, the value of argument n is
decreased by 1.
• When the value of n is less than 1, there is no recursive call.

29
Recursion

30
How to call functions in a
program?
• Call by value
• Call by reference

• Call by value:
• In call by value method, the value of the variable is passed to the function
as parameter.
• Argument values are passed to the function, the contents of the actual
parameters are copied into the formal parameters.
• The value of the actual parameter cannot be modified by formal
parameter.
• Different memory is allocated for both actual and formal parameters.
Because, value of actual parameter is copied to formal parameter.

31
Call by Value
• In this program,
the values of the
variables “m” and
“n” are passed to
the function
“swap”.
• These values are
copied to formal
parameters “a”
and “b” in swap
function and
used.

32
Call by Value
• While
Passing Parameters using call by value, xerox copy of original
parameter is created and passed to the called function.
• Any update made inside method will not affect the original value of
variable in calling function.
• Inthe above example, m and n are the original values and xerox
copy of these values is passed to the function and these values are
copied into a, b variable of swap function respectively.
• As their scope is limited to only function so they cannot alter the
values inside main function.

33
Call by Reference
• Incall by reference method, the address of the variable (pointer) is
passed to the function as parameter and not the value.
• The value of the actual parameter can be modified by formal
parameter.
• Same memory is used for both actual and formal parameters since
only address is used by both parameters.

34
Call by Reference
• In this program, the
address of the
variables “m” and “n”
are passed to the
function “swap”.
• These values are not
copied to formal
parameters “a” and
“b” in swap function.
• Because, they are just
holding the address of
those variables.
• This address is used
to access and change
the values of the
variables. 35
Call by Reference
• While passing parameter using call by address scheme , we are
passing the actual address of the variable to the called function.
• Anyupdates made inside the called function will modify the original
copy since we are directly modifying the content of the exact
memory location

36
Difference
Call by Value Call by Reference
The value of the variable is passed to the The address of the variable (pointer) is passed to
function as parameter. the function as parameter and not the value.
 
Argument values are passed to the function, the Instead of copy, the address of the variable is
contents of the actual parameters are copied into sent to the called function.
the formal parameters.
 
The value of the actual parameter cannot be The value of the actual parameter can be
modified by formal parameter. modified by formal parameter.
 
Different Memory is allocated for both actual Same memory is used for both actual and formal
and formal parameters. Because, value of actual parameters since only address is used by both
parameter is copied to formal parameter. parameters.
 
Creates a new memory location for use within Passes a pointer to the memory location.
the subroutine. The memory is freed once it Changes made to the variable within the
leaves the subroutine. Changes made to the subroutine affects the variable outside the
variable are not affected outside the subroutine. subroutine.

37
Array as Parameter in Function
• We can pass the whole array as a parameter to the function.
• The name of an array is a pointer to the first element of an array.
• So, if we pass the name of an array as an argument, we are
effectively passing the whole array as an argument.
• Naturally, passing an address of an array is call by reference.
• Refer following programs:
• parameter_as_array.c
• parameter_as_array_1.c
• accessing_1D_array_using_pointer.c
• pass_string.c
• passing_array_2D.c
• accessing_2D_array_using_pointer.c

38
Accessing 2D array using pointer
• Let us suppose a two-dimensional array : int matrix[3][3];
• matrix => Points to base address of two-dimensional array.
Since array decays to pointer.
• *(matrix) => Points to first row of two-dimensional array.
• *(matrix + 0) => Points to first row of two-dimensional array.
• *(matrix + 1) => Points to second row of two-dimensional array.
• **matrix => Points to matrix[0][0]
• *(*(matrix + 0)) => Points to matrix[0][0]
• *(*(matrix + 0) + 0) => Points to matrix[0][0]
• *(*matrix + 1) => Points to matrix[0][1]
• *(*(matrix + 0) + 1) => Points to matrix[0][1]
• *(*(matrix + 2) + 2) => Points to matrix[2][2]
39
40
Returning array from Function
•C programming language does not allow to return whole array from
a function.
• However, we can return a pointer to the base address(address of first
element of array) of array from a function like any basic data type.
• We should not return base pointer of a local array declared inside a
function because as soon as control returns from a function all local
variables gets destroyed.
• If
we want to return a local array then we should declare it as a static
variable so that it retains it's value after function call.
• Refer program: return_1D_array.c, return_1D_array_as_static.c

41
THANK YOU!!!

42

You might also like