can pls anyone tell me why this program doesn't work?

#include <iostream>
#include <stdlib.h>

using namespace std;
void printnum ( int begin);

int main()
{
printnum (0) ;


system("PAUSE");
return 0;
}

void printnum ( int begin )
{
cout<< begin;
if ( begin < 9 )
{
printnum ( begin++);
}
cout<< begin;
}
As far as I can tell, it does work. That is, the program should compile without errors and when it runs its behavior should be fully defined.
Maybe you and the computer simply have different definitions of "to work". What's the output you're expecting?
Function printnum makes use of recursion.

Unfortunately, this line: printnum ( begin++); calls the function with exactly the same parameter. That means each call is identical and the recursion never terminates.

The postincrement operator begin++ does not add one to 'begin' until after the function call.

I suspect what you really want is the pre-increment version, ++begin, like this:

1
2
3
4
5
6
7
8
9
void printnum (int begin)
{
    cout << begin;
    if (begin < 9)
    {
        printnum (++begin);
    }
    cout<< begin;
}
All I know is that system("pause"); may/will give some kind of problems, rather use cin.get;
Topic archived. No new replies allowed.