290 likes | 526 Views
COMSATS Institute of Information Technology. Object Oriented Programming Spring - 2012. Functions OOP in C++ by Robert Lafore - Chapter#5 Kaleem Ullah kaleemullah@ciitvehari.edu.pk. Overloaded functions. Same function name Perform different operations for different types of data
E N D
COMSATS Institute of Information Technology Object Oriented ProgrammingSpring - 2012 Functions OOP in C++ by Robert Lafore - Chapter#5 KaleemUllah kaleemullah@ciitvehari.edu.pk
Overloaded functions • Same function name • Perform different operations for different types of data • different data passed • Example: same name, different number of arguments • void repchar(); //declarations • void repchar(char); • void repchar(char, int);
Overloaded functions int main() { repchar(); repchar(‘=’); repchar(‘+’, 30); return 0; }
Overloaded functions // repchar() // displays 45 asterisks void repchar() { for(int j=0; j<45; j++) // always loops 45 times cout << ‘*’; // always prints asterisk cout << endl; }
Overloaded functions • // displays 45 copies of specified character • void repchar(char ch) • { • for(int j=0; j<45; j++) // always loops 45 times • cout << ch; // prints specified character • cout << endl; • }
Overloaded functions • // displays specified number of copies of specified character • void repchar(char ch, int n) • { • for(int j=0; j<n; j++) // loops n times • cout << ch; // prints specified character • cout << endl; • }
Overloaded functions: Different kinds of arguments • struct Distance • { • int feet; • float inches; • }; Void disp( Distance ); //declarations Void disp( float );
Overloaded functions: Different kinds of arguments • struct Distance • { • int feet; • float inches; • }; Void disp( Distance ); //declarations Void disp( float );
Recursion What is recursion? Recursion See “Recursion”. Recursion If you still don't get it, see "Recursion"
Recursion Void fun() { cout<<“this is fun”<<endl; fun(); }
Recursion Void fun() { cout<<“this is fun”<<endl; fun(); } Example of program to print numbers in descending order? When will this end?
Recursion Example of program to print numbers in descending order? int print (int n) { cout<< n<<endl; if (n>1) print(--n); else return 1; } void main () { print (10); // start recursion by calling recursive function }
Properties of recursive functions • Base Case(s): condition for terminating the recursive process • Recursive Case(s): set of rules to break the problem into smaller sub-problems to reach base case • Divide the problem into smaller sub-problems • Solve the sub-problems • Combine results to get answer Sub-problems solved as a recursive call to the same function
Need of Base Case and Recursive Case int loop(int x) { return (1 + loop(x)) } • Recursive function with • no base case • not a valid recursive case • Trace Table with x=5 Problem not being divided into smaller problems – no termination loop 5 1 + loop 5 1 + loop 5 infinite loop – no termination …