Board index » cppbuilder » Recursion

Recursion


2005-11-26 09:57:45 PM
cppbuilder90
#include <iostream>
using std::cout;
using std::endl;
static int c1,c2;// Counters
void foo(const int & f )
{
++c1;
if(f>= 10 ) {
cout << "in: " << c1 << ' ' << c2 << ' ' << f << endl;
foo( f / 10 ); // recursion
}
++c2;
//Don't understand this line being called 4 times
cout << "out: " << c1 << ' ' << c2 << ' ' << f << endl;
}
int main()
{
const int n = 1776;
foo(n);
return 0;
}
// Progam Outputs
//in: 1 0 1776
//in: 2 0 177
//in: 3 0 17
//out: 4 1 1
//out: 4 2 17
//out: 4 3 177
//out: 4 4 1776
 
 

Re:Recursion

William Joseph wrote:
Quote
#include <iostream>

using std::cout;
using std::endl;

static int c1,c2;// Counters

void foo(const int & f )
{

++c1;
if(f>= 10 ) {
cout << "in: " << c1 << ' ' << c2 << ' ' << f << endl;
foo( f / 10 ); // recursion
}
++c2;
//Don't understand this line being called 4 times
cout << "out: " << c1 << ' ' << c2 << ' ' << f << endl;
}

int main()
{
const int n = 1776;
foo(n);
return 0;
}
// Progam Outputs
//in: 1 0 1776
//in: 2 0 177
//in: 3 0 17
//out: 4 1 1
//out: 4 2 17
//out: 4 3 177
//out: 4 4 1776


When foo gets called with f < 10 it doesn't call foo again but
increments c2, outputs the last line, and returns. But it returns to
the previous call to foo, increments c2, prints the last line, and
returns. And so on until it returns after the call in main.
HTH
Nate
 

Re:Recursion

"William Joseph" < XXXX@XXXXX.COM >writes:
Quote
void foo(const int & f )
{

++c1;
if(f>= 10 ) {
cout << "in: " << c1 << ' ' << c2 << ' ' << f << endl;
foo( f / 10 ); // recursion
}
++c2;
//Don't understand this line being called 4 times
cout << "out: " << c1 << ' ' << c2 << ' ' << f << endl;
}
Because ++c2 is the next statement to execute after foo(f/10)
completes.
Perhaps you intended a "return" statement after the recursive call?
--
Chris (TeamB);
 

{smallsort}