1 / 40

EKT120 COMPUTER PROGRAMMING

EKT120 COMPUTER PROGRAMMING . Functions (Part 2) Dr. Nik Adilah Hanin Bt. Zahri adilahhanin@unimap.edu.my. Recaps… Functions Prototype. #include < stdio.h > /* function prototype */ double product(double x, double y); int main() { double var1 = 3.0, var2 = 5.0; double ans ;

michon
Download Presentation

EKT120 COMPUTER PROGRAMMING

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. EKT120COMPUTER PROGRAMMING Functions (Part 2) Dr. NikAdilahHanin Bt. Zahri adilahhanin@unimap.edu.my

  2. Recaps… Functions Prototype #include <stdio.h> /* 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 prototype • Function prototype is a declaration; indicates the function exists • Should have function name, return type and parameter • Placed before main () • Tells compiler that the function will be defined later

  3. Recaps… Functions Call #include <stdio.h> /* 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; } • Consists of a function name followed by an argument expression list enclosed in parentheses • Function call hasthe following form: <function_name> (exp, exp ...) • main is the calling function • product is the called function

  4. Recaps… Functions Definition #include <stdio.h> /* 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 function • Function definition hasthe following form: <return_type> <function_name> (arg_typearg_name, ...) { … statements … }

  5. Recaps… Number, order and type of parameter • Number, order and type of parameters in the argument list of a function call and function definitionMUST match. int sum(int, int);//function prototype int sum(int num1, int num2) //function definition sum(x,y);//function call

  6. Recaps … Functions that RETURN a value //This program sums up two numbers #include <stdio.h> int sum(int,int); //function prototype int main(){ intx,y,result; printf(“Enter x and y: ”); scanf(“%d %d”, &x, &y); result = sum(x,y); //function call printf(“Sum is : %d”,result); return 0; } intsum(int num1, int num2){ //function definition int add; add = num1+num2; return add; }

  7. Recaps… Functions that DO NOT RETURN a value //This program sums up two numbers #include <stdio.h> void sum_print(int, int); //function prototype int main(){ intx,y; printf(“Enter x and y: ”); scanf(“%d %d”, &x, &y); sum_print(x,y); //function call return 0; } void sum_print(int num1, int num2){ //function definition int add; add = num1+num2; printf(“Sum is: %d”,add); }

  8. Recaps… Global and Local Variables //Compute Area & Perimeter of a circle #include <stdio.h> 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; } • Global variable • These variables are declared outside all functions, at the top of a source file. • Declarations not placed in any functions • Life time of a global variable is the entire execution period of the program. • Can be accessed by any function defined below the declaration

  9. Recaps… Global and Local Variables //Compute Area & Perimeter of a circle #include <stdio.h> 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; } • 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.

  10. Today’s Outline • Passing parameters in functions :- Pass by value • Functions that return more than one value and its sample application • Passing parameters in functions :- Pass by reference and its application • Recursive function

  11. Sample Application • Write a C program that reads item code and quantity, then calculates the payment. Use functions: • fnMenu – print item code menu • fnDeterminePrice – determine price based on item code • fnCalc-calculate payment • fnPrintResult– print payment What argument names do I want to feed in as parameters and what to return?? Think!! Which function returns no value and which function returns a value.

  12. Sample Application: Local Variables #include <stdio.h> void fnMenu(); float fnDeterminePrice(int); float fnCalc(float,int); void fnPrintResult(float); int main() { intiCode,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; }

  13. Sample Application: Local Variables #include <stdio.h> void fnMenu(); float fnDeterminePrice(int); float fnCalc(float,int); void fnPrintResult(float); int main() { intiCode,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"); }

  14. Sample Application: Local Variables #include <stdio.h> void fnMenu(); float fnDeterminePrice(int); float fnCalc(float,int); void fnPrintResult(float); int main() { intiCode,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"); } OUTPUT: Code Item Price 1 Papaya 1.00 2 Melon 2.00 3 Durian 3.00 Others 4.00

  15. Sample Application: Local Variables #include <stdio.h> void fnMenu(); float fnDeterminePrice(int); float fnCalc(float,int); void fnPrintResult(float); int main() { intiCode,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; } OUTPUT: Code Item Price 1 Papaya 1.00 2 Melon 2.00 3 Durian 3.00 Others 4.00 Enter item code and quantity: 1 3

  16. Sample Application: Local Variables float fnDeterminePrice(intiItemCode) { 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; } #include <stdio.h> void fnMenu(); float fnDeterminePrice(int); float fnCalc(float,int); void fnPrintResult(float); int main() { intiCode,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; }

  17. Sample Application: Local Variables #include <stdio.h> void fnMenu(); float fnDeterminePrice(int); float fnCalc(float,int); void fnPrintResult(float); int main() { intiCode,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; } float fCalc(float fItemPrice, intiQuality) { float fTotal; fTotal = fItemPrice*iQuantity; return fTotal; }

  18. Sample Application Local Variables #include <stdio.h> void fnMenu(); float fnDeterminePrice(int); float fnCalc(float,int); void fnPrintResult(float); int main() { intiCode,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 fnPrintResult(float fPayment) { printf("Payment is %.2f\n", fPayment); } OUTPUT: Code Item Price 1 Papaya 1.00 2 Melon 2.00 3 Durian 3.00 Others 4.00 Enter item code and quantity: 1 3 Payment is 3.00

  19. Sample Application: Global Variables 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; } } #include <stdio.h> void fnMenu(); void fnDeterminePrice(); void fnCalc(); void fnPrintResult(); intiCode,iQty; float fPriceUnit,fPay; int main() { fnMenu(); printf("Enter item code and quantity:"); scanf("%d %d", &iCode,&iQty); fnDeterminePrice(); fnCalc(); fnPrintResult(); return 0; }

  20. Sample Application: Global Variables #include <stdio.h> void fnMenu(); void fnDeterminePrice(); void fnCalc(); void fnPrintResult(); intiCode,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; }

  21. Sample Application: Global Variables #include <stdio.h> void fnMenu(); void fnDeterminePrice(); void fnCalc(); void fnPrintResult(); intiCode,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); } OUTPUT: Code Item Price 1 Papaya 1.00 2 Melon 2.00 3 Durian 3.00 Others 4.00 Enter item code and quantity: 1 3 Payment is 3.00

  22. Pass by Value • If a parameter is passed by value, then the value of the original data is copied into the function’s parameter (scope: local variable(s)) • In other words, it (i.e. local variable) has its own copy of the data • Changes to copy do not change original data • During program execution, it (i.e. local variable) will only manipulate the data stored in its own memory space

  23. Pass by Value (Example) #include <stdio.h> void fnFun1(int,int); //function prototype int main() { intiA=5, iB=10; printf("Before function1\n“); printf(" iA = %d iB = %d\n”, iA,iB); fnFun1(iA, iB); //function call printf("\nAfter function1\n“); printf(" iA = %d iB = %d\n”, iA,iB); return 0; } void fnFun1(intiAA,intiBB) //function definition { ++iAA; --iBB; printf("\n\nInside fnFun1\n)"; printf(“iAA = %d iBB = %d\n”, iAA,iBB); }

  24. OUTPUT Before fnFun 1 iA = 5 iB = 10 Inside fnFun 1 iAA = 6 iBB = 9 After fnFun 1 iA = 5 iB = 10 Pass by Value (Example) #include <stdio.h> void fnFun1(int,int); //function prototype int main() { intiA=5, iB=10; printf("Before fnFun1\n“); printf(" iA = %d iB = %d\n”, iA,iB); fnFun1(iA, iB); //function call printf("\nAfter fnFun1\n“); printf(" iA = %d iB = %d\n”, iA,iB); return 0; } void fnFun1(intiAA,intiBB) //function definition { ++iAA; --iBB; printf("\n\nInside fnFun1\n)"; printf(“iAA = %d iBB = %d\n”, iAA,iBB); }

  25. Functions that Return More than One Value • When we talk about functions that return more than one value it refers to passing arguments by reference • passes addresses (references), NOT value or data • allows direct manipulation • changes will affectoriginal data • There are cases where you need to manipulate the value of an external variable from inside a function, thus we pass the value by reference

  26. Pass by Reference • A function’s parameter that receives the location (memory address) of the corresponding actual variables • When we attach * (star) after the arg_type in the parameter list of a function, then the variable following that arg_type is passed by reference • It stores the addressof the actual variable, NOT the value • During program execution to manipulate the data, the address stored will have direct control to the memory space of the actual variable • Syntax: • 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);

  27. Pass by Reference • Pass by reference is useful in two situations: • when you want to return more than one value from a function • when the value of the actual parameter needs to be changed

  28. Pass by Reference (Example) #include <stdio.h> void fnFun1(int, int*); //function prototype int main(void) { intiA=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(intiAA,int*iBB)//function definition { ++iAA; --*iBB; printf("\n\nInside fnFun1\n”); printf(“iAA = %d iBB = %d”,iAA,*iBB); }

  29. OUTPUT Output Before fnFun1 iA=5 iB = 10 Inside fnFun1 iAA = 6 iBB = 9 After fnFun1 iA = 5 iB = 9 Pass by Reference (Example) #include <stdio.h> void fnFun1(int, int*); //function prototype int main(void) { intiA=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(intiAA,int*iBB)//function definition { ++iAA; --*iBB; printf("\n\nInside fnFun1\n”); printf(“iAA = %d iBB = %d”,iAA,*iBB); }

  30. Sample Application • Write a C program that calculates and prints average of 2 test marks. • Your program should have functions: • fnReadMarks – read 2 test marks • fnCalcAvg – calculate average of two test marks • fnPrint - print average

  31. #include <stdio.h> 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); } Sample Application Function that returns more than one value - arguments are passed by reference

  32. #include <stdio.h> 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); } Sample Application Function that returns more than one value - arguments are passed by reference Enter marks for test1 and test2 : 70 80 Average marks are : 75.00

  33. Recursive Functions • Recursion 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 case • If not base case, the function breaks the problem into a slightly smaller, slightly simpler, problem that resembles the original problem and • Launches a new copy of itself to work on the smaller problem, slowly converging towards the base case • Makes a call to itself inside the returnstatement • Eventually the base case gets solved and then that value works its way back up to solve the whole problem • Useful in mathematical calculations and in sorting of lists

  34. Recursive Functions: Factorial • Example: factorial n! = n * ( n – 1 ) * ( n – 2 ) * … * 1 • Recursive relationship: ( n! = n * ( n – 1 )! ) • Example: 4! 4! = 4 * 3! 3! = 3 * 2! 2!=2*1! 1!=1*0! • Base case (1! = 0! = 1)

  35. Recursive Functions: Factorial • Factorial of 4 4 * 6 = 24 is returned Factorial(4) 3 * 2 = 6 is returned 4 * Factorial(3) 3 * Factorial(2) 2 * 1 = 2 is returned 2 * Factorial(1) Value 1 is returned 1

  36. Recursive Functions: Factorial • #include <stdio.h> • intfnFactorial(int); • void main() • { • intiN=4; • printf(“Factorial %d is %d“,n, fnFactorial(n)); • } • intfnFactorial(intiN) • { • if(iN <= 1) //base case • return 1; • else • return ( iN * fnFactorial(iN-1)); • } • Call function name itself

  37. Recursive Functions(Fibonacci Series) • Example : Fibonacci series 0, 1, 1, 2, 3, 5, 8... • Each number is the sum of two previous numbers • Example of a recursive formula: fib(n) = fib(n-1) + fib(n-2) Fibonacci series of 3: fib(3) = fib(2) + fib(1) fib(2) = fib(1) + fib(0) fib(1) = 1 fib(0) = 0

  38. f( 3 ) return f( 2 ) + f( 1 ) return f( 1 ) f( 0 ) return 1 + return 1 return 0 Recursive Functions(Example) • Diagram of Fibonacci function: = 2 = 1 = 1

  39. Recursive Functions(Example) • Sample code for fibonacci function long fnFibonacci( long lN ) { if ( lN == 0 || lN == 1 ) //base case return lN; else return fnFibonacci(lN–1)+ fnFibonacci(lN–2); }

  40. End Functions (2) Q & A!

More Related