1. Function prototype Function prototype is a declaration; indicates the function exists Should have...

40
EKT120 COMPUTER PROGRAMMING Functions (Part 2) Dr. Nik Adilah Hanin Bt. Zahri [email protected] 1

Transcript of 1. Function prototype Function prototype is a declaration; indicates the function exists Should have...

EKT150 INTRODUCTION TO COMPUTER PROGRAMMING

EKT120COMPUTER PROGRAMMING

Functions (Part 2)

Dr. Nik Adilah Hanin Bt. [email protected]

11Recaps Functions PrototypeFunction prototype

Function prototype is a declaration; indicates the function existsShould have function name, return type and parameterPlaced before main ()Tells compiler that the function will be defined later

#include

/* function prototype */

double product(double x, double y);

int main(){ double var1 = 3.0, var2 = 5.0; double ans;

/*function call*/ ans = product(var1, var2); printf("var1 = %.2lf\n" "var2 = %.2lf\n",var1,var2); printf("var1*var2 = %lf\n", ans);}

/* function definition */ double product(double x, double y)

{ double result;

result = x * y; return result; }2 Recaps Functions CallConsists of a function name followed by an argument expression list enclosed in parenthesesFunction call has the following form: (exp, exp ...)main is the calling functionproduct is the called function

#include

/* function prototype */

double product(double x, double y);

int main(){ double var1 = 3.0, var2 = 5.0; double ans;

/*function call*/ ans = product(var1, var2); printf("var1 = %.2lf\n" "var2 = %.2lf\n",var1,var2); printf("var1*var2 = %lf\n", ans);}

/* function definition */ double product(double x, double y)

{ double result;

result = x * y; return result; }3Recaps Functions Definition#include

/* function prototype */

double product(double x, double y);

int main(){ double var1 = 3.0, var2 = 5.0; double ans;

/*function call*/ ans = product(var1, var2); printf("var1 = %.2lf\n" "var2 = %.2lf\n",var1,var2); printf("var1*var2 = %lf\n", ans);}

/* function definition */ double product(double x, double y)

{ double result;

result = x * y; return result; }Function definition includes the body of a functionFunction definition has the following form: (arg_type arg_name, ...){ statements }4Recaps Number, order and type of parameterNumber, order and type of parameters in the argument list of a function call and function definition MUST match.5 int sum(int, int); //function prototype

int sum(int num1, int num2) //function definition

sum(x,y); //function call

//This program sums up two numbers#include int sum(int,int);//function prototype

int main(){ int x,y,result;printf(Enter x and y: );scanf(%d %d, &x, &y);result = sum(x,y); //function callprintf(Sum is : %d,result); return 0;}

int sum(int num1, int num2){ //function definitionint add;add = num1+num2;return add;}

6Recaps Functions that RETURN a valueRecaps Functions that DO NOT RETURN a value//This program sums up two numbers#include void sum_print(int, int); //function prototype

int main(){ int x,y;printf(Enter x and y: );scanf(%d %d, &x, &y);sum_print(x,y); //function callreturn 0;}void sum_print(int num1, int num2){//function definitionint add;add = num1+num2;printf(Sum is: %d,add); }7Recaps Global and Local VariablesGlobal variable

These variables are declared outside all functions, at the top of a source file.Declarations not placed in any functionsLife time of a global variable is the entire execution period of the program.Can be accessed by any function defined below the declaration8//Compute Area & Perimeter of a circle#include float pi = 3.14159; /* Global */int main() { floatrad;/* Local */ printf( Enter the radius ); scanf(%f , &rad);

if ( rad > 0.0 ) { float area = pi * rad * rad; float peri = 2 * pi * rad;

printf( Area = %f\n , area ); printf( Peri = %f\n , peri ); } else printf( Negative radius\n);

printf( Area = %f\n , area );

return 0;}Local variables

These variables are declared inside some functions (in a block { })Life time is the entire execution period of the function in which it is defined.Cannot be accessed by any other function scope is within its block In general variables declared inside a block are accessible only in that block.

9//Compute Area & Perimeter of a circle#include float pi = 3.14159; /* Global */int main() { float rad;/* Local */ printf( Enter the radius ); scanf(%f , &rad);

if ( rad > 0.0 ) { float area = pi * rad * rad; float peri = 2 * pi * rad;

printf( Area = %f\n , area ); printf( Peri = %f\n , peri ); } else printf( Negative radius\n);

printf( Area = %f\n , area );

return 0;}Recaps Global and Local VariablesTodays OutlinePassing parameters in functions :- Pass by valueFunctions that return more than one value and its sample applicationPassing parameters in functions :- Pass by reference and its applicationRecursive function10Sample Application Write a C program that reads item code and quantity, then calculates the payment. Use functions:fnMenu print item code menufnDeterminePrice determine price based on item codefnCalc - calculate paymentfnPrintResult print payment11Think!! Which function returns no value and which function returns a value.What argument names do I want to feed in as parameters and what to return??12#include

void fnMenu();float fnDeterminePrice(int);float fnCalc(float,int);void fnPrintResult(float);

int main(){int iCode,iQty;float fPriceUnit,fPay;fnMenu();printf("Enter item code and quantity:");scanf("%d %d", &iCode,&iQty);fPriceUnit = fnDeterminePrice(iCode);fPay = fnCalc(fPriceUnit,iQty);fnPrintResult(fPay);return 0; }

Sample Application: Local Variables13#include

void fnMenu();float fnDeterminePrice(int);float fnCalc(float,int);void fnPrintResult(float);

int main(){int iCode,iQty;float fPriceUnit,fPay;fnMenu();printf("Enter item code and quantity:");scanf("%d %d", &iCode,&iQty);fPriceUnit = fnDeterminePrice(iCode);fPay = fnCalc(fPriceUnit,iQty);fnPrintResult(fPay);return 0; }

void fnMenu(){ printf("Code\tItem\tPrice\n"); printf("1\tPapaya\t1.00\n"); printf("2\tMelon\t2.00\n"); printf("3\tDurian\t3.00\n"); printf("\tOthers\t4.00\n");}Sample Application: Local Variables#include

void fnMenu();float fnDeterminePrice(int);float fnCalc(float,int);void fnPrintResult(float);

int main(){int iCode,iQty;float fPriceUnit,fPay;fnMenu();printf("Enter item code and quantity:");scanf("%d %d", &iCode,&iQty);fPriceUnit = fnDeterminePrice(iCode);fPay = fnCalc(fPriceUnit,iQty);fnPrintResult(fPay);return 0; }

14void fnMenu(){ printf("Code\tItem\tPrice\n"); printf("1\tPapaya\t1.00\n"); printf("2\tMelon\t2.00\n"); printf("3\tDurian\t3.00\n"); printf("\tOthers\t4.00\n");}Code Item Price1 Papaya 1.002 Melon 2.003 Durian 3.00 Others 4.00OUTPUT:Sample Application: Local Variables#include

void fnMenu();float fnDeterminePrice(int);float fnCalc(float,int);void fnPrintResult(float);

int main(){int iCode,iQty;float fPriceUnit,fPay;fnMenu();printf("Enter item code and quantity:");scanf("%d %d", &iCode,&iQty);fPriceUnit = fnDeterminePrice(iCode);fPay = fnCalc(fPriceUnit,iQty);fnPrintResult(fPay);return 0; }

15Code Item Price1 Papaya 1.002 Melon 2.003 Durian 3.00 Others 4.00Enter item code and quantity: 1 3OUTPUT:Sample Application: Local Variables#include

void fnMenu();float fnDeterminePrice(int);float fnCalc(float,int);void fnPrintResult(float);

int main(){int iCode,iQty;float fPriceUnit,fPay;fnMenu();printf("Enter item code and quantity:");scanf("%d %d", &iCode,&iQty);fPriceUnit = fnDeterminePrice(iCode);fPay = fnCalc(fPriceUnit,iQty);fnPrintResult(fPay);return 0; }

16float fnDeterminePrice(int iItemCode){ float fPricing; switch(iItemCode) { case 1: fPricing = 1.00;break; case 2: fPricing = 2.00;break; case 3: fPricing = 3.00;break; default:fPricing = 4.00; } return fPricing;}Sample Application: Local Variables#include

void fnMenu();float fnDeterminePrice(int);float fnCalc(float,int);void fnPrintResult(float);

int main(){int iCode,iQty;float fPriceUnit,fPay;fnMenu();printf("Enter item code and quantity:");scanf("%d %d", &iCode,&iQty);fPriceUnit = fnDeterminePrice(iCode);fPay = fnCalc(fPriceUnit,iQty);fnPrintResult(fPay);return 0; }

17float fCalc(float fItemPrice, int iQuality){ float fTotal; fTotal = fItemPrice*iQuantity; return fTotal;}Sample Application: Local Variables#include

void fnMenu();float fnDeterminePrice(int);float fnCalc(float,int);void fnPrintResult(float);

int main(){int iCode,iQty;float fPriceUnit,fPay;fnMenu();printf("Enter item code and quantity:");scanf("%d %d", &iCode,&iQty);fPriceUnit = fnDeterminePrice(iCode);fPay = fnCalc(fPriceUnit,iQty);fnPrintResult(fPay);return 0; }

18void fnPrintResult(float fPayment){ printf("Payment is %.2f\n", fPayment);} Code Item Price1 Papaya 1.002 Melon 2.003 Durian 3.00 Others 4.00Enter item code and quantity: 1 3Payment is 3.00OUTPUT:Sample Application Local Variables19#include

void fnMenu();void fnDeterminePrice();void fnCalc();void fnPrintResult();

int iCode,iQty;float fPriceUnit,fPay;

int main(){ fnMenu();printf("Enter item code and quantity:");scanf("%d %d", &iCode,&iQty);fnDeterminePrice();fnCalc();fnPrintResult();return 0; }

void fnDeterminePrice(){ switch(iCode) { case 1: fPriceUnit=1.00; break; case 2: fPriceUnit=2.00; break; case 3: fPriceUnit=3.00; break; default:fPriceUnit=4.00; }}Sample Application: Global Variables20#include

void fnMenu();void fnDeterminePrice();void fnCalc();void fnPrintResult();

int iCode,iQty;float fPriceUnit,fPay;

int main(){ fnMenu();printf("Enter item code and quantity:");scanf("%d %d", &iCode,&iQty);fnDeterminePrice();fnCalc();fnPrintResult();return 0; }

void fCalc(){ fPay = fPriceUnit*iQty;}Sample Application: Global Variables21#include

void fnMenu();void fnDeterminePrice();void fnCalc();void fnPrintResult();

int iCode,iQty;float fPriceUnit,fPay;

int main(){ fnMenu();printf("Enter item code and quantity:");scanf("%d %d", &iCode,&iQty);fnDeterminePrice();fnCalc();fnPrintResult();return 0; }

void fnPrintResult(){ printf("Payment is %.2f\n", fPay);} Code Item Price1 Papaya 1.002 Melon 2.003 Durian 3.00 Others 4.00Enter item code and quantity: 1 3Payment is 3.00OUTPUT:Sample Application: Global Variables Pass by Value If a parameter is passed by value, then the value of the original data is copied into the functions parameter (scope: local variable(s))In other words, it (i.e. local variable) has its own copy of the dataChanges to copy do not change original dataDuring program execution, it (i.e. local variable) will only manipulate the data stored in its own memory space22Pass by Value (Example)#include void fnFun1(int,int); //function prototypeint main(){int iA=5, iB=10;printf("Before function1\n);printf(" iA = %d iB = %d\n, iA,iB);fnFun1(iA, iB); //function callprintf("\nAfter function1\n);printf(" iA = %d iB = %d\n, iA,iB);return 0;}

void fnFun1(int iAA,int iBB) //function definition{++iAA;--iBB;printf("\n\nInside fnFun1\n)";printf(iAA = %d iBB = %d\n, iAA,iBB);} 23Pass by Value (Example)#include void fnFun1(int,int); //function prototypeint main(){int iA=5, iB=10;printf("Before fnFun1\n);printf(" iA = %d iB = %d\n, iA,iB);fnFun1(iA, iB); //function callprintf("\nAfter fnFun1\n);printf(" iA = %d iB = %d\n, iA,iB);return 0;}

void fnFun1(int iAA,int iBB) //function definition{++iAA;--iBB;printf("\n\nInside fnFun1\n)";printf(iAA = %d iBB = %d\n, iAA,iBB);} 24OUTPUT

Before fnFun 1iA = 5 iB = 10

Inside fnFun 1iAA = 6 iBB = 9

After fnFun 1iA = 5 iB = 10

Functions that Return More than One Value When we talk about functions that return more than one value it refers to passing arguments by referencepasses addresses (references), NOT value or dataallows direct manipulationchanges will affect original dataThere are cases where you need to manipulate the value of an external variable from inside a function, thus we pass the value by reference

25Pass by Reference A functions parameter that receives the location (memory address) of the corresponding actual variablesWhen we attach * (star) after the arg_type in the parameter list of a function, then the variable following that arg_type is passed by referenceIt stores the address of the actual variable, NOT the valueDuring program execution to manipulate the data, the address stored will have direct control to the memory space of the actual variableSyntax: In function protoype and function definition, put the * (star) after the data type Example : void fnReadMarks(float *,float *);In function call, put the &(ampersand) before the argument name to be passed by reference Example : fnReadMarks(&fMarks1,&fMarks2);2627Pass by reference is useful in two situations:when you want to return more than one value from a functionwhen the value of the actual parameter needs to be changedPass by Reference Pass by Reference (Example)#include void fnFun1(int, int*); //function prototypeint main(void){ int iA=5,iB=10; printf("Before fun 1\n); printf(iA = %d iB = %d,iA,iB); fnFun1(iA, &iB); //function call printf(\n\nAfter fun 1\n); printf(iA = %d iB = %d\n,iA,iB); return 0;}void fnFun1(int iAA,int *iBB)//function definition{++iAA; --*iBB; printf("\n\nInside fnFun1\n); printf(iAA = %d iBB = %d,iAA,*iBB);}28Pass by Reference (Example)#include void fnFun1(int, int*); //function prototypeint main(void){ int iA=5,iB=10; printf("Before fun 1\n); printf(iA = %d iB = %d,iA,iB); fnFun1(iA, &iB); //function call printf(\n\nAfter fun 1\n); printf(iA = %d iB = %d\n,iA,iB); return 0;}void fnFun1(int iAA,int *iBB)//function definition{++iAA; --*iBB; printf("\n\nInside fnFun1\n); printf(iAA = %d iBB = %d,iAA,*iBB);}29OUTPUT

OutputBefore fnFun1iA=5 iB = 10

Inside fnFun1iAA = 6 iBB = 9

After fnFun1iA = 5 iB = 9

Sample Application Write a C program that calculates and prints average of 2 test marks.Your program should have functions: fnReadMarks read 2 test marksfnCalcAvg calculate average of two test marksfnPrint - print average3031#include void fnReadMarks(float*,float*);float fnCalcAvg(float,float);void fnPrint(float);

int main(void){ float fMarks1, fMarks2, fAvg; fnReadMarks(&fMarks1,&fMarks2); fAvg = fnCalcAvg(fMarks1,fMarks2); fnPrint(fAvg);return 0;}

void fnReadMarks(float *fM1,float *fM2){ printf("Enter marks for test1 and test2 : "); scanf("%f %f", fM1,fM2); //notice no &}

float fnCalcAvg(float fM1, float fM2){ return((fM1 + fM2)/2);}

void fnPrint(float fAverage){ printf("\nAverage marks are :%.2f\n",fAverage);}

Function that returns more than one value - arguments are passed by referenceSample Application32#include void fnReadMarks(float*,float*);float fnCalcAvg(float,float);void fnPrint(float);

int main(void){ float fMarks1, fMarks2, fAvg; fnReadMarks(&fMarks1,&fMarks2); fAvg = fnCalcAvg(fMarks1,fMarks2); fnPrint(fAvg);return 0;}

void fnReadMarks(float *fM1,float *fM2){ printf("Enter marks for test1 and test2 : "); scanf("%f %f", fM1,fM2); //notice no &}

float fnCalcAvg(float fM1, float fM2){ return((fM1 + fM2)/2);}

void fnPrint(float fAverage){ printf("\nAverage marks are :%.2f\n",fAverage);}

Enter marks for test1 and test2 : 70 80Average marks are : 75.00Function that returns more than one value - arguments are passed by referenceSample ApplicationRecursive FunctionsRecursion is a term describing functions which are called by themselves (functions that call themselves)Recursive function has two parts i.e. base case and not base caseIf not base case, the function breaks the problem into a slightly smaller, slightly simpler, problem that resembles the original problem andLaunches a new copy of itself to work on the smaller problem, slowly converging towards the base caseMakes a call to itself inside the return statementEventually the base case gets solved and then that value works its way back up to solve the whole problemUseful in mathematical calculations and in sorting of lists3334Example: factorialn! = n * ( n 1 ) * ( n 2 ) * * 1Recursive relationship: ( n! = n * ( n 1 )! ) Example: 4!4! = 4 * 3!3! = 3 * 2!2!=2*1! 1!=1*0!Base case (1! = 0! = 1)Recursive Functions: Factorial 35Factorial of 4

Factorial(4)4 *Factorial(3)3 * Factorial(2)2 * Factorial(1)1Value 1 is returned2 * 1 = 2 is returned3 * 2 = 6 is returned4 * 6 = 24 is returnedRecursive Functions: Factorial 36 #include int fnFactorial(int);

void main() {int iN=4;printf(Factorial %d is %d,n, fnFactorial(n)); }

int fnFactorial(int iN) {if(iN