Recursive Functions: Writing and Tracing A Recursive Function Terminal Case
Recursive Functions: Writing and Tracing A Recursive Function Terminal Case
int main()
{
long n;
cout << "Enter n>=0: ";
cin >> n;
cout << n << "! = "
<< fact(n) << endl;
return 0;
}
long fact(long n)
{
if(n==0) // terminal case
return 1;
else // solve a "smaller" case
return n * fact(n-1);
}
int main()
{
rec_task(4);
return 0;
}
void rec_task(int n)
{
if(n==1) // terminal case
cout << n << " GO BACK" << endl;
else
{
cout << n << " hi\n";
rec_task(n-1);
cout << n << " bye\n";
}
}
Here is a trace of a call rec_task(4):
rec_task(4): Output "4 hi"; call rec_task(3)
rec_task(3): Output "3 hi"; call rec_task(2)
rec_task(2): Output "2 hi"; call rec_task(1)
rec_task(1): Output "1 GO BACK" - done!
finish rec_task(2): Output "2 bye" - done!
finish rec_task(3): Output "3 bye" - done!
finish rec_task(4): Output "4 bye" - done!
int main()
{
int m = 123456;
print_spaced (m);
cout << endl;
print_spaced (908070605);
cout << endl;
return 0;
}
int main()
{
int m = 123456;
print_commas(m);
cout << endl;
print_commas(387);
cout << endl;
print_commas(908070605);
cout << endl;
return 0;
}
void print_commas(int n)
{
if (n < 1000) // terminal case
cout << n;
else // n >=1000 -- recursive step
{
print_commas(n/1000);
if ((n%1000)<10)
cout << ",00" << n%1000;
else if ((n%1000)<100)
cout << ",0" << n%1000;
else
cout << "," << n%1000;
}
}
int main()
{
vector<string> V;
string want;
int where;
char ans;
get_vector(V);
do {
cout << "Enter string to find: ";
cin >> want;
where = bin_search(V,want,0,V.size()-1);
if (where>=0)
cout << want << " is in cell " << where;
else
cout << want << " is not in the vector.";
cout << "\n\nAgain? (Y/N): "; cin >> ans;
}
while (ans!='n' && ans!='N');
return 0;
}
int main()
{
int n;
cout << "How many disks? ";
cin >> n;
char src = 'A', dest = 'C', aux = 'B';
move_pile(n, src, dest, aux);
cout << endl;
return 0;
}