0% found this document useful (0 votes)
49 views94 pages

PPS Unit-4 Notes

The document discusses functions in C programming. It defines objectives like understanding function declaration, definition, calls and parameter passing. It explains concepts like modular programming using functions, advantages of functions, and function definition, declaration and calls. Sample programs are provided to demonstrate how functions work and how they can be used to break down a large problem into smaller modular parts.

Uploaded by

ruchi
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)
49 views94 pages

PPS Unit-4 Notes

The document discusses functions in C programming. It defines objectives like understanding function declaration, definition, calls and parameter passing. It explains concepts like modular programming using functions, advantages of functions, and function definition, declaration and calls. Sample programs are provided to demonstrate how functions work and how they can be used to break down a large problem into smaller modular parts.

Uploaded by

ruchi
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/ 94

UNIT-3: Functions

Objectives

• To understand the software engineering principles of Structured programming and


modularity (top-down development)
• To understand the function declaration, function call, and function definition
• To understand inter- function communication through parameters
• To understand the four basic function designs
• To understand how function communicate through parameters
• To understand Standard functions
• To understand the differences between global and local scope

1
Derived data types

• Limited number of problems can be solved by using primary


data types
• Derived data types are needed to solve complex problems.
• Complex data types are derived from primary data types
• Derived data types available in C language are given below:

2
Designing Structured Programs

• Simple programs studied so far can be solved and understood without too much effort.

• Large programs need to be reduced into elementary parts for better understanding.

• The principles of top-down design and structured programming dictate that a program
should have a main module and its related modules.

• Each module can be further divided in to sub modules.

• Breaking a complex problem into smaller parts is known as factoring.

3
Hierarchy of modularization

• Module 1,2,3 are sub modules of main module


• Module 1a,1b,1c are sub modules of module1
• Module 2a is sub module of module 2
• Module 3a,3b are sub modules of module 3

4
Modularization
Example:
PRINCIPAL
(main module)

CULTURAL SPORTS ACADEMIC


( module 1) (module 2) (module 3)

SINGING DANCE CRICKET VOLLEY BALL


(module 1a) (module 1b) (module 2a) (module 2b)

TECH QUIZ PRESENTATION


(module 3a) (module 3b)
5
Modular Programming - Manageable
Same book
published in
Huge Book of several volumes.
3000 pages Easily
manageable
Functions in C

• Top-down design is implemented by using Functions in C

• A Program in C is made up of one or more functions, one and only one of which

must be named as main.

• The execution of the program always starts and ends with main, but it can call

other functions to do specific task.

• main ( ) is called by the OS and control returns to the OS after completion of main

function.

7
Structure Chart for a C Program

8
Functions in C

• A function is a section of a program that performs a specific task

• Solving a problem using different functions makes programming much simpler with
fewer defects

• A function receives zero or more pieces of data, operate on them and return at most one
piece of data

9
Advantages of Functions (1 of 2)
• Problems can be factored in to understandable and manageable steps(easy to
code and debug).

• Functions can be developed by different people and can be combined


together as one application.

• Functions support reusability. That is, once a function is written, it can be


called from any other module without having to rewrite the same. This saves
time in rewriting the same code.

10
Advantages of Functions (2 of 2)

James working on Susan working on cash George working on


enquiry module withdrawal module cash deposit module

Work Allotment

Code Integration

Application Development
11
Function Definition (1 of 4)
• A function is always associated with following three steps

• Function definition

• Function declaration

• Function call

• Function definition contains the code for a function

• Function definition is made up two parts

• Function Header

• Function body (Compound statement within opening and closing


braces)

12
Function Definition (2 of 4)
Function Header
• A function header consist of 3 parts
return type
function name
formal parameter list
• A semicolon is not used at end of function definition header

Function Body
• The function body contains local declarations and function statements in between
braces.
• Local declarations specify the variables needed by the function.
• The function statement terminated by a return statement
• If the function return type is void, a return statement is optional.

13
Function Definition (3 of 4)
Parameters
• Formal parameters are variables that are declared in the header of the function definition

• Actual parameters are used in the calling statement or sometimes they may be an
expression

• Formal and actual parameters must match exactly in type, order, and number. Their
names, however, no need to match.

14
Function Definition (4 of 4)
Parameters
Formal and actual parameters must match exactly in type, order, and number. Their names,
however, need not match.
double average(int x,int y);
void main()
{ actual parameters
double sum1;
sum1=average(10,20);// calling function
} x,y formal
parameters Execute

turbo C program examples 2 & 3, also show error simulation 15


Function Declaration (1 of 2)
• Function declaration consists only of a function header (no code)

• Function declaration header consists of three parts: the return type, the function
name and formal parameters

• Function declarations are terminated with a semicolon

• Declarations are placed in global declaration section before

the main function

• Function declaration is also known as function prototype

16
Function Declaration (2 of 2)
The general form of a function Prototype or Declaration

P arameter names can be omitted


F unc tion P rototype: from the function prototype

return_type function_name (type1 name1, type2 name2,..., typen namen) ;

R eturn type and parameter types S emi-colon indicates that this is only
must be provided in the prototype the function prototype, and that its
definition will be found elsewhere

17
Function Call (1 of 4)
• Function call is a postfix expression

• The operand in a function call is the function name; the operator is the parentheses set
(…), which contains actual parameters.

• Actual parameters identify the values that are to be sent to called function and must
match the formal parameters in type and order

• Multiple actual parameters are separated by comma

• Function call transfers the control to the function definition (called function)

• After execution of the function, it returns the result to the calling function

• Function having a return type void can be used only as a stand-alone statement

18
Function Call (2 of 4)
General form

Actual parameters

return type function-name(name1,name2,name3,……….,namen);

Return type of function


Each parameter is separated by
comma and function call ends with
semicolon

19
Function Call (3 of 4)

turbo c example 1 also show error simulation


20
Function Call (4 of 4)
Examples of Function Calls

21
How Functions Work?
main()

User defined
function
Function
call

22
Sample Program with function

23
Sample Program with function

24
Sample Program with function

turbo c example 2 also show error simulation

25
User Defined Functions

• Functions must be both declared and defined.


• Function declaration gives the whole picture of the function .
• Function declaration must be placed before the function call.

• Function declaration consists of:

• name of the function,


• return type,
• type and order of parameters

• Function definition contains the code that needs to complete the task

26
Declaring, Calling and Defining Functions

27
Basic Function designs (1 of 5)
• Basic function design is based on their return value and parameter list

• There are four basic designs

1. Void Functions without Parameter.

• Function with no arguments and no return value.

2. Void Functions with Parameter.

• Functions with arguments and no return values.

3. Non Void Functions without Parameters

• Functions with no argument and return values.

4. Non Void Functions with Parameters

• Functions with argument and return values.

28
Basic Function designs (1 of 5)
  Do not pass argument Do pass arguments
void main(void) void main(void)
{ {
      TestFunct();       TestFunct(123);
      ...       ...
} }
   
void TestFunct(void) void TestFunct(int i)
No return { {
   // receive nothing    // receive something and
   // and nothing to be    // the received/passed
   // returned    // value just
}    // used here. Nothing
   // to be returned.
}

void main(void) void main(void)


{ {
      x = TestFunct();       x = TestFunct(123);
      ...       ...
} }
   
With a return int TestFunct(void) int TestFunct(int x)
{ {
   // received/passed    // received/passed something
   // nothing but need to    // and need to return something
   // return something       return (x + x);
      return 123; }
}

29
Basic Function designs (2 of 5)
1. Void Functions without Parameters
• Void functions without parameters does not receive any parameters and also
does not return any value .
• This can be used only as a statement because a Void function does not return
a value
• This cannot be used in an expression
Example : result=greeting(); //error

turbo c example 4 also show error simulation


30
Basic Function designs (3 of 5)
2. Void Functions with Parameter
• The function that receives parameter but does not return any value
• This function takes arguments(parameter list)
• It can be used only as statement
• It cannot be used in an expression
Example: result=greeting(); //error

Void Function with Parameters C program example5.c


31
Basic Function designs (4 of 5)
3. Non Void Functions without Parameters

• The function returns a value but does not receive parameters

• It cannot be used as statement

• It can be used in an expression

Example: result=greeting(); //correct

Non-void Function without Parameters c program example6.c


32
Basic Function designs (5 of 5)
4. Non Void Function with Parameters

• The function receives parameters and return values


• It cannot be used as a statement
• It can be used in an expression
Example : result=greeting(); //correct

Calling a Function That Returns a Value c program example7.c 33


Assignment

Write a C program to implement GCD of 2


numbers by using 4 types of user defined
functions

34
Inter-Function Communication (1 of 5)

• The calling and called functions need to communicate to exchange data.


• The data flow between the calling and called functions can be divided into three
strategies:
1. a downward flow,
2. an upward flow, and
3. a bi-directional flow.
• A downward flow from calling function to called function
• An upward flow from called function to calling function
• A bi-directional flow in both directions

35
Inter-Function Communication (2 of 5)

Data Flow Strategies

36
Inter-Function Communication (3 of 5)
Downward flow
• Calling function sends data to called function (one way communication)
• Copy of data items are passed from calling function to called function
• Called function may change the values passed, but the original values in the calling
function remains unchanged
• Use call by value mechanism to implement downward flow

• Rules:
a. Use values in function call to pass the data
b. Use appropriate data types in function parameter list to receive data values
c. Use parameter identifiers in the called function to access the local copies of
the data

37
Inter-Function Communication (4 of 5)
Upward flow
• Called function sends data back to the calling function (one way communication)
• Data items are returned to the calling function from the called function
• Calling function may use the values passed from called function
• Original values of called function remains unchanged
• Use call by reference or return mechanism to implement upward communication
• Rules:
a. Use &variable name in function call to pass a reference to the variable
b. Use types * in the function parameter list to receive the variable’s address
c. Use *parameter name in the function to reference the original variable

38
Inter-Function Communication (5 of 5)
Bi-directional flow
• Calling function sends data down to called function
• Called function sends data up to calling function during or at the end of the process.
• Use call by reference or return mechanism to implement
bi-directional communication

• Rules:
a. Use &variable name in function call to pass a reference to the variable
b. Use types * in the function parameter list to receive the variable’s address
c. Use *parameter name in the function to reference the original variable

39
Inter-Function Communication
‘C’ implementation

• Most programming languages have three strategies for Inter-function communication:


Pass by value, pass by reference and return

• C Language uses two mechanisms for Inter function communication:

1. Pass by values

2. return

40
Inter-Function Communication
Downward Communication in C

• Pass-by-Value is a perfect solution for communication in downward direction

• Two data items are passed from main to the down function.

• Called function does not return any data item

41
Inter-Function Communication
An example for Downward Communication

turbo c example8.c also show error simulation 42


Inter-Function Communication
Upward Communication
• Return statement provides a mechanism for the return of data items in upward direction
flow
• This mechanism allows only one data item to be returned to the calling function.
• Called function needs to access variables in the calling function for passing multiple data
items. But C does not allow direct reference to a variable in the calling function.
• The solution to this problem is as follows.
• Calling function pass the address of a variable:
Ex: upfun (&x, &y)
• Called function declares a pointer variable to receive the address:
Ex: void upfun (int * ax, int * ay).
• Called function can then put the data in the address of the variable given by the
calling function.

43
Inter-Function Communication
Upward Communication in C

44
Inter-Function Communication
An example for Upward Communication

turbo c example9.c also show error simulation 45


Inter-Function Communication
Bi-directional Communication
• Strategy used for upward direction can be applied for communication in both
directions with a little difference.
• Use indirect reference in both sides of the assignment statement
• The variable in the called function is first accessed for retrieving the address variable
in the right hand side
• Access the same parameter again to store a value in the left hand side

46
Inter-Function Communication
An example for Bi-directional Communication

47
turbo c example10.c also show error simulation
Inter-Function Communication
An Exchange Function

48
turbo c example11.c also show error simulation
Inter-Function Communication
An example for Bi-directional Communication

Calculate Quotient and Remainder C program example16.c 49


Standard Functions (1 of 15)

• A Function whose definitions have been written and are available, which can be
used in a program.

• Declare the standard function that is to be used in the function declaration.

• Function declaration for these functions are grouped together and collected in
several header files

• Instead of using function declarations, standard functions can be included in the


header files at top portion of the program
• Ex: printf(),scanf()

50
Standard Functions (2 of 15 )
Library Functions and the Linker

51
Standard Functions (3 of 15 )
Math functions
• Many important library functions are available for mathematical calculations
• Most of these function declarations are in math header file (math.h) or standard library
header file (stdlib.h )
• Integer functions can be found in stdlib.h

Absolute value functions


• Absolute value function returns absolute value of a number
• Absolute value is the positive rendering of the value regardless of its sign
• In this function, there are 3 integer and 3 real functions
• Three integer functions are abs, labs and llabs
int abs (int number); //stdlib.h
long int labs(long int number); //stdlib.h
long long int llabs(long long int number); //stdlib.h
52
Standard Functions (4 of 15 )
Absolute value functions
• Three real functions are fabs(), fabsf() and fabsl()

double fabs(double number); //math.h


float fabsf(float number) //math.h
long double fabsl(long double number); //math.h

Example

abs(3)=3
abs(-3)=3
fabs(-3.4)=3.4
fabs(1.1)=1.1
abs(-1.9)=1

C example program12.c 53
Standard Functions (5 of 15)
Ceiling Functions
• A ceiling is the smallest integral value greater than or equal to a
number
• If all numbers are considered as a continuous range from minus
infinity to plus infinity, this function moves the number right to an
integral value
• Syntax
double ceil(double number); //math.h
float ceilf(float number); //math.h
long double ceill(long double number); //math.h
• Example
ceil(-1.9) =-1.0 ceil(1.9) =2.0
ceil(1.1) =2.0 ceil(-1.1) =-1.0

Note: ceilf() and ceill() are not supported in the current version
c example program program13.c 53
Standard Functions (6 of 15)
Floor Functions
• A floor is the largest integral value that is less than or equal to a
number
• If all numbers are considered as a continuous range from minus
infinity to plus infinity, this function moves the number left to an
integral value
• Syntax
double floor(double number); //math.h
float floorf(float number); //math.h
long double floorl(long double number); //math.h
• Example
floor(-1.9) =-2.0 floor(1.9) =1.0
floor(1.1) =1.0 floor(-1.1) =-2.0

Note: floorf() and floorl() are not supported in the current version
c example program program14.c 54
Standard Functions (7 of 15)
Truncate Functions
• A Truncate functions return the integral in the direction of zero
• This functions same as floor function for positive numbers and the same as ceiling for
negative numbers
• Syntax
double trunc(double number); //math.h
float truncf(float number); //math.h
long double truncl(long double number); //math.h
• Example
trunc(-1.1) =-1.0
trunc(1.9) =1.0
trunc(2.1)=2.0
trunc(-1.1) =-1.0
55
Note: trunc() function not supported in the current version
Standard Functions (8 of 15)
Round function
• Round function returns nearest integer value
• Syntax:
double round(double number); //math.h
float roundf(float number) //math.h
long double roundl(long double number); //math.h
long int lround(double number); //math.h
long int lroundf(float number) //math.h
long int lroundl(long double number); //math.h
long long int llround(doublenumber); //math.h
long long int llroundf(float number) //math.h
long long int llroundl(long double number); //math.h
• Examples:
round(-1.1)=-1.0 round(1.9)=2.0
round(-1.5)=-2.0 round(1.5)=2.0

56
Standard Functions (9 of 15 )
Power function

• The power(x,y) function returns the value of the x raised to the power of y i.e., x y

• Syntax:

double pow(double n1,double n2) //math.h


float powf(float n1,float n2) //math.h
long double powlf(long double n1,lobg double n2)//math.h

• Example:

pow(3.0,4.0)=81.0
pow(3.4,2.3)=16.687893

58
Standard Functions (10 of 15)
Sqrt function
Sqrt () returns non-negative square root of a number. Error occurs if the number is negative

Syntax:

double sqrt(double number); //math.h


float sqrtf(float number) //math.h
long double sqrtlf(long double number); //math.h

Examples:
sqrt(25)=5.0
sqrt(256)=16.0

59
Standard Functions (11 of 15 )
Random numbers
• A random number is a number selected from a set in which all members have same
probability of being selected
• Random numbers are useful in many areas of computer science
• Applications are testing and gaming
Random number Generation:
• Most languages provides functions to generate random numbers
• Each time a function is called, it generates another number
• To generate next number, the function uses its previous number
Random number generation methods
1. Seed provided by the user
2.we can use default seed provided by system

60
Standard Functions (12 of 15 )
Random Number Generation

61
Standard Functions (13 of 15 )

Generating a Random Number Series

62
Standard Functions (14 of 15)

Random numbers in C
• Two Random functions are provided in ‘C’ to build a random number series
seed random (srand)
random (rand)
• These function declarations are available in stdlib.h

Seed Random Number function(srand)


• This function creates the starting seed from a number series

Syntax
void srand(unsigned int seed);
• To generate same series in each run we can provide a constant seed, preferably prime
number such as 997 Ex: srand(997);
• To generate a different series in each run ,we use time of day as seed
as time will change every second , for this we need time.h
Ex: srand(time(NULL));

C program example15.c example17.c 62


Standard Functions (15 of 15)
Random number function
• The random number function - rand() returns pseudo random integer between 0 and
RAND_MAX
• RAND_MAX is defined in standard library as largest number that rand() can generate
• Each call generates next number in a random number series
• The random number function declaration is
int rand(void);
• C specifies the range between 0 to 32767
• When we need a random number in a different range we must map the standard range to
specified range
• Two common ranges are
real number series 0.0 to 1.0
integer series 0 to 25 or 11 to 20
• Generalized formula: rand()%range + minimum
range=(maximum-minimum)+1

63
Arrays to functions

• To process arrays in a large program, arrays are required to be passed to functions.

• Arrays can be passed to functions in two ways:

• Passing Individual Elements

• Individual elements can be passed to a function either by passing the data


values or by passing the addresses

• Passing the whole Array

• By using this, an Array name can be passed to the called function

65
Arrays to functions
Passing Array Elements

66
Arrays to functions

Passing the Address of an Array Element

67
Arrays to functions
Passing the Whole Array

68
Recursion

• There are two approaches to write repetitive algorithms: one approach uses loops
and the other one uses recursion

• Recursion is a repetitive process, in which a function can call itself.

• Recursive functions are useful in evaluating certain types of mathematical functions.

• Recursion is also a useful way of creating and accessing dynamic data structures
such as linked lists or binary trees.

86
Designing recursive function

• Recursive functions have two steps:


• each call either solves one part of the problem
• it reduces the size of the problem

• Every recursive function must have a base case. The statement that solves the
problem is known as the base case.

• The rest of the function is known as the general case.

• The recursion will be done until the problem converges to the simplest case.

• This simplest case will be solved by the function which will then return a value.

• Each recursive call reduces the size of the problem

87
Rules for designing recursive function

• First, determine the base case

• Then, determine the general case

• Finally, combine the base case and general case into a function.

88
Example: Factorial of a given number

Iterative Definition
•Factorial(n)= 1 if n=0
n*(n-1)*(n-2)…3*2*1 if n>0

Recursive Definition
Base Case
Factorial(n) = 1 if n=0
n*Fcatorial(n-1) if n>0
General Case

89
Recursive representation of Factorial(3) (1 of 2)

90
Recursive representation of Factorial(3) (2 of 2)
factorial(0) = 1;
factorial(n) = n*factorial(n-
1);
factorial(3) = 3 * factorial(2)
= 3 * (2 * factorial(1))
= 3 * ( 2 * (1 * factorial(0)))
= 3 * ( 2 * ( 1 * 1)))
= 3 * ( 2 * 1)
=3*2
=6

91
Recursive representation of Factorial(4) (1 of 11)
Executes factorial(4)

factorial(4)
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6 Stack

return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2
return 2 * factorial(1)
Main method

Step 3: executes factorial(1)


Step 6: return 1
return 1 * factorial(0)
Step 4: executes factorial(0)
Step 5: return 1
return 1

92
Recursive representation of Factorial(4) (2 of 11)

factorial(4)
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Executes factorial(3)
Stack
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2
return 2 * factorial(1)
Space Required
for factorial(4)

Step 3: executes factorial(1)


Main method
Step 6: return 1
return 1 * factorial(0)
Step 4: executes factorial(0)
Step 5: return 1
return 1

93
Recursive representation
Recursive representation of Factorial(4)
of Factorial(4) (3 of 11)

factorial(4)
Executes factorial(2)
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes factorial(3)
Step 8: return 6 Stack

return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2
return 2Space
* Required
factorial(1)
for factorial(3)
Space Required
Step 3: executes factorial(1)
Step 6: return 1 for factorial(4)
Main method

return 1 * factorial(0)
Step 4: executes factorial(0)
Step 5: return 1
return 1

94
Recursive representation of Factorial(4) (4 of 11)

factorial(4) Executes factorial(1)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1:
Stackexecutes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Space Required
Step 7: return 2 for factorial(2)
Space Required
return 2for*factorial(3)
factorial(1)
Space Required
for factorial(4)
Step 3: executes factorial(1)
Step 6: return 1 Main method

return 1 * factorial(0)
Step 4: executes factorial(0)
Step 5: return 1
return 1

95
Recursive representation of Factorial(4) (5 of 11)

factorial(4) Executes factorial(0)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Stack

Step 1: executes factorial(3)


Step 8: return 6
Space Required
return 3 * factorial(2)
for factorial(1)
Space Required
for factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Space Required
for factorial(3)

return 2 * factorial(1)
Space Required
for factorial(4)
Main method
Step 3: executes factorial(1)
Step 6: return 1
return 1 * factorial(0)
Step 4: executes factorial(0)
Step 5: return 1
return 1

96
Recursive representation of Factorial(4) (6 of 11)

factorial(4)
returns 1
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Stack
Step 1: executes factorial(3)
Step 8: return 6 Space Required
for factorial(0)

return 3 * factorial(2)
Space Required
for factorial(1)
Space Required
Step 2: executes factorial(2)
for factorial(2)
Step 7: return 2 Space Required
for factorial(3)
return 2 * factorial(1)
Space Required
for factorial(4)
Main method Step 3: executes factorial(1)
Step 6: return 1
return 1 * factorial(0)
Step 4: executes factorial(0)
Step 5: return 1
return 1

97
Recursive representation of Factorial(4) (7 of 11)

factorial(4)
returns factorial(0)
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes
Stack factorial(3)
Step 8: return 6
return 3 * factorial(2)
Space Required
for factorial(1)

Step 2: executes factorial(2)


Space Required

Step 7: return 2 for factorial(2)


Space Required

return 2 * factorial(1)
for factorial(3)
Space Required
for factorial(4)
Step 3: executes factorial(1)
Step 6: return 1 Main method

return 1 * factorial(0)
Step 4: executes factorial(0)
Step 5: return 1
return 1

98
Recursive representation of Factorial(4) (8 of 11)

factorial(4)
returns factorial(1)
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Step 1: executes
Stack factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Space Required

Step 7: return 2 for factorial(2)


Space Required

return 2 * Space
factorial(1)
for factorial(3)
Required
for factorial(4)
Step 3: executes factorial(1)
Step 6: return 1 Main method

return 1 * factorial(0)
Step 4: executes factorial(0)
Step 5: return 1
return 1

99
Recursive representation of Factorial(4) (9 of 11)

factorial(4) returns factorial(2)


Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Stack

Step 1: executes factorial(3)


Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2 Space Required
for factorial(3)

return 2 * factorial(1)
Space Required
for factorial(4)
Main method
Step 3: executes factorial(1)
Step 6: return 1
return 1 * factorial(0)
Step 4: executes factorial(0)
Step 5: return 1
return 1

100
Recursive representation of Factorial(4) (10 of 11)

factorial(4)
returns factorial(3)
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Stack
Step 1: executes factorial(3)
Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2
return 2 Space
* factorial(1)
Required
for factorial(4)
Main method Step 3: executes factorial(1)
Step 6: return 1
return 1 * factorial(0)
Step 4: executes factorial(0)
Step 5: return 1
return 1

101
Recursive representation of Factorial(4) (11 of 11)

returns factorial(4)

factorial(4)
Step 0: executes factorial(4)
Step 9: return 24
return 4 * factorial(3)
Stack

Step 1: executes factorial(3)


Step 8: return 6
return 3 * factorial(2)
Step 2: executes factorial(2)
Step 7: return 2
return 2 * factorial(1)
Main method
Step 3: executes factorial(1)
Step 6: return 1
return 1 * factorial(0)
Step 4: executes factorial(0)
Step 5: return 1
return 1

102
Differences between Iteration and Recursion

ITERATION RECURSION

Iteration explicitly uses repetition Recursion achieves repetition by


structure. calling the same function repeatedly.

Iteration is terminated when the loop Recursion is terminated when base


condition fails case is satisfied.

May have infinite loop if the loop Recursion is infinite if there is no base
condition never fails case or if base case never reaches.

Iterative functions execute much Recursive functions are slow and


faster and occupy less memory space. takes a lot of memory space compared
to iterative functions

Demo C Program Ex No. 26 & 27 103


Unit No:4

Dynamic Memory allocation


Lecture No:L63

Link to Session

Planner (SP):S.No….of SP

Date Conducted:

Page No:

Topics to be discussed in this section:

Memory Usage
Static Memory Allocation
Dynamic Memory Allocation
Memory Allocation Functions
Releasing Memory (free)

87
Memory allocation functions
• Memory allocation can be done either statically or dynamically.
• Static Allocation: Memory is allocated at compile time
• Dynamic Allocation: Memory is allocated at run time

Memory Allocation

88
Memory Usage
• Conceptually memory is divided into program memory and Data Memory.
• Program memory consists of the memory that is used for main() and all called functions.
• Data memory consists of global data and declarations .
• The stack memory contains the local variables of the function.
• Heap memory is unused memory allocated to the program and available during its execution.

A Conceptual View of Memory

89
Note: We can refer to memory allocated in the heap only through a pointer.
Memory allocation functions
• Four Memory management functions are used with dynamic memory.
• Functions malloc(), calloc(), realloc() are used for memory allocation.
• free() is used to return memory when memory is no longer needed.
• All the above memory management functions are available in the standard library
file (stdlib.h).

Memory Management Functions

90
Malloc()
• The malloc() function allocates a block of memory that contains the number of bytes
specified in its parameter.
• returns a void pointer to the first byte of the allocated memory.
• The malloc() function is declared as : void *malloc(size_t size);
• Ex: pInt=malloc(sizeof(int));
• malloc() returns the address of the first byte in the memory space allocated, otherwise returns
a NULL pointer, if it is not successful.

• An attempt to allocate memory from the heap when memory is insufficient is known as overflow.

• Turbo c exp7.c with error simulation 91


Unit No:4

Calloc()
Lecture No:L64

Link to Session

Planner (SP):S.No….of SP

Date Conducted:

• calloc() (contiguous memory allocation) function is primarily used to allocate


Page No:

memory for arrays.


• It sets memory to null characters, by differing malloc().
• The calloc() function is declared as :
• void *calloc(size_t element_count,size_t element_size);

• Turbo c exp8.c with error simulation


92
Realloc()
• The realloc() function changes the size of the memory block by deleting or
extending the memory at the end of the block.
• The realloc() function is declared as :
• void *realloc(void *ptr,size_t newsize);

• Turbo c exp9.c with error simulation


93
Releasing Memory(free)
• When memory locations allocated by malloc(),calloc(),realloc() are no longer needed, they
should be freed by using the function free().
• The free() function is declared as : void free(void *ptr);
• The following figure shows two examples .The first one releases memory allocated with
malloc() and second releases memory for 200 elements allocated by calloc().

Note: 1) Using a pointer after its memory has been released is a common programming
error. Guard against it by clearing the pointer.
2) The pointer used to free memory must be of the same type as the pointer used to
allocate the memory.

• Turbo c exp10.c with error simulation 94

You might also like