60 likes | 79 Views
ICOM 4015 Advanced Programming. Lecture 8 Procedural Abstraction V Reading: Chapter 3. Prof. Bienvenido Velez. Procedural Abstraction V Outline. Round up recursion Fibonacci numbers exponential vs. linear processes Function overloading. Example 1 Fibonacci Numbers. // fibonacci.cc
E N D
ICOM 4015 Advanced Programming Lecture 8 Procedural Abstraction V Reading: Chapter 3 Prof. Bienvenido Velez ICOM 4015
Procedural Abstraction V Outline • Round up recursion • Fibonacci numbers • exponential vs. linear processes • Function overloading ICOM 4015
Example 1Fibonacci Numbers // fibonacci.cc // Iterative and recursive algorithms for computing Fibonacci numbers ... // Auxiliary Functions long recFibonacci(long n) { if (n==0) { return 0; } else if (n==1) { return 1; } else { return (recFibonacci(n-1) + recFibonacci(n-2)); } } long iterFibonacci(long n) { if (n==0) { return 0; } else if (n==1) { return 1; } long F0 = 0; long F1 = 1; long FN; for (long i=1; i<n; i++) { FN = F0 + F1; F0 = F1; F1 = FN; } return FN; } [bvelez@amadeus] ~/icom4015/lec07 >>fibonacci Please enter a positive number (or negative to end): 3 Recursive: F(3) = 2 Iterative: F(3) = 2 Please enter a positive number (or negative to end): 4 Recursive: F(4) = 3 Iterative: F(4) = 3 Please enter a positive number (or negative to end): 8 Recursive: F(8) = 21 Iterative: F(8) = 21 Please enter a positive number (or negative to end): ICOM 4015
Iteration vs. RecursionSummary • Recursion is as expressive as iteration • Iteration can yield faster code • less duplication of work • less function call overhead • Recursion can yield cleaner code ICOM 4015
Function OverloadingExample - Int/Float Functions int intSqr (int x) { return x * x } long longSqr(long x) { return x * x; } float floatSqr(float x) { return x * x } Without overloading int sqr (int x) { return x * x } long sqr(long x) { return x * x; } float sqr(float x) { return x * x } With overloading ICOM 4015
Function OverloadingSummary • Related functions can be grouped under a common name • Overloaded functions may have different return types, but must have different parametters. • The importance of overloading will become clearer when we get into classes and object-oriented programming ICOM 4015