290 likes | 308 Views
Learn how function overloading allows multiple functions with the same name but different parameters in C++ programming. Explore recursion, a method where a function calls itself, to solve complex problems efficiently.
E N D
Function Overloading and Recursion CISC 1600 Dr. Karen Trovato
Function Overloading What is it? When a function has: • Same Name and • Different types of Parameters and/or • Different number of Parameters
Why do we use this? • Enables us to use the samefunctionname • Same intent • For multiple 'objects' For the moment, think of each data type (int, float, string, char) as a different kind of object
Example of Function Overloading void print(int i) { cout << "Printing int: " << i << endl; } void print(float f) { cout << "Printing float: " << f << endl; }
Example of Function Overloading (more) void print(char c) { cout << "Printing character: " << c << endl; } void print(string s) // At top of file need to have: #include <string> { cout << "Printing string: " << s << endl; }
Calling overloaded function main() { print(1); // compiler figures out parameter is an int print (3.14); // compiler figures out parameter is a float print("Hello CS2, I am ready for you!"); // string print ('x'); // char }
Calling overloaded function main() { print(1); // compiler figures out parameter is an int print (3.14); // compiler figures out parameter is a float print("Hello CS2, I am ready for you!"); // string print ('x'); // char } Printing int : 1 Printing float : 3.14 Printing string: Hello, CS2, I am ready for you! Printing character: x
Overloading function: More than 1 parameter Not only the type. Also # parameters determine which function to call void print(int var1, float var2) { cout << "Integer number: " << var1; cout << " and float number:" << var2; }
Overloaded average function in action int main(){ int numInputs; float in1, in2, in3; cout << "How many inputs?"; cin >> numInputs; if(numInputs==2) { cout << "Give me 2 numbers: "; cin >> in1 >> in2; cout << "Average: " << average(in1,in2) << endl; } else { cout << "Give me 3 numbers: "; cin >> in1 >> in2 >> in3; cout << "Average: " << average(in1,in2,in3) << endl; } return 0; } Define the two functions
Overloaded averaging function float average(float num1, float num2) { return (num1+num2)/2.0; } float average(float num1, float num2, float num3) { return (num1+num2+num3)/3.0; } // system picks the correct one
Recursion When a function calls itself: • Can be a simpler way to write a loop • Can be used as a 'divide-and-conquer' method
Original Power function int power(int base, int exponent) { int result = 1; for (int i = 1; i <= exponent; i++) { result = result * base; } return(result); // if exp == 0, we can just return 1 }
Recursive function design Must have: • Stopping case, sometimes called 'base case' • Simplified recursive calls – each new call must bring us closer to reaching base case(s)
Power calculation, another way to look at it 2 5 = 2 * 2 * 2 * 2 * 2 We can also say 2 5 = 2 * 2 4 And we know: 2 0 = 1
Alternate power (pow) function int power(int base, int expon) { if(expon>0) return (base * power(base,expon-1)); else return 1; // any base with 0 as exponent = 1 } Recursive case Stop (base) case
Factorial (N!) Example: 5! = 5*4*3*2*1 • So… • N! = N*(N-1)*(N-2)… *(1)
Basic Factorial Code int fact (int x) { int result = 1; for (int i = x; i > 1; i--) // example for x = 5: 5*4*3*2 result *= i; return(result); } Define a base and incremental part of the recursive code
Factorial (N!) – Recursive style • Base case? • 1! equals 1 • When N=1, stop multiplying! Recursive case: N*Factorial(N-1)
Put them together to get: int fact(int n) { if(n == 1) return(1); else // not really needed return(n*fact(n-1)); } main() { int num = 5; cout << num; cout << " factorial = " ; cout << fact(num) << endl; } 5 factorial = 120 Stop(base) case Recursive case
2) What does this code produce if the user enters4? 1) Identify the key parts of the recursive function int funcC(int a); int main() { int a; cout << "Enter a number: "; cin >> a; cout << funcC(a); return 0; } int funcC(int a) { if(a==0) return a; else return a + funcC(a-1); }
Recursion efficiency Reality: • Function calls are 'expensive' (take more time) • When it is a simple function that can be performed with a loop Use the loop
When is Recursion really 'worth it' ? When you are in more advanced courses But, you should know how it works And be able to build simple recursive functions. Some in examples where it is used (Not on the final, but For Your Curiosity) A glimpse into more advanced topics
When is Recursion 'worth it' ? Tree Traversal (visit all the nodes in this 'tree') void preorder(BinNodert){ if (rt== null) return; // Empty subtree - do nothing visit(rt); // Process (e.g. print) root node preorder(rt.left()); // Process all nodes in left preorder(rt.right()); // Process all nodes in right } Even though you can hardly read this code now, you can still tell it is recursive
Fractals Koch Snowflake A fractal is a never ending pattern that repeats itself at different scales. This property is called “Self-Similarity.” Fractals are extremely complex, sometimes infinitely complex - meaning you can zoom in and find the same shapes forever. Amazingly, fractals are extremely simple to make. A fractal is made by repeating a simple process again and again.
Fractals - Geometry. Sierpinski Triangle Make an equilateral Triangle drawAtriangle( ) { If connecting-lines smaller than X return; Make 4 triangles by connecting lines from adjacent sides For each outer triangle, drawAtriangle( ) } Sierpinski triangle You decide when to stop
Fractals - Geometry. Sierpinski Triangle Colorize: Alternate fill colors Left: By Beojan Stanislaus, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=8862246