You are on page 1of 90

1

2
3
4
ER/CORP/CRS/LA06/003 5
ER/CORP/CRS/LA06/003 6
ER/CORP/CRS/LA06/003 7
8
9
10
ER/CORP/CRS/LA06/003 11
The Retail Application case study will be used in through out the course for
introducing various concepts related to programming. This is continuation with the
case study discussed in the Programming Basics course
ER/CORP/CRS/LA06/003 12
13
14
Dividing a complex tasks into simpler sub tasks will help in managing better
as the sub tasks can be managed easily
15
To implement modular programming in C language , we can use functions. Top
Down approach can be used
What is Top Down approach ?
It is a Divide and Conquer approach
Top down approach is a technique for solving a large problem.
Top Down approach is iterative
-- many levels of decomposition
All the necessary knowledge should be present for the program before designing.
The slide shows an example of a retail application The application consists of
various modules which contain the activities involved in a retail store. The modules
are translated into functions , which in turn can further be divided into sub-functions
and so on. For example, the function for adding items can in turn call a function for
validation of the item description .
ER/CORP/CRS/LA06/003 16
17
How does functions make writing large programs easier?
Consider a program with 500 lines. It is rather easy write the program consisting of 10 functions
each of 50 lines of code than to write a single program of 500 lines.
The benefits of writing a large program in terms of functions are:
1. If a program is written using functions, the same can be tested independently of one
another.
2. The function designed for one program can be reused between other different
programs/projects. E.g login validations
3. Functions eliminate duplicating of the code
How does using functions make cooperative programming easier?
In a project wherein more number of programmers are involved (referred as multi-person
programming scenario), first it is decided on what functions need to be implemented and then
the functions are divided amongst the programmers.
PS: Cooperative programming is method in which certain or all costs involved in achieving a
common objective is/are divided among participating parties
18
The slide represents one possibility. The class may discuss others as well
19
The slide represents one possibility. The class may discuss others as well
20
21
Main is a user defined function and it is the starting point of execution of a
program.
Library is a collection of commonly used functions. It is present on the hard
disk and is written for us by people who write compilers.
Library functions need not be written by the user whereas the user defined
functions have to be written by the user. Libraries do not need main function
to be defined in them as they are a collection of functions.
22
Functions are of two types:
(1) Functions that return a value
(2) Functions that do not return a value
23
24
25
Function Declaration:
Also called function prototype or signature
Function Invocation:
Also called function calling or invocation
Function Definition:
Implementing the function.
26
The return data type in the prototype indicates the data type of the value that
the called function returns to the calling function.
If the return type of the function is void, it indicates that the function does not
return any value back to the calling function.
During the program life cycle if the program has any function call
statements,the compiler checks for the syntax of the function. The syntax of
the function basically revolves around the signature of the function (number
of parameters / type of parameters and sequence of parameters). This
information needs to be made available to the compiler before any function
is called. The signature of the function can be supplied to the compiler either
through function prototype declaration or through function definition. If this
input is not made available to the compiler it results in a compilation error
and the object code of the program is not successfully built.
27
The function prototype is required before the function is used in order to
inform the compiler about the function ie. The name, the parameters if any
and the return type.
28
A function definition contains the following two parts
Function header which contains:
1) Function name
2)Function return type
3)List of parameters
Function body which may contain:
1)Local variable declarations
2)Functional statements
3)Return statement
The function name should be a valid identifier.
The function return type is the type of value like int, float etc, that the function is expected to
return to the program calling the function. A function is void if it does not return
anything.
Parameter list:
Parameter list in the function call should match with the parameter list in the function header
Local variable declarations specify the variables needed by the function.
Function statements perform the task of the function.
Return statement returns the value to the calling function.
Return statement is also used to pass the execution from the called function to the calling
function
Void functions do not contain return statements.
29
30
31
32
33
34
35
In the slide shown above,
The function fnDisplay does the task of displaying Hello World.
36
The statements.. mentioned in the slide will be filled in due course. This represents
the skeleton code for the functions
37
38
39
40
41
42
43
44
45
46
Whenever a function is called, internally some set of instructions are executed to copy the
value/address of actual arguments to formal arguments and storing the return address to
the stack and also some set of instructions are executed to pop the return address from the
stack and also returns a value from the called function if any. So if the function task is too
simple then the amount overhead required for these book keeping operations will be more
than that is required for completing the actual task of the function which results in not
achieving the advantage of functions.
For example: In the following program example, functions are written for reading and
displaying an employee Id. As these tasks are too simple and require one or two lines and
also there is no scope of reusability, we can avoid writing separate functions for these.
#include<stdio.h>
int main(int argc, char **argv){
int iEmpId;
iEmpId = fnRead(iEmpId);
fnDisplay(iEmpId);
return 0;
}
int fnRead( int iEmpId){
printf(Enter employee Id);
scanf(%d, &iEmpId);
return iEmpId;
}
void fnDisplay( int iEmpId){
printf(Employee Id=%d, iEmpId);
}
47
The instructor can facilitate a discussion in class
More information:
Consider that there are 10 paintings and 3 of them needs to be chosen for hanging on the wall. In
order to know the number of combinations, the above mentioned formula is used. Here n=10, r=3
and hence C is 120
Possible implementation:
fnFactorial function to calculate the factorial of a number passed to it
fnCombination function to implement the formula using the fnFactorial function(this would be called
three times, hence is reusable code)
One main() to call the fnCombination function
We may avoid-
A function to calculate the difference
A function to divide a number by the other
48
49
Examples: Inside the functions ( local variables):
int fnArea() {
/*declaring local variables*/
int iLength, iBreadth, iArea;
/* initializing the variables*/
iLength = 50;
iBreadth = 40;
/* finding the area ( area = length x breadth )*/
iArea = iLength * iBreadth;
/* returning the value of Area */
return (iArea);
}
In the definition of function parameters:
int fnArea(int iLength, int iBreadth, int iArea) {
/* declaring the variables as formal parameters*/
/*finding the area ( area = length x breadth )*/
iArea = iLength * iBreadth;
/* returning the value of Area */
return (iArea);
}
Outside of all functions:
/*declaring global variables ( outside any functions)*/
/* Coding standards are not followed intentionally for global variables */
Int iLength, iBreadth, iArea
int fnArea() {
/* initializing the variables*/
iLength = 50;
iBreadth = 40;
/*finding the area ( area = length x breadth )*/
iArea = iLength * iBreadth;
/* returning the value of Area */
return (iArea);
}
50
51
52
Since every function is to act as an independent black box, the variables declared
inside one function are not available to another function. By default, the scope of a
variable is local to the function in which it is declared. That is, a variable declared
within a block is said to be local to that block and cannot be accessed in any other
block. If another function needs to use this variable, it must be passed as a
parameter to that function.
A variable that is declared outside of all functions is a global variable. Global
variable value can be accessed and modified by any statement in an application.
The lifetime of the global variable is the same as that of the program itself; therefore
the memory allotted to the global variable is not released until the program
execution is completed. If the value of the global variable is incorrect, a detailed
code review of the functions in the program is to be made, while if the variable is
local to a function, only that function needs to debugged. It is therefore a good
programming practice to use global variables minimally and with caution. Structured
programming Gurus denounce the use of the global variables.
The distinction between local and global variables is that global variables are
initialized with default values but the local variables may contain garbage values if
not initialized. It is good practice to initialize the local variables
53
Consider the following example.
#include <stdio.h>
int giGlobalVar;
int iSameName;
void fnFunc();
int main(int argc, char **argv) {
int iLocalVar;
iSameName = 1;
giGlobalVar = 2;
iLocalVar = 3;
printf( "Starting in main : ");
printf(" iGlobalVar = %d, iLocalVar = %d, iSameName = %d \n\n", giGlobalVar, iLocalVar,
iSameName);
fnFunc();
printf( "Returned to main: ");
printf(" iGlobalVar = %d, iLocalVar = %d, iSameName = %d \n\n", giGlobalVar, iLocalVar,
iSameName);
return 0;
}
void fnFunc() {
int iLocalVar;
int iSameName;
giGlobalVar = 20;
iLocalVar = 50;
iSameName = 10;
printf( "In SubFunc..");
printf(" iGlobalVar = %d, iLocalVar = %d, iSameName = %d \n\n", giGlobalVar,
iLocalVar,iSameName);
}
Note that giGlobalVar and iSameName are global variables. Their values are visible throughout the program. The variable
iLocalVar is local to the function main(). Local variables are declared and are visible only inside function blocks. The variable
iLocalVar declared in the two functions have no connection with each other. They refer to different memory locations.
54
Continued from previous slide
When inside a function, a local variable has the same name as a global variable
(iSameName, for example), the local variable gets precedence to the global variable. Note
the output of the last printf() statement in the main( ) function. The value of the global
variable iSameVar is not changed because inside the function fnFunc(), only the local
variable of the same name is accessed.
Storing variables - Stack and Heap
When functions are in execution, memory is allocated from the stack for variables that are
referenced in a function. This storage is released as soon as the function completes the
execution.
On the other hand Global variables, which can be accesses by all functions of the program,
are stored on the data segment. Since they are accessible to every program the lifetime of
global variables is the lifetime of the program.
55
Continued from previous slide
Local variables come into existence as and when the function is called and
go away when the function execution is completed
Global variables are existing throughout the lifetime of the entire program
and can be used as communication source between several source files
56
57
Dynamic memory allocation refers to allocation of memory during execution
of a program ie. at runtime. Static allocation refers to allocation of memory
during program loading time.Ex. Variable declarations etc.
However the scope of dynamic memory allocation is beyond this course
hence not discussed in detail
58
59
60
61
62
Communication between functions is through the parameters. There are various mechanisms used to pass this
information.
(1)Pass by value
(2)Pass by reference
Consider the program below
#include <stdio.h>
void fnSwap(int, int);
int main( int argc, char **argv){
int iNum1,iNum2;
printf( Enter two integers to be swapped.);
scanf( "%d %d", &iNum1, &iNum2);
printf( "In main. A = %d and B = %d", iNum1, iNum2);
fnSwap(iNum1, iNum2);
printf("\n Back to main. Now A = %d and B = %d \n", iNum1, iNum2);
return 0;
}
void fnSwap( int iNumF1, int iNumF2){
int iTemp;
iTemp = iNumF1;
iNumF1 = iNumF2;
iNumF2 = iTemp;
printf(\n In vSwap. Now A = %d and B = %d", iNumF1, iNumF2);
}
63
64
65
66
67
68
69
70
71
Call by reference is used when arrays, structures etc. are passed . It is to be
noted however that arrays are passed only by reference and structures may
be passed by value or by reference
72
Here, at a time an individual array element is passed to the function
fnDisplay() and the function prints the passed array element. Note that since
at a time only one element is being passed, this element is collected in an
ordinary integer variable iMarks, in the function fnDisplay()
Array as function arguments
Array elements in function arguments act just like simple variables
- Pass by value
An array name passed as a function argument without an associated array
index acts as if was pass by reference
- Changing array elements in the function changes the
corresponding array elements in the calling program.
- It really is still pass by value, but it requires knowledge of
pointers to understand why
73
74
75
76
77
78
79
80
81
How does recursion work?
Below mentioned represents a simulation of how every call will be translated
.However, there is only one copy of the function and many recursive calls as per the
problem statement. Whenever the control returns from the function, it will return to
the place where it has been called.
int main(int argc, char **argv) {
-------------
iFactorial=fnFact(4);
---------------------
return 0;
}
Call 1:int fnFact(4)
{ int iFact;
if (4<= 1) { return 1; }
else {iFact = 4 * fnFact(4 - 1);}
return iFact;
}
Call 2:int f nFact(3)
{ int iFact;
if (3<= 1) { return 1; }
else { iFact =3 * f nFact(3 - 1); }
return iFact;
}
Call 3:int f nFact(2)
{ int iFact;
if (2<= 1) { return 1; }
else { iFact = 2 * f nFact(2 - 1); }
return iFact;
}
Call 4:int f nFact(1)
{ int iFact;
if (1<= 1) { return 1; }
else { iFact = 1 * f nFact(1 - 1); }
return iFact;
}
This figure demonstrates the calculation of factorial of 5 and how the recursive
technique splits the problem into smaller sub problems ( of the same type ) till an
indivisible unit is obtained
82
This figure shows the calculation of fnFact(3) , depicts the stack creation
83
84
Whenever the control returns from the function, it will return to the place where it has been called.
Call 1: void f nReverse(5)
{
if (5 > 0) {
f nReverse(5-1);
}
printf ("%d\t",5);
}
Call 2: void f nReverse(4)
{
if (4 > 0) {
f nReverse(4-1);
}
printf ("%d\t",4);
}
Call 3: void f nReverse(3)
{
if (3 > 0) {
f nReverse(3-1);
}
printf ("%d\t",3);
}
Call 4: void f nReverse(2)
{
if (2 > 0) {
f nReverse(2-1);
}
printf ("%d\t",2);
}
Call 5: void f nReverse(1)
{
if (1> 0) {
f nReverse(1-1);
}
printf ("%d\t",1);
}
Call 6: void f nReverse(0)
{
if (0> 0) {
f nReverse(0-1);
}
printf ("%d\t",0);
}
85
86
87
88
89
90

You might also like