You are on page 1of 65

Programming Fundamentals

Day 2

ER/CORP/CRP/LA06/003 1
Session Plan
• What are functions ?
• How to define them ?
• Accessing functions
• Global variables and local variables
• Recursive Functions
• Use of functions
• Issues with functions
• Top down design
• Using Editor to trace and debug errors

ER/CORP/CRS/LA06/003
Copyright © 2004, 2
Infosys Technologies Ltd Version no: 2.0

Today's session we will be discussing the need for functions and how to use functions.

ER/CORP/CRP/LA06/003 2
References
• Kanetkar Yashvant, Let us C, BPB Publications
• Balaguruswamy, Programming in ANSI C, Tata McGraw Hill

ER/CORP/CRS/LA06/003
Copyright © 2004, 3
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 3
Function Definition
• A unit of program code, as per some syntax, to perform specific and well
defined task

ER/CORP/CRS/LA06/003
Copyright © 2004, 4
Infosys Technologies Ltd Version no: 2.0

The functions are the basic building block of a program. The use of functions breaks a large computing task into
several smaller and more manageable ones and allows reuse of what may already exist. Good functions hide
details of operation from parts of the program that don't need to know about them, thus giving a clear view of the
big picture. Basically, the functions provides the mechanism for producing programs that are easy to read, write,
understand, modify, debug and maintain
For a better understanding lets consider a program written in last class
#include <stdio.h>
void main(void)
{
float fMark1, fMark2, fMark3,fSum,fAvg;
scanf(“%f%f%f”,&fMark1,&fMark2,&fMark3);
fSum=fMark1+fMark2+fMark3; // statement 1
fAvg=fSum/3; //statement 2
printf(“%f”,fAvg);
}
There are 3 main functions in the above piece of code.They are scanf, printf, main.
Logically, a function is a piece of code that (ideally) achieves one well-defined objective – several of these pieces
are put together to write a complete working program. In our example scanf and printf are functions used to read
input and write output, respectively. These functions are available as part of the C library and may be used by any
C program. Note that, to use these functions, our program need not know anything about them except their name
and the format of the inputs to be provided. The code for the functions has been written, compiled and tested and
are made available in the C library. All that our program does is 'call' these functions with the right inputs.

ER/CORP/CRP/LA06/003 4
Function Definition-(Contd…)
• Please refer to Notes page for more explanation on previous slide

ER/CORP/CRS/LA06/003
Copyright © 2004, 5
Infosys Technologies Ltd Version no: 2.0

The three main components involved while using functions are:-


•Function Declaration
•Function Invocation
•Function Definition
Lets look at extending the same program to finding the grade of a student based on the average
#include <stdio.h>
void main(void)
{
float fMark1, fMark2, fMark3,fSum,fAvg;
scanf(“%f%f%f”,&fMark1,&fMark2,&fMark3);
fSum=fMark1+fMark2+fMark3; // statement 1
fAvg=fSum/3; //statement 2
if (fAvg > 80)
{
printf(“Grade is Excellent”);
}
else
{
printf(“Grade is Good”);
}
}
In both the program the instructions to calculate the average given the marks remains the same. Now lets put these
instructions in the function named calc_avg and call the function in both our programs.

ER/CORP/CRP/LA06/003 5
Function Definition - Syntax

data_type FunctionName(data_type id1, …,data_type idn)


{
Statement 1
………..
Statement n
return <return value>
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 6
Infosys Technologies Ltd Version no: 2.0

While defining functions the syntax to be followed is discussed in the slide. Use the syntax define the function
calc_avg for our problem.
float fCalc_avg(float fM1,fM2,fM3)
{
float fSum,fAvg;
fSum=fM1 + fM2 + fM3;
fAvg=fSum/3;
return fAvg;
}
In the above function definition
•The return type of the function is float
•The input to the function is three parameters fM1,fM2,fM3
•The function name is calc_avg
The mechanism that is used to implement new operations on data is function definition. A function definition
specifies the name of the function, the signature (the data types, order and number of parameters it expects to
receive) and its return type. A function definition also includes a function body with the declarations of its local
variables, and the statements that determine what the function does. The return statement is used to return a
value to the calling function. In C, every function must have a return type that indicates the data type of the value
that the function returns. If the function does not return a value, then the return type of the function is void.
Lets now use this function in our programs written earlier.

ER/CORP/CRP/LA06/003 6
Function Definition - Example
int fiValidate_Date(int d,int m, int y)
{
/* Logic of Date Validation comes here*/
:
:
return(iValidationFlag);
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 7
Infosys Technologies Ltd Version no: 2.0

/* program to calc avg and print it *


#include <stdio.h>
float fCalc_avg(float,float,float); // function declaration
void main(void){
float fMark1, fMark2, fMark3,fAvg;
scanf(“%f%f%f”,&fMark1,&fMark2,&fMark3);
fAvg=fCalc_avg(fMark1, fMark2, fMark3); // function invocation
printf(“%f”,fAvg);
}
#include <stdio.h>
float fCalc_avg(float,float,float);
void main(void)
{
float fMark1, fMark2, fMark3,fAvg;
scanf(“%f%f%f”,&fMark1,&fMark2,&fMark3);
fAvg=fCalc_avg(fMark1, fMark2, fMark3);
if (fAvg > 80)
{
printf(“Grade is Excellent”);
}
else
{
printf(“Grade is Good”);
}
}

ER/CORP/CRP/LA06/003 7
Function Definition – Example-(Contd…)
• Please refer to Notes page for more explanation on previous slide

ER/CORP/CRS/LA06/003
Copyright © 2004, 8
Infosys Technologies Ltd Version no: 2.0

In the above 2 codes we are declaring the function and then calling/invoking it. If you compare these codes with
our earlier codes 2 advantages are clear:-
•Modularity of the code
•Encapsulation (A person who may not know the process to calculating the average can call the calc_avg
function to achieve the result)
Function prototype or declaration establishes the name of the function, its return type, and the data type, order
and number of its formal parameters(may be none). The function declaration is optional if the function is defined
before it is used. Consider this example of a function prototype:
float fGetAverage (int iNum1, int iNum2, int iNum3);
Here fGetAverage is the name of the function. Float is the return type of the function. iNum1, iNum2 and iNum3
are integer variables and are the formal arguments (or parameters) passed to the function. Note the semi-colon
at the end of the function declaration.
The definition of this function could look like this:
float fGetAverage (int iNum1, int iNum2, int iNum3)
{
float fAvg;
fAvg = (iNum1 +iNum2 +iNum3)/3.0;
return fAvg;
}
The return statement is used to return a value to the calling function. In C, every function must have a return type
that indicates the data type of the value that the function returns. If the function does not return a value, then the
return type of the function is void.

ER/CORP/CRP/LA06/003 8
Accessing functions
• Create a Prototype
• Call the function with appropriate arguments

ER/CORP/CRS/LA06/003
Copyright © 2004, 9
Infosys Technologies Ltd Version no: 2.0

Function prototype or declaration establishes the name of the function, its return type, and
the data type, order and number of its formal parameters(may be none). The function
declaration is optional if the function is defined before it is used. A function can call another
function only if the compiler sees at least the declaration of the called function before the
actual function call in the program file. Therefore, if main() calls the function fCalc_avg(), at
least the declaration of fCalc_avg() must be placed before main( ) in the program file.

When we make calls to standard library functions in our C programs, we are including the
prototype of these functions using the preprocessor directive
#include <stdio.h>
The prototype to fCalc_avg function which was written earlier can be put in a user defined
header file which will be #included in every program that needs to call the fCalc_avg
function.There is no rule that you have to put all the prototypes in a .h file. Its just a
convention followed.
Just like there are standard library functions it is possible for us to create user defined library
functions

ER/CORP/CRP/LA06/003 9
Function Prototype -- Syntax

• Prototype :
data_type FunctionName(data_type id1, ...
data_type idn);

• Example :
int iValidate_Date(int d,int m, int y);
Note: Name of the variables are not obligatory in prototype declaration

ER/CORP/CRS/LA06/003
Copyright © 2004, 10
Infosys Technologies Ltd Version no: 2.0

During the program life cycle if your program is having any function call statements then
while compilation process 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 info 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 thru function prototype declaration or thru function definition. If this input
is not made available to the compiler we get a compilation error and the object code of the
program is not successfully built

ER/CORP/CRP/LA06/003 10
Calling a function

Function Call :
result=function_name(Argument1, …,
ArgumentN);

•Example :

iValidDate=iValidate_Date(iDay,iMonth,iYear);

ER/CORP/CRS/LA06/003
Copyright © 2004, 11
Infosys Technologies Ltd Version no: 2.0

A function call is made when we wish to execute the set to instruction as part of the function.
After the object codes of the program are built during the linking phase the function call
reference is set to the function definition. If function definition is not found then it gives a
linker error and the exe is not created

ER/CORP/CRP/LA06/003 11
Example One
File test.c: File share.c
int sum (int x, int y); int sum(int x, int y);

main() int sum (int x, int y)


{ {
int iResult,iN2,iN2; return (x+y);
scanf(“%d%d”, &iN1,&iN2); }
iResult = sum(iN1,iN2);
printf(“%d”, iResult);
iResult = diff(iN1,iN2);
printf(“%d”, iResult);
}

The above program gives a compilation error because diff is not declared

ER/CORP/CRS/LA06/003
Copyright © 2004, 12
Infosys Technologies Ltd Version no: 2.0

The file test.c contains main function and the signature of the sum function.
It also calls the diff function but the diff function declaration is not found.
So the program gives a compilation error

ER/CORP/CRP/LA06/003 12
Example Two
File test.c: File share.c
#include <stdio.h> #include <stdio.h>
int sum (int x, int y); int sum(int x, int y);

main() int sum (int x, int y)


{ {
int iResult,iN1,iN2; return (x+y);
scanf(“%d%d”, &iN2,&iN2); }
iResult = sum(iN1,iN2);
printf(“%d”, iResult);
}

The program will compile and link successfully

ER/CORP/CRS/LA06/003
Copyright © 2004, 13
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 13
Example Three

File test.c: File share.c


#include <stdio.h>
#include <stdio.h>
int sum(int x, int y);
int sum (int x, int y);
main( )
main( )
{
{ int c;
int iResult,iN1,iN2; c=10;
scanf(“%d%d”, &iN1,&iN2); }
iResult = sum(a,b); int sum (int x, int y)
printf(“%d”, iResult); {
} return (x+y);
}

The above programs will give a linker error because there are multiple main functions

ER/CORP/CRS/LA06/003
Copyright © 2004, 14
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 14
Example Four
File test.c: File share.c
int sum (int x, int y); int sum(int x, int y);
int diff (int p, int q);
main() int sum (int x, int y)
{ {
int iResult; return (x+y);
scanf(“%d%d”, &a,&b); }
iResult = sum(a,b);
printf(“%d”, iResult);
iResult = diff(a,b);
printf(“%d”, iResult);
}

The above program gives linker error as the definition of the diif function is not
available

ER/CORP/CRS/LA06/003
Copyright © 2004, 15
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 15
Example Five

File test.c: File share.c


int sum (int x, int y); int sum(int x, int y);
int diff (int p, int q); int diff (int p, int q);
main() int sum (int x, int y)
{ {
int iResult; return (x+y);
scanf(“%d%d”, &a,&b); }
iResult = sum(a,b); int diff (int x, int y)
printf(“%d”, iResult); {
iResult = diff(a,b); return (x-y);
printf(“%d”, iResult); }
}

Program compiles and links successfully

ER/CORP/CRS/LA06/003
Copyright © 2004, 16
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 16
Key learning's

• Source can be distributed in Multiple Files

• main( ) denotes the entry point

• There can only be one main( ) across all files in a Program/Project.

• Multiple files Why???

ER/CORP/CRS/LA06/003
Copyright © 2004, 17
Infosys Technologies Ltd Version no: 2.0

Multiple files help us to divide the program logically into well defined modules which can be
coded and tested before integration together to create the complete application. It also helps
is easier development because the application is broken down into small modules which
meet a specific functionality. The modules are coded to meet the required specific
functionality. After all the modules are built as individual files the entire application is
integrated and linked to create on single exe.

ER/CORP/CRP/LA06/003 17
Communication of functions
• Information is passed to a function via arguments

• The function processes the information to produce a result (a value).

• Result is returned using a return statement.

ER/CORP/CRS/LA06/003
Copyright © 2004, 18
Infosys Technologies Ltd Version no: 2.0

Communication between functions is by arguments passed to the functions and values


returned by the functions. The return() statement is the mechanism for returning a value
from the called function to its caller. For example consider this program:
#include <stdio.h>
void vEmptyFunction (int ivar1, int ivar2)
{

}
void main()
{
int iNum1;
int iNum2;
vEmptyFunction (iNum1, iNum2);
}
Here, the variables iNum1 and iNum2 are declared with the main() function. main() is the
calling function and vEmptyFunction() is the called function. The above program when the
function vEmptyFunction is called the current context of main is stored in memory before the
control branches to the vEmptyfunction for execution. After the function completes execution
control returns to main (which is the parent calling function) , the context of main is retrieved
back and the execution continues

ER/CORP/CRP/LA06/003 18
Arguments
• The arguments appearing in the function definition are formal arguments

• The arguments appearing in the function call are actual arguments

ER/CORP/CRS/LA06/003
Copyright © 2004, 19
Infosys Technologies Ltd Version no: 2.0

iNum1 and iNum2 are actual arguments


ivar1 and ivar2 are formal arguments / parameters

void vEmptyFunction (int ivar1, int ivar2)


{

}
void main()
{
int iNum1;
int iNum2;
vEmptyFunction (iNum1, iNum2);
}

ER/CORP/CRP/LA06/003 19
Arguments continued
• The number of actual arguments must be the same as the number of formal
arguments
• The actual argument must be of the same data type as its corresponding
formal argument

ER/CORP/CRS/LA06/003
Copyright © 2004, 20
Infosys Technologies Ltd Version no: 2.0

The function signature consists of the number, type and order of arguments .

ER/CORP/CRP/LA06/003 20
Example
• Write a function to find the cube of an integer
• Use it in main function to print the cubes of first 10 integers

ER/CORP/CRS/LA06/003
Copyright © 2004, 21
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 21
Cube function definition
int iCube(int iNumber)
{
int iCube;
iCube = iNumber*iNumber*iNumber;
return (iCube);
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 22
Infosys Technologies Ltd Version no: 2.0

Use this function on a program that prints cube of first 10 integers.Type in the program on
using the Visual Studio editor. Compile, link and execute. Step through the program. Notice
how the control goes from the calling function to the called function.
While writing the function attempt should be made to create a function that is reusable
across applications and not just tied to one particular program. The function is a reusable
code that can be used in any program that needs to find the cube of integer numbers.

ER/CORP/CRP/LA06/003 22
Assignment
• Write a function that prints whether a given date falls in a leap year or not.
Validate the date as soon as it is accepted.

ER/CORP/CRS/LA06/003
Copyright © 2004, 23
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 23
Parameter passing
• Pass by value
• Pass by reference

ER/CORP/CRS/LA06/003
Copyright © 2004, 24
Infosys Technologies Ltd Version no: 2.0

Communication between functions is through the parameters. There are various


mechanisms used to pass this information as listed.

ER/CORP/CRP/LA06/003 24
Passing by value
• The value of the actual argument is copied into the formal argument.
• The value of the corresponding formal argument can be altered within the
function.
• The value of the actual argument within the calling routine will not change.

ER/CORP/CRS/LA06/003
Copyright © 2004, 25
Infosys Technologies Ltd Version no: 2.0

The value of the actual argument is copied into the formal arguments defined within the function. Hence when the
value of the formal argument is altered in the function, the value in the actual argument is not changed. In C,
parameters are passed by value.by default.
Consider the program below
#include <stdio.h>
void vSwap(int iA, int iB);
void main()
{
int iA,iB;
printf(“Enter two integers to be swapped.”);
scanf("%d %d", &iA, &iB);
printf("In main. A = %d and B = %d", iA, iB);
vSwap(iA, iB);
printf("\n Back to main. Now A = %d and B = %d \n", iA, iB);
}
void vSwap(int iA, int iB)
{
int iTemp;
iTemp = iA;
iA = iB;
iB = iTemp;
printf(“\n In vSwap. Now A = %d and B = %d", iA, iB);
}

ER/CORP/CRP/LA06/003 25
PASS BY VALUE

Actual Arguments

100 200

200 Data Being Passed


100

100 200 Formal Arguments

ER/CORP/CRS/LA06/003
Copyright © 2004, 26
Infosys Technologies Ltd Version no: 2.0

Consider the program below


#include <stdio.h>
void vSwap(int iA, int iB);
void main()
{
int iA, iB;
printf(“Enter two integers to be swapped.”);
scanf("%d %d", &iA, &iB);
printf("In main. A = %d and B = %d", iA, iB);
vSwap(iA, iB);
printf("\n Back to main. Now A = %d and B = %d \n", iA, iB);
}
void vSwap(int iA, int iB)
{
int iTemp;
iTemp = iA; iA = iB; iB = iTemp;
printf(“\n In vSwap. Now A = %d and B = %d", iA, iB);
}
Run the above code. Note that the values of iA and iB are not swapped after the function vSwap() is called. This is
because the values of iA and iB are passed by value to vSwap( ). That is, vSwap() works with a copy of the variables,
not the actual variables themselves.

ER/CORP/CRP/LA06/003 26
Passing by value- (Contd…)
• Advantages :
– Actual argument can be an expression /variable.
– Protects value of the actual argument from alterations within the function.
• Disadvantages
– Information cannot be transferred back to the calling portion of the program via
arguments.

ER/CORP/CRS/LA06/003
Copyright © 2004, 27
Infosys Technologies Ltd Version no: 2.0

Pass by value mechanisms does not help in getting the changes reflected back to the calling
function. Also functions by default return only one value back to the calling module. If we
would want the function to return multiple values than it would be possible only when the
changes made to the parameters in the functions are reflected to the calling module. This is
achieved using the pass by reference mechanism

ER/CORP/CRP/LA06/003 27
Pass by Reference
• Changes to formal args affect actual args
• Alternative mechanism for returning info

ER/CORP/CRS/LA06/003
Copyright © 2004, 28
Infosys Technologies Ltd Version no: 2.0

The value of the variable is not passed to the function; instead the address of the argument
is passed. The formal arguments receive the address and hence any modification done
within the function is actually reflected in the actual argument. An ampersand (&) before the
actual parameters in the function call indicates that the address of the parameter is passed

ER/CORP/CRP/LA06/003 28
Pass by Reference

Actual Arguments

100 200

Address of Actual
1020 Arguments
1023

1020 1023 Formal


Arguments

ER/CORP/CRS/LA06/003
Copyright © 2004, 29
Infosys Technologies Ltd Version no: 2.0

Consider the program below:-


#include <stdio.h>
void vSwap(int* iA, int* iB);
void main()
{
int iA, iB;
printf(“Enter two integers to be swapped.”);
scanf("%d %d", &iA, &iB);
printf("\nIn main. A = %d and B = %d.", iA, iB);
vSwap(&iA, &iB);
printf("\n Back to main. Now A = %d and B = %d \n", iA, iB);
}
void vSwap(int* iA, int* iB)
{
int iTemp;
iTemp = *iA; *iA = *iB; *iB = iTemp;
printf(“\n In vSwap. Now A = %d and B = %d", *iA, *iB);
}
Here, the * in the list of formal parameters indicates that the parameters passed to the functions must be the pointers
to addresses of the parameters, not the parameters themselves. Since the called function vSwap works with the
addresses of the variable iA and iB directly, so the swap made by vSwap( ) are retained.

ER/CORP/CRP/LA06/003 29
Recursive functions
• Functions that call themselves.

• Useful to implement functions on recursively defined structures.

• Elegant compared to non-recursive versions.

• Possibly inefficient.

ER/CORP/CRS/LA06/003
Copyright © 2004, 30
Infosys Technologies Ltd Version no: 2.0

A function calling itself is said to be a recursive function. The number of recursive calls is
limited to the size of the stack. Each time the function is called, new storage is allocated for
the parameters and for the local variables so that their values in previous, unfinished calls
are not overwritten. Parameters are only directly accessible to the instance of the function in
which they are created. Previous parameters are not directly accessible to ensuing
instances of the function.

Note that variables declared with static (Not to be used in this course) storage do not
require new storage with each recursive call. Their storage exists for the lifetime of the
program. Each reference to such a variable accesses the same storage area.
A recursive function should have the following properties:
· There must be a certain criteria, called base criteria, for which the function does not
call itself.
· Each time the function calls itself it must be closer to the base criteria.
The advantage of recursion is that many problems that exist in computer science are defined
in terms of recursive relationships, and the recursive problems usually end up with simple
and elegant solutions.

ER/CORP/CRP/LA06/003 30
Consider the example that calculates the Factorial of a number using recursion.
fact(n) = n * fact (n-)

The above rule terminates when n = 1, as the factorial of 1 is 1

#include <stdio.h> Fact(1)


long int factorial(int num); Returns 1
void main()
{ int num; long int f; Fact(2) Returns 2 * fact(1)
printf("Enter a number: "); which is 2 *1 ~1
scanf("%d", &num);
Fact(3)
f = factorial(num); Returns 3 * fact(2)
printf("factorial of %d is %ld\n", num, f); which is 3 *2 ~ 6
return 0; } Fact(4)
long int factorial(int num)
Returns 4 * fact(3)
{ which is 4 *6 ~ 24
if (num == 1) Fact(5)
return 1;
Returns 5 * fact(4)
else main which is 5 *24 ~ 120
return num * factorial(num-1);
} Output is 120
ER/CORP/CRS/LA06/003
Copyright © 2004, 31
Infosys Technologies Ltd Version no: 2.0

Functions may be recursive, that is a function may call itself. Each call to itself requires that
the current state of the function is pushed onto the stack. It is important to remember this
fact as it is easy to create a stack overflow, i.e. the stack has ran out of space to place any
more data
Consider a function that calculates the factorial of a given positive integer.

int iFactorial (int iNum)


{
if (iNum==0)
return (1);
else
return (n*iFactorial(n-1));
}

Although the use of recursion typically leads to smaller programs, recursive functions may
require more stack memory which is generally limited for an application . For a recursive
function, stack memory is used up for each recursive call and no memory is released until
the outer most function terminates. This may sometimes lead to a "Stack overflow" error
while using recursive functions.

ER/CORP/CRP/LA06/003 31
Recursive functions
• Example
Write a function which finds the sum of first n integers; where n is the
argument to the function

ER/CORP/CRS/LA06/003
Copyright © 2004, 32
Infosys Technologies Ltd Version no: 2.0

int fiSum(int iN)


{
if(iN==0)
return 0;
else
return iN + fiSum(iN-1);
}

ER/CORP/CRP/LA06/003 32
Sum of n integers
/* To find the sum of N integers, using the iterative method. */

int iSum_Iterative(int iNumber)


{
int iCount;
int iCumulativeSum=0;
for(iCount = 1; iCount <= iNumber; iCount = iCount + 1)
iCumulativeSum = iCumulativeSum + iCount;
return iCumulativeSum;
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 33
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 33
Sum of n integers -- recursive
/* To find the sum of N integers, using the recursive method. */

int iSum_Recursive(int iNumber)


{
if (iNumber == 1)
return 1;
else
return (iSum_Recursive(iNumber - 1) + iNumber);
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 34
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 34
Assignment

• Write a recursive function to find the factorial of a given integer number.


• Write a program to calculate Fibonacci number using
• Recursive Algorithm
• Non recursive algorithm

ER/CORP/CRS/LA06/003
Copyright © 2004, 35
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 35
Use of functions ?
• To handle the complexity of design
– Divide & conquer
• Abstraction
• Modularisation
– Reusability of code

ER/CORP/CRS/LA06/003
Copyright © 2004, 36
Infosys Technologies Ltd Version no: 2.0

People,as problem solvers are only able to focus on and comprehend at one time a very
limited span of logic or instructions. A technique for algorithm design that tries to
accommodate this human limitation is known as top down design. Top design is a strategy
that you can apply to take the solution of a computer problem from a vague outline to a
precisely defined algorithm and programming implementation. Top down design provides us
with a way of handling the inherent logical complexity of problems involving a number of
tasks. It allows us to build our solutions to such problems in a step wise fashion. Adopting a
structured style of programming provided us ways to break up a long continuous program
into a series of individual modules that are related to each other in a specified fashion.
These smaller programs called as functions also helped us in reusability of code.

ER/CORP/CRP/LA06/003 36
Advantages
• Writing modular programs
• Reusability
• Easy testing & debugging
• Easy program modification
• Encapsulation

ER/CORP/CRS/LA06/003
Copyright © 2004, 37
Infosys Technologies Ltd Version no: 2.0

Modularity
Functions provide the ability to organize complexity in a program. A large algorithm
can be divided into a number of components, with each component implemented as
a function. This division must be performed in such a way that only a few details
about a function are needed to write the main program. The majority of details need
be of concern only when designing the function itself.
Ease of testing and debugging
Since each function performs an independent task, it can be debugged and tested
independently. Once tested, a function can act like a black box to the rest of the
program - which only needs to be concerned with what the function does, not the
how.
Reuse
Functions can reduce the cost of developing a system. It eases the production
process through the use of previously written program components. By using these
programs, the programmer of a particular application can focus his attention on
those aspects unique to the given problem. It also reduces the need for redundant
programming of the same instructions.
Logical clarity
The decomposition of a program into several concise subprograms, where each
subprogram represents some well-defined part of the overall problem, results in
logical clarity, which in turn makes the program easier to modify in the future.

ER/CORP/CRP/LA06/003 37
Issues in functions
• Parameter passing
• Variables: Local & Global
• Scope of variables

ER/CORP/CRS/LA06/003
Copyright © 2004, 38
Infosys Technologies Ltd Version no: 2.0

A variable declared within the braces {} of a function is visible only within that function;
variables declared within functions are called local variables. If another function somewhere
else declares a local variable with the same name, it's a different variable entirely, and the
two don't clash with each other.
On the other hand, a variable declared outside of any function is a global variable, and it is
potentially visible anywhere within the program. You use global variables when you do want
the communications path to be able to travel to any part of the program. When you declare a
global variable, you will usually give it a longer, more descriptive name (not something
generic like i) so that whenever you use it you will remember that it's the same variable
everywhere.
Another word for the visibility of variables is scope.
How long do variables last? By default, local variables (those declared within a function)
have automatic duration: they spring into existence when the function is called, and they
(and their values) disappear when the function returns. Global variables, on the other hand,
have static duration: they last, and the values stored in them persist, for as long as the
program does. (Of course, the values can in general still be overwritten, so they don't
necessarily persist forever.)
Finally, it is possible to split a function up into several source files, for easier maintenance.
When several source files are combined into one program the compiler must have a way of
correlating the global variables which might be used to communicate between the several
source files.

ER/CORP/CRP/LA06/003 38
Global & local variables
• Local variables
– variables defined inside a function
• Global variables
– variables defined outside any function

ER/CORP/CRS/LA06/003
Copyright © 2004, 39
Infosys Technologies Ltd Version no: 2.0

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 any function 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.

ER/CORP/CRP/LA06/003 39
Global & local variables-(Contd..)
• Please refer to Notes page for more explanation on previous slide

ER/CORP/CRS/LA06/003
Copyright © 2004, 40
Infosys Technologies Ltd Version no: 2.0

Consider the following example.


#include <stdio.h>
int iGlobalVar; int iSameName;
void vFunc();
void main() {
int iLocalVar; iSameName = 1; iGlobalVar = 2; iLocalVar = 3;
printf("Starting in main : ");
printf(" iGlobalVar = %d, iLocalVar = %d, iSameName = %d \n\n", iGlobalVar, iLocalVar,
iSameName);
vFunc();
printf("Returned to main: ");
printf(" iGlobalVar = %d, iLocalVar = %d, iSameName = %d \n\n", iGlobalVar, iLocalVar,
iSameName); }

ER/CORP/CRP/LA06/003 40
Global & local variables-(Contd..)
• Please refer to Notes page for more explanation on previous slide

ER/CORP/CRS/LA06/003
Copyright © 2004, 41
Infosys Technologies Ltd Version no: 2.0

void vFunc()
{
int iLocalVar;
int iSameName;
iGlobalVar = 20;
iLocalVar = 50;
iSameName = 10;
printf("In vSubFunc.."); printf(" iGlobalVar = %d, iLocalVar = %d, iSameName = %d \n\n", iGlobalVar, iLocalVar,
iSameName);

Note that iGlobalVar 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.

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 fSubFunc(), only
the local variable of the same name is accessed.

2.4 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. The variables declared inside
a function (i.e. all the local variables) are allocated on the stack, as part of the function's stack frame. This stack
frame is wiped out once the function exits. All the local variables go away when the stack frame is wiped out.
Global variables, that are visible to every single function in the program, are stored on the heap memory. Since
they are accessible to every program the lifetime of global variables is the lifetime of the program.

ER/CORP/CRP/LA06/003 41
Scope of Variables
• Visibility of variables

ER/CORP/CRS/LA06/003
Copyright © 2004, 42
Infosys Technologies Ltd Version no: 2.0

Here is an example demonstrating almost everything we've seen so far:


int globalvar = 1;
f()
{
int localvar;
int localvar2 = 2;
}
globalvar is a global variable. The declaration we see is its defining instance (it happens also
to include an initial value). globalvar can be used anywhere in this source file, and it could be
used in other source files, too (as long as corresponding external declarations are issued in
those other source files).
localvar is a local variable within the function f(). It can be accessed only within the function
f(). (If any other part of the program declares a variable named ``localvar'', that variable will
be distinct from the one we're looking at here.) localvar is conceptually ``created'' each time
f() is called, and disappears when f() returns. Any value which was stored in localvar last
time f() was running will be lost and will not be available next time f() is called. Furthermore,
since it has no explicit initializer, the value of localvar will in general be garbage each time f()
is called.
localvar2 is also local, and everything that we said about localvar applies to it, except that
since its declaration includes an explicit initializer, it will be initialized to 2 each time f() is
called.

ER/CORP/CRP/LA06/003 42
Scope rules
• Why do we need them?

ER/CORP/CRS/LA06/003
Copyright © 2004, 43
Infosys Technologies Ltd Version no: 2.0

The scope of a variable is simply the part of the program where it may be accessed or
written. It is the part of the program where the variable's name may be used. If a variable is
declared within a function, it is local to that function. Variables of the same name may be
declared and used within other functions without any conflicts. For instance,

int fun1()
{
int a;
int b;
....
}

int fun2()
{
int a;
int c;
....
}

ER/CORP/CRP/LA06/003 43
Scope rules-(Contd…)
• Please refer to Notes page for more explanation on previous slide

ER/CORP/CRS/LA06/003
Copyright © 2004, 44
Infosys Technologies Ltd Version no: 2.0

Here, the local variable "a" in fun1 is distinct from the local variable "a" in fun2. Changes made to "a" in one
function have no effect on the "a" in the other function. Also, note that "b" exists and can be used only in fun1. "C"
exists and can be used only in fun2. The scope of b is fun1. The scope of c is fun2. Note that main is also a
function. Variables declared after the opening bracket of main will have all of main as their scope.

int fun1();
int fun2();

int main()
{
int a;
int b;
int x,y,z;

x = fun1();
y = fun2();

return 0;
}

int fun1()
{
int a;
int b;
....
}

int fun2()
{
int a;
int c;
}

ER/CORP/CRP/LA06/003 44
Scope rules-(Contd…)
• Please refer to Notes page for more explanation on previous slide

ER/CORP/CRS/LA06/003
Copyright © 2004, 45
Infosys Technologies Ltd Version no: 2.0

So here, a, b, x, y and z are local to main, a and b are local to fun1 and a and c are local to fun2.
Notice that in this example there are three distinct local variables all named "a". Local variables are
also referred to as automatic variables. They come to life at the beginning of a function and die at the
end automatically.
Global Variables
Variables may also be defined outside of any function. These are referred to as global variables. The
scope of an global variable is from its declaration to the end of the file. For instance:

int j;
...
int main()
{
....
}

int k;
float funA()
{
}

int l;
float funB()
{
}

The variable "j" will be visible in main, funA and funB. The variable "k" will be visible in funA and funB
only. The variable "l" will be visible only in function funB.

ER/CORP/CRP/LA06/003 45
Scope rules-(Contd…)
• Please refer to Notes page for more explanation on previous slide

ER/CORP/CRS/LA06/003
Copyright © 2004, 46
Infosys Technologies Ltd Version no: 2.0

An important distinction between local variables and global variables is how they are initialized. Global variables
are initialized to zero. Local variables are undefined. They will have whatever random value happens to be at their
memory location. Automatic, or local, variables must always be initialized before use. It is a serious error, a bug, to
use a local variable without initialization.

int fun1();
int fun2();
int main()
{
....
}
int fun3();

int fun1()
{
int i;
....
i = fun3();
....
}

int fun2()
{
.....
}
int fun3()
{
.....
}

Notice that here fun1 and fun2 may be called from main but fun3 may not. The function fun3 can be called from
fun1 and fun2 or from anywhere after its declaration

ER/CORP/CRP/LA06/003 46
Global variables
• Useful to communicate more than one results to the caller function
• Not the only means to do so
• Not recommended by the disciples of structured/modular programming.
• Alternate means – Pass by reference

ER/CORP/CRS/LA06/003
Copyright © 2004, 47
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 47
Top Down Design
• A technique for decomposing a problem into subtasks
• Top Down design is iterative
– many levels of decomposition

ER/CORP/CRS/LA06/003
Copyright © 2004, 48
Infosys Technologies Ltd Version no: 2.0

any large real world program is likely to have its code distributed among multiple files. There
are several practical reasons for organizing a program into multiple files. First, it allows parts
of the program to be developed independently, possible by different programmers. This
separation also allows independent compiling and testing of the modules in each file.
Second, it allows greater reuse. Files containing related functions can become libraries of
routines that can be used in multiple programs.

ER/CORP/CRP/LA06/003 48
Top Down Design-(Contd…)
• Strengths
– easy to design
– can defer implementation details
– suitable for natural hierarchical problems

ER/CORP/CRS/LA06/003
Copyright © 2004, 49
Infosys Technologies Ltd Version no: 2.0

In general, its recommended to put the main program in a single file and related functions in
their own files. So, you might have a large program divided into several files such as main.c,
input.c, output.c and calc.c. Here, main.c would contain the main program. Input functions
would be in input.c. Output functions would be in output.c and calculation functions in calc.c.
Each of the "function" files should have its own include file containing the prototypes of all
the functions in that file. So in this example, you would also have the include files input.h,
output.h and calc.h. Assume that main uses functions from all three files and that calc.c
requires routines from output.c to log error messages. Overall the program looks like:

main.c:
#include "input.h"
#include "output.h"
#include "calc.h"
main()
{
....
}

input.c:
function1() /* Functions can, of course, have any name */
{
}
function2()
{
}

ER/CORP/CRP/LA06/003 49
Top Down Design-(Contd…)
• Please refer to Notes page for more explanation on previous slide

ER/CORP/CRS/LA06/003
Copyright © 2004, 50
Infosys Technologies Ltd Version no: 2.0

utput.c:
functionA()
{
}
functionB()
{
}

calc.c:
#include "output.h"
functiony()
{
}
functionz()
{
}

ER/CORP/CRP/LA06/003 50
Example
• Write a function to find the number of days between two given dates, using
functions.

ER/CORP/CRS/LA06/003
Copyright © 2004, 51
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 51
Solution
date1 = ( d1, m1, y1),
date2 = (d2, m2, y2)
Assume date1 is earlier or same as date2.

ER/CORP/CRS/LA06/003
Copyright © 2004, 52
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 52
Solution continued
Case 1: y1 < y2
total_days = s_y_days + e_y_days + m_y_days

where:

s_y_days = no of remaining days in m1 +


the total of days in the months from (m1+1) to 12
e_y_days = (no of days covered in m2)-1 +
the total of days in the months from 1 to (m2-1)
m_y_days = total no of days in the years from y1+1 to (y2-1)

ER/CORP/CRS/LA06/003
Copyright © 2004, 53
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 53
Solution continued
Case 2: y1 == y2
total_days = s_m_days + e_m_days + m_m_days

where:
s_m_days = no of remaining days in m1
e_m_days = (no of days covered in m2) - 1
m_m_days = total no of days in the months
from (m1+1) to (m2-1)

ER/CORP/CRS/LA06/003
Copyright © 2004, 54
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 54
Example

• Write a function which will return the absolute value of a given number.

• Write a function whose prototype is, double fSquareRoot(double ) .


The function should return the square root of a given number, N, with
reasonable approximation, say, |N – (output)2 | < 0.001.
(For hint look at the text page.)

• Write a function to find whether the given number is prime or not.

• Use the above function to find the next prime number if the given number is not
prime.

ER/CORP/CRS/LA06/003
Copyright © 2004, 55
Infosys Technologies Ltd Version no: 2.0

Hint: you may use the following formula for your calculation:
Guess = ½( N/Guess +Guess), where Guess is the square root guessed by the user for the
first time . By default it can be 1 too.

ER/CORP/CRP/LA06/003 55
Solution: Absolute Value function

float fAbsoluteVal(float N)
{
if( N > 0)
return N;
else
return -N;
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 56
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 56
Soln Contd. :SquareRoot Function

float fSqroot(int iValue)


{
int iCounter = 0;
float fGuess = 1.0;
float fTemp;
do {
fGuess = (fGuess + (iValue / fGuess)) / 2;
iCounter = iCounter + 1;
fTemp = fAbsoluteVal(fGuess * fGuess - iValue);
}while ((iCounter < 100) && (fTemp> 0.001) );
return fGuess;
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 57
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 57
Soln. Contd. : PrimeCheck function

int iIsPrime(int iNumber)


{
int iCounter;
int iEnd;
iNumber =(int) fAbsoluteVal( iNumber);
iEnd =(int) fSqroot(iNumber);
for (iCounter = 2; iCounter <= iEnd; iCounter++)
if ((iNumber % iCounter) = = 0)
return (0);
return (1);
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 58
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 58
Solution Contd. : Main program

void main()
{
int iNumber;
printf("Please Enter the Number : ");
scanf("%d", &inumber);
//Find The Nearest Smaller Prime Number To A Given Integer
while (iIsPrime(inumber) != 1)
iNumber = iNumber - 1;//If The Number Is Not Prime Decrement It
printf("The Nearest Smaller Prime Number is : %d\n\n", iNumber);
}

ER/CORP/CRS/LA06/003
Copyright © 2004, 59
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 59
Project Specs
• Telephone directory maintenance system.

ER/CORP/CRS/LA06/003
Copyright © 2004, 60
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 60
Detail Design
• The date difference problem.

ER/CORP/CRS/LA06/003
Copyright © 2004, 61
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 61
High Level Design

main

iValidate_Date Swap_Dates iDate_Difference

iIs_Leap_Year

ER/CORP/CRS/LA06/003
Copyright © 2004, 62
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 62
Sample of the detailed design

• int iValidate_Date(int iday, int imonth, int iyear)


• Input Parameters : the day of the date
the month of the date
the year of the date
• Return Value : 1 if the date is valid.
0 if the date is not valid.
• Description : This function checks whether
a given date is valid or not.
• Functions Called by : main
• Functions called by this function : iIs_Leap_Year.

ER/CORP/CRS/LA06/003
Copyright © 2004, 63
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 63
Summary
• Functions are basic building blocks of applications
• Advantages of Top down design

ER/CORP/CRS/LA06/003
Copyright © 2004, 64
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 64
Thank You!

ER/CORP/CRS/LA06/003
Copyright © 2004, 65
Infosys Technologies Ltd Version no: 2.0

ER/CORP/CRP/LA06/003 65