Void logic problems

void printNumber(int a){
if(a<10) cout << a <<" "; return;
printNumber(a/10);
cout <<a/10<<" ";
}
int main() {
//printNumber:
printNumber (19683);
cout << endl;
return 0;
}
Last edited on
I have to Write a recursive function printNumber to print a number, digit by digit, separated by spaces, forwards. I dont know whats wrong with this code, it compiles but doesnt show anything
C++ doesn't care what you put on a line. What matters is code blocks and semicolons.

Therefore this:

 
if(a<10) cout << a <<" "; return;


is the same as this:

1
2
3
4
if(a < 10)
    cout << a << " ";

return;


That is... you return after that first cout statement, regardless of whether or not it printed everything.

If you want multiple commands in an if block, you need to encase it in braces:

1
2
3
4
5
if(a < 10)
{
  cout << a << " ";
  return;
}
Topic archived. No new replies allowed.