PPS Unit-4 Notes
PPS Unit-4 Notes
Objectives
1
Derived data types
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.
3
Hierarchy of modularization
4
Modularization
Example:
PRINCIPAL
(main module)
• A Program in C is made up of one or more functions, one and only one of which
• The execution of the program always starts and ends with main, but it can call
• 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
• 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).
10
Advantages of Functions (2 of 2)
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 Header
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
• Function declaration header consists of three parts: the return type, the function
name and formal parameters
16
Function Declaration (2 of 2)
The general form of a function Prototype or Declaration
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
• 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
19
Function Call (3 of 4)
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
25
User Defined Functions
• 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
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.
}
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
34
Inter-Function Communication (1 of 5)
35
Inter-Function Communication (2 of 5)
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
1. Pass by values
2. return
40
Inter-Function Communication
Downward Communication in C
• Two data items are passed from main to the down function.
41
Inter-Function Communication
An example for Downward Communication
43
Inter-Function Communication
Upward Communication in C
44
Inter-Function Communication
An example for Upward Communication
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
• A Function whose definitions have been written and are available, which can be
used in a program.
• Function declaration for these functions are grouped together and collected in
several header files
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
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:
• 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:
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 )
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
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));
63
Arrays to functions
65
Arrays to functions
Passing Array Elements
66
Arrays to functions
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 also a useful way of creating and accessing dynamic data structures
such as linked lists or binary trees.
86
Designing recursive function
• Every recursive function must have a base case. The statement that solves the
problem is known as the base 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.
87
Rules for designing recursive function
• 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
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)
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)
return 1 * factorial(0)
Step 4: executes factorial(0)
Step 5: return 1
return 1
95
Recursive representation of Factorial(4) (5 of 11)
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)
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
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)
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
102
Differences between Iteration and Recursion
ITERATION RECURSION
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.
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
Page No:
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.
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).
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.
Calloc()
Lecture No:L64
Link to Session
Planner (SP):S.No….of SP
Date Conducted:
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.