Transcript Lecture 4
RECURSION AND RECURSIVE FUNCTIONS
•
Main calls another function…..normal
•
A function calls another function2….normal
•
A function calls itself ?! Possible?? YES
•
A recursive function is one that call itself.
RECURSION AND RECURSIVE FUNCTIONS
•
An example to print numbers counting down:
Void Print( int counter)
{
if(counter == 0)
return;
else
{
cout <<counter<<endl;
Print(--counter);
return;
}
}
FINDING FACTORIAL RECURSIVELY
5!
Final value=120
5!
5!=5*24=120 returned
5*4!
5*4!
4!=4*6=24 returned
4*3!
4*3!
3!=3*2=6 returned
3*2!
3*2!
2!=2*1=2 returned
2*1!
2*1!
1
1
1
FINDING FACTORIAL RECURSIVELY
//Recursive factorial Function
Int factorial(int);//prototype
int main()
{
int num;
cout<<“enter a positive integer:”;
cin>>num;
cout<<“factorial=“<<factorial(num);
return 0;
}
int factorial(int n)
{
if ( n <= 1) //the base case
return
1;
else
return n * factorial (n - 1);
}
FUNCTION OVERLOADING
Functions with same name and different parameters or return
data type
Should perform similar tasks
I.e., function to square int and function to square float
int square( int x) {return x * x;}
float square(float x) { return x * x; }
• A call-time c++ complier selects the proper function by
examining the number, type and order of the parameters
FUNCTION OVERLOADING
• An overloaded function appears to perform different activities
depending on the kind of data sent to it.
• It performs one operation on one kind of data but another operation
on a different kind.
EXAMPLE 1
#include <iostream>
Using namespace std;
Void repchar();
//prototype
Void repchar(char);
Void repchar(char, int);
int main()
{
repchar(); //First
repchar(‘=’); //Second
repchar(‘+’,30); //Third
Return 0;
}
Void repchar()
// first
{
For (int j=0; j<45; j++)
cout<<‘*’;
cout<<endl;
}
Void repchar (char ch)
// Second
{
For (int j=0;j<45; j++)
cout<<ch;
cout<<endl;
}
Void repchar(char ch,
{
for(int j=0;j<n; j++)
cout<<ch;
cout<<endl;
}
int n)
//Third
This program prints out three lines of characters. Here’s the output:
*********************************************
=============================================
++++++++++++++++++++++++++++++
FUNCTION OVERLOADING
• The program contains three functions with the same name.
• There are three declarations, three function calls, and three function
definitions.
• The compiler uses the function signature—the number of
arguments, and their data types—to distinguish one function from
another.
•
FUNCTION OVERLOADING
void
repchar();
which takes no arguments, describes an entirely different function than
the declaration
void
repchar(char);
which takes one argument of type char, or the declaration
void
repchar(char, int);
which takes one argument of type char and another of type int.
EXAMPLE 2
void add(int x, int y);
void add(double x, double y);
int main()
{
add(10,20);
add(10.4,20.4);
return(0);
}
/////////////////////////////
void add(int x, int y)
{ cout<< x+y; }
void add(double x,double y)
{ cout<<x+y; }