+ 9
Why the output of this code is 012345, but not 543210?
#include <stdio.h> int main() { int loopy(int i){ if(i==0){ printf("%i",i); } else{ loopy(i-1); printf("%d",i); } } loopy(5); return 0; }
4 Answers
+ 5
Hello, How are you? Well, the problem is that you are using recursion.
For example, considering i = 5, it will happen:
"i == 0? No, so the else staments will be proccessed.
The first stament is loopy(i-1). It will call the function again.
Calling the function again, my i is 4, because 5 - 1 is equals 4.
Now the same thing will happen, 4 == 0? No! So the else staments will processed and the first line is loopy(i-1).
It will repeat with i = 3, 2 and 1. When i be equals 0, it will print.
After it, all called functions of loopy will be finished by stack order (last in first out), in other words, the last else stament (print("%d", i)) following 1, 2 , 3 , 4 and 5".
Well, it is happening. I am sorry because I didn't get to explain it clairly, but the problem is the recursion.
+ 6
Just a little additional note to what Gabriel said, move the "loopy" function outside the main function, but first you follow his suggestion before you move it : )
+ 6
This is an interesting 5-question challenge quiz.
Just like what Gabriel has explained, the reason output is 012345 is because the recursive is before print index.
Therefore the whole logic is like a nested if else statement.
If 5 is 0
__print 0
Else
__if 4 is 0
____print 0
__else
____if 3 is 0
______print 0
____else
______if 2 is 0
________print 0
______else
________if 1 is 0
__________print 0
________else
__________if 0 is 0
____________print 0
__________else
____________...
__________print 1
________print 2
______print 3
____print 4
__print 5
+ 2
So, for your code prints what you would like, just you change the first and second else staments of place, such as:
int loopy(int i) {
if (i == 0) {
printf("%i", i);
}
else {
printf("%i, i);
loopy(i - 1);
}
}