programming fundamentals - wordpress.com · er/corp/crp/la06/003 4 er/corp/crs/la06/003 version no:...

65
ER/CORP/CRP/LA06/003 1 Programming Fundamentals Day 2

Upload: others

Post on 20-Sep-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 1

Programming FundamentalsDay 2

Page 2: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 2

ER/CORP/CRS/LA06/003

Version no: 2.02Copyright © 2004,

Infosys Technologies Ltd

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

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

Page 3: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 3

ER/CORP/CRS/LA06/003

Version no: 2.03Copyright © 2004,

Infosys Technologies Ltd

References

• Kanetkar Yashvant, Let us C, BPB Publications• Balaguruswamy, Programming in ANSI C, Tata McGraw Hill

Page 4: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 4

ER/CORP/CRS/LA06/003

Version no: 2.04Copyright © 2004,

Infosys Technologies Ltd

Function Definition

• A unit of program code, as per some syntax, to perform specific and well defined task

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.

Page 5: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 5

ER/CORP/CRS/LA06/003

Version no: 2.05Copyright © 2004,

Infosys Technologies Ltd

Function Definition-(Contd…)

• Please refer to Notes page for more explanation on previous slide

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.

Page 6: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 6

ER/CORP/CRS/LA06/003

Version no: 2.06Copyright © 2004,

Infosys Technologies Ltd

data_type FunctionName(data_type id1, …,data_type idn)

{

Statement 1

………..

Statement n

return <return value>

}

Function Definition - Syntax

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.

Page 7: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 7

ER/CORP/CRS/LA06/003

Version no: 2.07Copyright © 2004,

Infosys Technologies Ltd

Function Definition - Example

int fiValidate_Date(int d,int m, int y){

/* Logic of Date Validation comes here*/::return(iValidationFlag);

}

/* 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”);

}

}

Page 8: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 8

ER/CORP/CRS/LA06/003

Version no: 2.08Copyright © 2004,

Infosys Technologies Ltd

Function Definition – Example-(Contd…)

• Please refer to Notes page for more explanation on previous slide

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.

Page 9: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 9

ER/CORP/CRS/LA06/003

Version no: 2.09Copyright © 2004,

Infosys Technologies Ltd

Accessing functions

• Create a Prototype• Call the function with appropriate arguments

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

Page 10: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 10

ER/CORP/CRS/LA06/003

Version no: 2.010Copyright © 2004,

Infosys Technologies Ltd

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

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

Page 11: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 11

ER/CORP/CRS/LA06/003

Version no: 2.011Copyright © 2004,

Infosys Technologies Ltd

Function Call :

result=function_name(Argument1, …, ArgumentN);

•Example :

iValidDate=iValidate_Date(iDay,iMonth,iYear);

Calling a function

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

Page 12: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 12

ER/CORP/CRS/LA06/003

Version no: 2.012Copyright © 2004,

Infosys Technologies Ltd

File test.c:int sum (int x, int y);

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

File share.cint sum(int x, int y);

int sum (int x, int y){return (x+y);}

Example One

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

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

Page 13: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 13

ER/CORP/CRS/LA06/003

Version no: 2.013Copyright © 2004,

Infosys Technologies Ltd

File test.c:

#include <stdio.h>int sum (int x, int y);

main(){int iResult,iN1,iN2;scanf(“%d%d”, &iN2,&iN2);iResult = sum(iN1,iN2);printf(“%d”, iResult);}

File share.c#include <stdio.h>int sum(int x, int y);

int sum (int x, int y){return (x+y);}

Example Two

The program will compile and link successfully

Page 14: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 14

ER/CORP/CRS/LA06/003

Version no: 2.014Copyright © 2004,

Infosys Technologies Ltd

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

File share.c#include <stdio.h>int sum(int x, int y);main( ){int c;c=10;}int sum (int x, int y){return (x+y);}

Example Three

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

Page 15: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 15

ER/CORP/CRS/LA06/003

Version no: 2.015Copyright © 2004,

Infosys Technologies Ltd

File test.c:int sum (int x, int y);int diff (int p, int q);main(){int iResult;scanf(“%d%d”, &a,&b);iResult = sum(a,b);printf(“%d”, iResult);iResult = diff(a,b);printf(“%d”, iResult);}

File share.cint sum(int x, int y);

int sum (int x, int y){return (x+y);}

Example Four

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

Page 16: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 16

ER/CORP/CRS/LA06/003

Version no: 2.016Copyright © 2004,

Infosys Technologies Ltd

File test.c:int sum (int x, int y);int diff (int p, int q);main(){int iResult;scanf(“%d%d”, &a,&b);iResult = sum(a,b);printf(“%d”, iResult);iResult = diff(a,b);printf(“%d”, iResult);}

File share.cint sum(int x, int y);int diff (int p, int q);int sum (int x, int y){return (x+y);}int diff (int x, int y){return (x-y);}

Example Five

Program compiles and links successfully

Page 17: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 17

ER/CORP/CRS/LA06/003

Version no: 2.017Copyright © 2004,

Infosys Technologies Ltd

• 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???

Key learning's

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.

Page 18: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 18

ER/CORP/CRS/LA06/003

Version no: 2.018Copyright © 2004,

Infosys Technologies Ltd

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.

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

Page 19: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 19

ER/CORP/CRS/LA06/003

Version no: 2.019Copyright © 2004,

Infosys Technologies Ltd

Arguments

• The arguments appearing in the function definition are formal arguments

• The arguments appearing in the function call are actual arguments

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);

}

Page 20: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 20

ER/CORP/CRS/LA06/003

Version no: 2.020Copyright © 2004,

Infosys Technologies Ltd

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

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

Page 21: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 21

ER/CORP/CRS/LA06/003

Version no: 2.021Copyright © 2004,

Infosys Technologies Ltd

Example

• Write a function to find the cube of an integer• Use it in main function to print the cubes of first 10 integers

Page 22: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 22

ER/CORP/CRS/LA06/003

Version no: 2.022Copyright © 2004,

Infosys Technologies Ltd

Cube function definition

int iCube(int iNumber){

int iCube;iCube = iNumber*iNumber*iNumber;return (iCube);

}

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.

Page 23: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 23

ER/CORP/CRS/LA06/003

Version no: 2.023Copyright © 2004,

Infosys Technologies Ltd

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.

Page 24: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 24

ER/CORP/CRS/LA06/003

Version no: 2.024Copyright © 2004,

Infosys Technologies Ltd

Parameter passing

• Pass by value• Pass by reference

Communication between functions is through the parameters. There are various mechanisms used to pass this information as listed.

Page 25: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 25

ER/CORP/CRS/LA06/003

Version no: 2.025Copyright © 2004,

Infosys Technologies Ltd

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.

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);

}

Page 26: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 26

ER/CORP/CRS/LA06/003

Version no: 2.026Copyright © 2004,

Infosys Technologies Ltd

100 200

200100

100 200

Actual Arguments

Data Being Passed

Formal Arguments

PASS BY VALUE

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.

Page 27: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 27

ER/CORP/CRS/LA06/003

Version no: 2.027Copyright © 2004,

Infosys Technologies Ltd

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.

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

Page 28: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 28

ER/CORP/CRS/LA06/003

Version no: 2.028Copyright © 2004,

Infosys Technologies Ltd

Pass by Reference

• Changes to formal args affect actual args• Alternative mechanism for returning info

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

Page 29: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 29

ER/CORP/CRS/LA06/003

Version no: 2.029Copyright © 2004,

Infosys Technologies Ltd

1020 1023

200100

10201023

Actual Arguments

Address of Actual Arguments

Formal Arguments

Pass by Reference

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.

Page 30: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 30

ER/CORP/CRS/LA06/003

Version no: 2.030Copyright © 2004,

Infosys Technologies Ltd

Recursive functions

• Functions that call themselves.

• Useful to implement functions on recursively defined structures.

• Elegant compared to non-recursive versions.

• Possibly inefficient.

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.

Page 31: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 31

ER/CORP/CRS/LA06/003

Version no: 2.031Copyright © 2004,

Infosys Technologies Ltd

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>long int factorial(int num); void main() { int num; long int f;printf("Enter a number: ");

scanf("%d", &num); f = factorial(num);printf("factorial of %d is %ld\n", num, f); return 0; } long int factorial(int num) { if (num == 1) return 1; elsereturn num * factorial(num-1); }

Fact(1)

Fact(2)

Fact(3)

Fact(5)

Fact(4)

main

Returns 1

Returns 2 * fact(1) which is 2 *1 ~1

Returns 3 * fact(2) which is 3 *2 ~ 6

Returns 4 * fact(3) which is 4 *6 ~ 24

Returns 5 * fact(4) which is 5 *24 ~ 120

Output is 120

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.

Page 32: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 32

ER/CORP/CRS/LA06/003

Version no: 2.032Copyright © 2004,

Infosys Technologies Ltd

Recursive functions

• ExampleWrite a function which finds the sum of first n integers; where n is the argument to the function

int fiSum(int iN)

{

if(iN==0)

return 0;

else

return iN + fiSum(iN-1);

}

Page 33: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 33

ER/CORP/CRS/LA06/003

Version no: 2.033Copyright © 2004,

Infosys Technologies Ltd

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;

}

Page 34: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 34

ER/CORP/CRS/LA06/003

Version no: 2.034Copyright © 2004,

Infosys Technologies Ltd

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;

elsereturn (iSum_Recursive(iNumber - 1) + iNumber);

}

Page 35: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 35

ER/CORP/CRS/LA06/003

Version no: 2.035Copyright © 2004,

Infosys Technologies Ltd

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

Page 36: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 36

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/CRS/LA06/003

Version no: 2.036Copyright © 2004,

Infosys Technologies Ltd

Use of functions ?

• To handle the complexity of design– Divide & conquer

• Abstraction

• Modularisation

– Reusability of code

Page 37: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 37

ModularityFunctions 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 debuggingSince 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.ReuseFunctions 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/CRS/LA06/003

Version no: 2.037Copyright © 2004,

Infosys Technologies Ltd

Advantages

• Writing modular programs• Reusability• Easy testing & debugging• Easy program modification• Encapsulation

Page 38: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 38

ER/CORP/CRS/LA06/003

Version no: 2.038Copyright © 2004,

Infosys Technologies Ltd

Issues in functions

• Parameter passing• Variables: Local & Global• Scope of variables

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.

Page 39: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 39

ER/CORP/CRS/LA06/003

Version no: 2.039Copyright © 2004,

Infosys Technologies Ltd

Global & local variables

• Local variables– variables defined inside a function

• Global variables– variables defined outside any function

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.

Page 40: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 40

ER/CORP/CRS/LA06/003

Version no: 2.040Copyright © 2004,

Infosys Technologies Ltd

Global & local variables-(Contd..)

• Please refer to Notes page for more explanation on previous slide

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); }

Page 41: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 41

ER/CORP/CRS/LA06/003

Version no: 2.041Copyright © 2004,

Infosys Technologies Ltd

Global & local variables-(Contd..)

• Please refer to Notes page for more explanation on previous slide

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.

Page 42: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 42

ER/CORP/CRS/LA06/003

Version no: 2.042Copyright © 2004,

Infosys Technologies Ltd

Scope of Variables

• Visibility of variables

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.

Page 43: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 43

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/CRS/LA06/003

Version no: 2.043Copyright © 2004,

Infosys Technologies Ltd

Scope rules

• Why do we need them?

Page 44: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 44

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/CRS/LA06/003

Version no: 2.044Copyright © 2004,

Infosys Technologies Ltd

Scope rules-(Contd…)

• Please refer to Notes page for more explanation on previous slide

Page 45: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 45

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 VariablesVariables 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 funBonly. The variable "l" will be visible only in function funB.

ER/CORP/CRS/LA06/003

Version no: 2.045Copyright © 2004,

Infosys Technologies Ltd

Scope rules-(Contd…)

• Please refer to Notes page for more explanation on previous slide

Page 46: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 46

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/CRS/LA06/003

Version no: 2.046Copyright © 2004,

Infosys Technologies Ltd

Scope rules-(Contd…)

• Please refer to Notes page for more explanation on previous slide

Page 47: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 47

ER/CORP/CRS/LA06/003

Version no: 2.047Copyright © 2004,

Infosys Technologies Ltd

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

Page 48: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 48

ER/CORP/CRS/LA06/003

Version no: 2.048Copyright © 2004,

Infosys Technologies Ltd

Top Down Design

• A technique for decomposing a problem into subtasks• Top Down design is iterative

– many levels of decomposition

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.

Page 49: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 49

ER/CORP/CRS/LA06/003

Version no: 2.049Copyright © 2004,

Infosys Technologies Ltd

Top Down Design-(Contd…)

• Strengths– easy to design

– can defer implementation details– suitable for natural hierarchical problems

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(){}

Page 50: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 50

ER/CORP/CRS/LA06/003

Version no: 2.050Copyright © 2004,

Infosys Technologies Ltd

Top Down Design-(Contd…)

• Please refer to Notes page for more explanation on previous slide

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

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

Page 51: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 51

ER/CORP/CRS/LA06/003

Version no: 2.051Copyright © 2004,

Infosys Technologies Ltd

Example

• Write a function to find the number of days between two given dates, using functions.

Page 52: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 52

ER/CORP/CRS/LA06/003

Version no: 2.052Copyright © 2004,

Infosys Technologies Ltd

Solution

date1 = ( d1, m1, y1), date2 = (d2, m2, y2)Assume date1 is earlier or same as date2.

Page 53: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 53

ER/CORP/CRS/LA06/003

Version no: 2.053Copyright © 2004,

Infosys Technologies Ltd

Solution continued

Case 1: y1 < y2total_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)

Page 54: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 54

ER/CORP/CRS/LA06/003

Version no: 2.054Copyright © 2004,

Infosys Technologies Ltd

Solution continued

Case 2: y1 == y2total_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)

Page 55: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 55

ER/CORP/CRS/LA06/003

Version no: 2.055Copyright © 2004,

Infosys Technologies Ltd

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.

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.

Page 56: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 56

ER/CORP/CRS/LA06/003

Version no: 2.056Copyright © 2004,

Infosys Technologies Ltd

Solution: Absolute Value function

float fAbsoluteVal(float N){

if( N > 0)return N;

elsereturn -N;

}

Page 57: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 57

ER/CORP/CRS/LA06/003

Version no: 2.057Copyright © 2004,

Infosys Technologies Ltd

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;

}

Page 58: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 58

ER/CORP/CRS/LA06/003

Version no: 2.058Copyright © 2004,

Infosys Technologies Ltd

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);}

Page 59: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 59

ER/CORP/CRS/LA06/003

Version no: 2.059Copyright © 2004,

Infosys Technologies Ltd

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 Integerwhile (iIsPrime(inumber) != 1)

iNumber = iNumber - 1;//If The Number Is Not Prime Decrement Itprintf("The Nearest Smaller Prime Number is : %d\n\n", iNumber);}

Page 60: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 60

ER/CORP/CRS/LA06/003

Version no: 2.060Copyright © 2004,

Infosys Technologies Ltd

Project Specs

• Telephone directory maintenance system.

Page 61: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 61

ER/CORP/CRS/LA06/003

Version no: 2.061Copyright © 2004,

Infosys Technologies Ltd

Detail Design

• The date difference problem.

Page 62: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 62

ER/CORP/CRS/LA06/003

Version no: 2.062Copyright © 2004,

Infosys Technologies Ltd

High Level Design

main

iValidate_Date Swap_Dates iDate_Difference

iIs_Leap_Year

Page 63: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 63

ER/CORP/CRS/LA06/003

Version no: 2.063Copyright © 2004,

Infosys Technologies Ltd

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 datethe year of the date

• Return Value : 1 if the date is valid.

0 if the date is not valid.

• Description : This function checks whethera given date is valid or not.

• Functions Called by : main

• Functions called by this function : iIs_Leap_Year.

Page 64: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 64

ER/CORP/CRS/LA06/003

Version no: 2.064Copyright © 2004,

Infosys Technologies Ltd

Summary

• Functions are basic building blocks of applications• Advantages of Top down design

Page 65: Programming Fundamentals - WordPress.com · ER/CORP/CRP/LA06/003 4 ER/CORP/CRS/LA06/003 Version no: 2.0 Copyright © 2004, 4 Infosys Technologies Ltd Function Definition • A unit

ER/CORP/CRP/LA06/003 65

ER/CORP/CRS/LA06/003

Version no: 2.065Copyright © 2004,

Infosys Technologies Ltd

Thank You!