c++ - "print 1 to n" function prints 1 twice -
void printint(int n){ if(n==1) cout<<1<<" "; else printint(n-1); cout<<n<<" "; }
the output is
1 1 2 3....n
i'm writing out actual steps of function on piece of paper don't how printing 1 in console (visual studio 2010). past hw solutions strictly understanding how works.
you need braces:
if(n==1) { cout<<1<<" "; } else { printint(n-1); cout<<n<<" "; }
or else second cout
gets run when n==1
. strictly speaking braces around first cout
aren't required, style in case.
editorial note: problem solved stepping through function in debugger.
Comments
Post a Comment