All the trouble comes from the fact that your output didn't introduce any separation in values cout << i;
prints.
You actually getting the following at first:
4, 3, 2, 1
We got this out of these two statements:
// ...
cout<< i;
rek(i-1);
// ...
Where each call to the rek(i)
prints its current i
and then calls rek(i-1)
, which in turn before proceed through the function body has to print its i-1
and then call rek((i-1)-1)
... And so on, until it hits the i < 0
case.
The remaining part is brought to you by the output of 1
one time, 2
two times, 3
three times, and 4
four times. All because of the for
loop:
for (int k=0; k < i; k++) // print the value of i, i times
cout << i;
Thus, you essentially have the following:
4
3
2
1 // We hit base case on next rek() call, so no print out of there
1 // Here the for loop comes in
2 2
3 3 3
4 4 4 4
By the way, please note that the placement of brace(s) in your code is somewhat counterintuitive.