just a question

hey guys i was practicing c++ i just want to ask if this type of program is an example of recursion?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include<iostream>
using namespace std;
int recursive(int base,int total);
int main()
{

	unsigned int base,total=1, expo;
	cout<<"Enter base : ";
	cin>>base;
	cout<<"Enter exponent : ";
	cin>>expo;
	for(int i=1; i<=expo; i++)
	{
		total=recursive(base,total);
	}
	cout<<total; 
}
int recursive(int base,int total)
{
	
	return total*=base;
	
}
No. That's a example of a function called many times into a loop for.

An example of a recursive function is like that:

1
2
3
4
5
6
7
8
int recursive(int base,int total)
{
	if (total <= 1)
            return total;

	return (base * recursive(base, total -1);
	
}


A recursive function is a function that is called by itself...
hey i have a question how does this line work out
//(base * recursive(base, total -1);//
im confuse because you have 2 arguments first is base and second is total which is decremented by 1 everytime you make a recursive call, how does that work do the arguments gets add or multiply maybe? i dont know please
Imagine you wanna know the result of 5^3.

So, you use:

 
recursive(5, 3);


In the first time the argument's values is:

1
2
base = 5;
total = 3;


As total > 1, the function doesn't returns. So, it calls itself again, but now it pass:

1
2
base = 5;
total = 2;


The recursive function does it until total <=1.

So, the last occurence of the function is when total == 1. Then, it return the base. But when it was called, we got:

 
 return (base * recursive(5, 1));


As the base is returned, we got:
return( base * base)

Which in turn, it wil return for itself, but now:

return (base * (base * base))

And the function does it until the first call, when it return the value for you.

I don't know if I could explain clearly, but that's it. :)
no i understand it now thanks .
Topic archived. No new replies allowed.