0% found this document useful (0 votes)
19 views58 pages

Unit-IV PPS (3)

The document provides an overview of functions in C programming, explaining their definition, advantages, types, and how to work with them, including function declaration, calling, and definition. It also covers dynamic memory allocation (DMA) and the importance of adjusting array sizes during runtime using functions like malloc, calloc, free, and realloc. Additionally, the document discusses recursion, its implementation, and examples such as calculating factorial and Fibonacci series.

Uploaded by

rishik reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views58 pages

Unit-IV PPS (3)

The document provides an overview of functions in C programming, explaining their definition, advantages, types, and how to work with them, including function declaration, calling, and definition. It also covers dynamic memory allocation (DMA) and the importance of adjusting array sizes during runtime using functions like malloc, calloc, free, and realloc. Additionally, the document discusses recursion, its implementation, and examples such as calculating factorial and Fibonacci series.

Uploaded by

rishik reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Unit-IV

Functions, DMA

Prepared by GSK 1
What is Function?
• A function is a block of code that performs a
specific task.
• Suppose, you need to create a program to create
a circle and color it. You can create two functions
to solve this problem:
• create a circle function
• create a color function
• Dividing a complex problem into smaller chunks
makes our program easy to understand and
reuse

Prepared by GSK 2
What is Function?
• 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.

Prepared by GSK 3
Advantage of functions in C
• 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.

Prepared by GSK 4
How to work with Function?
• 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
parameters as it is declared in the function
declaration.

Prepared by GSK 5
How to work with Function?
• 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.

Prepared by GSK 6
Syntax:
Function declaration:
return_type function_name (argument list);
Function call:
function_name (argument_list)
Function definition:
return_type function_name (argument list)
{
function body;
}

Prepared by GSK 7
Types of Functions
• There are two types of functions in C
programming:
• Library Functions: are the functions which are
declared in the C header files such as scanf(),
printf(), gets(), puts(), ceil(), floor() etc.
• 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.

Prepared by GSK 8
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.
Prepared by GSK 9
Some of the Examples of Library Function

Header file Description


This is standard input/output
stdio.h header file in which Input/Output
functions are declared
This is console input/output
conio.h
header file
All string related functions are
string.h
defined in this header file
This header file contains general
stdlib.h
functions used in C programs
All maths related functions are
math.h
defined in this header file
Prepared by GSK 10
C User-defined functions
• A function is a block of code that performs a
specific task.
• C allows you to define functions according to
your need. These functions are known as user-
defined functions. For example:
• Suppose, you need to create a circle and color it
depending upon the radius and color. You can
create two functions to solve this problem:
• createCircle() function
• color() function

Prepared by GSK 11
Function prototype
• A function prototype is simply the declaration of a
function that specifies function's name,
parameters and return type. It doesn't contain
function body.
• A function prototype gives information to the
compiler that the function may later be used in
the program.

Prepared by GSK 12
Function prototype
• Syntax of function prototype
returnType functionName(type1 argument1, type2
argument2, ...);
• In the above example, int addNumbers(int a, int b); is
the function prototype which provides the following
information to the compiler:
• name of the function is addNumbers()
• return type of the function is int
• two arguments of type int are passed to the function
• The function prototype is not needed if the user-defined
function is defined before the main() function.
Prepared by GSK 13
Prepared by GSK 14
Calling a function
• Control of the program is transferred to the user-
defined function by calling it.
• Syntax of function call
• functionName(argument1, argument2, ...);
In the above example, the function call is made
using addNumbers(n1, n2);
statement inside the main() function.

Prepared by GSK 15
Function definition
• Function definition contains the block of code to
perform a specific task. In our example, adding
two numbers and returning it.
Syntax of function definition
• returnType functionName(type1 argument1,
type2 argument2, ...)
• {
• //body of the function
• } When a function is called, the control of the
program is transferred to the function definition.
And, the compiler starts executing the codes
inside the body of a function.
Prepared by GSK 16
Passing arguments to a function
• n programming, argument refers to the variable
passed to the function. In the above example,
two variables n1 and n2 are passed during the
function call.
• The parameters a and b accepts the passed
arguments in the function definition. These
arguments are called formal parameters of the
function.

Prepared by GSK 17
Prepared by GSK 18
Return Statement
• The return statement terminates the execution of
a function and returns a value to the calling
function. The program control is transferred to
the calling function after the return statement.
• In the example, the value of the result variable is
returned to the main function. The sum variable
in the main() function is assigned this value.

Prepared by GSK 19
Return Statement

Prepared by GSK 20
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.
void hello()
{
printf("hello c");
}

Prepared by GSK 21
Return Statement
• 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.
int value()
{
Statements;
return 10;
}
Prepared by GSK 22
How function works?

Prepared by GSK 23
Different aspects of function calling
Types of User defined Functions
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

Prepared by GSK 24
Parameter Passing
Techniques

Pass by value (Call by value)


Pass by reference (Call by reference)

Prepared by GSK 25
Parameter Passing Techniques

Prepared by GSK 26
Animation

Prepared by GSK 27
Prepared by GSK 28
Call by value
• Function call by value is the default way of calling
a function in C programming. Before we discuss
function call by value, lets understand the
terminologies that we will use while explaining
this:
• Actual parameters: The parameters that appear
in function calls.

• Formal parameters: The parameters that


appear in function definition

Prepared by GSK 29
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, different memory is allocated for
actual and formal parameters since the value of
the actual parameter is copied into the formal
parameter.

Prepared by GSK 30
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.
Prepared by GSK 31
Prepared by GSK 32
Prepared by GSK 33
Recursion in C
• A function that calls itself is known as a recursive
function. And, this technique is known as
recursion.

Prepared by GSK 34
Recursion Animated

Prepared by GSK 35
How recursion works?
void recurse()
{ ... .. ...
recurse();
... .. ...
}
int main()
{ ... .. ...
recurse();
... .. ...
}
Prepared by GSK 36
Prepared by GSK 37
Recursion in C
• 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.

Prepared by GSK 38
Recursion in C Cont. .
• 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.
Prepared by GSK 39
#include<stdio.h>

long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}

void main()
{
int number;
long fact;
printf("Enter a number: ");
scanf("%d", &number);

fact = factorial(number);
printf("Factorial of %d is %ld\n", number, fact);
return 0;
}
Prepared by GSK 40
Case:1 Output:

Case:2

Case:3

Prepared by GSK 41
Recursion

Prepared by GSK 42
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.

Prepared by GSK 43
Recursive Function
• if (test_for_base)
• {
• return some_value;
• }
• else if (test_for_another_base)
• {
• return some_another_value;
• }
• else
• {
• // Statements;
• recursive call;
• } Prepared by GSK 44
Fibonacci series using Recursion
• Fibonacci series in C using a loop and recursion.
You can print as many terms of the series as
required. The numbers of the sequence are
known as Fibonacci numbers.
• The first few numbers of the series are 0, 1, 1, 2,
3, 5, 8, ..., except for the first two terms of the
sequence, every other is the sum of the previous
two, for example, 8 = 3 + 5 (sum of 3 and 5).

Prepared by GSK 45
#include<stdio.h>
int f(int);
int main()
{
int n, i = 0, c;
scanf("%d", &n);
printf("Fibonacci series terms are:\n");
for (c = 1; c <= n; c++)
{
printf("%d\n", f(i));
i++;
}
return 0;
}
int f(int n)
{
if (n == 0 || n == 1)
return n;
else
return (f(n-1) + f(n-2));
}
Prepared by GSK 46
Output:

Prepared by GSK 47
Dynamic Memory
Allocation

DMA

Prepared by GSK 48
Dynamic Memory Allocation
• Since C is a structured language, it has some
fixed rules for programming. One of it includes
changing the size of an array. An array is
collection of items stored at continuous memory
locations

Prepared by GSK 49
DMA
• As it can be seen that the length (size) of the array
above made is 9. But what if there is a requirement to
change this length (size). For Example,
• If there is a situation where only 5 elements are
needed to be entered in this array. In this case, the
remaining 4 indices are just wasting memory in this
array. So there is a requirement to lessen the length
(size) of the array from 9 to 5.
• Take another situation. In this, there is an array of 9
elements with all 9 indices filled. But there is a need to
enter 3 more elements in this array. In this case 3
indices more are required. So the length (size) of the
array needs to be changed from 9 to 12.
Prepared by GSK 50
DMA
• Therefore, C Dynamic Memory Allocation can be
defined as a procedure in which the size of a data
structure (like Array) is changed during the runtime.
• C provides some functions to achieve these tasks.
There are 4 library functions provided by C defined
under <stdlib.h> header file to facilitate dynamic
memory allocation in C programming. They are:
• malloc()
• calloc()
• free()
• realloc()

Prepared by GSK 51
malloc( ) method
• “malloc” or “memory allocation” method in C
is used to dynamically allocate a single large
block of memory with the specified size.
• It returns a pointer of type void which can be cast
into a pointer of any form. It initializes each block
with default garbage value.
• Syntax:
• ptr = (cast-type*) malloc(byte-size)
• If space is insufficient, allocation fails and returns
a NULL pointer.

Prepared by GSK 52
malloc( ) method Cont. .
For Example:
• ptr = (int*) malloc(5 * sizeof(int));
• Since the size of int is 4 bytes, this statement will
allocate 20 bytes of memory. And, the pointer ptr
holds the address of the first byte in the allocated
memory.

Prepared by GSK 53
calloc( ) method
• “calloc” or “contiguous allocation” method in C is
used to dynamically allocate the specified number of
blocks of memory of the specified type.
• It initializes each block with a default value ‘0’.
Syntax:
• ptr = (cast-type*)calloc(n, element-size);

Prepared by GSK 54
calloc( ) method
For Example:
ptr = (float*) calloc(5, sizeof(int));
• This statement allocates contiguous space in
memory for 20 elements each with the size of the
int.

Prepared by GSK 55
free( ) method
• “free” method in C is used to dynamically de-
allocate the memory. The memory allocated using
functions malloc() and calloc() is not de-allocated on
their own. Hence the free() method is used, whenever
the dynamic memory allocation takes place. It helps to
reduce wastage of memory by freeing it.
Syntax:
• free(ptr);

Prepared by GSK 56
realloc( ) method
• “realloc” or “re-allocation” method in C is used
to dynamically change the memory allocation of
a previously allocated memory.
• In other words, if the memory previously
allocated with the help of malloc or calloc is
insufficient, realloc can be used to dynamically
re-allocate memory.
• re-allocation of memory maintains the already
present value and new blocks will be initialized
with default garbage value.

Prepared by GSK 57
realloc( ) method
• Syntax:
• ptr = realloc(ptr, newSize);
• where ptr is reallocated with new size 'newSize'.

Prepared by GSK 58

You might also like