0
I am beginner for C++ and confused with the output.
Why is the output 01234 instead of 43210? #include <iostream> using namespace std; void func(int x){ if(x>0){ func(--x); cout<<x; } else return; } int main() { func(5); return 0; }
4 Antworten
+ 2
Marven Mendoza just change two lines in func as below and output will change:
cout << x; //first print value of x
func(--x); // after printing value 5 first on cout, again function is called for 4 and so on....
Now coming to original code having output as 01234...Refer below:
From main, func is called and x is 5... in func x is more than 0 so, again func is called with 4 (--x)..Note that yet cout << x is not executed for func() with x=5 and func for x=4 is called..so, all this function call happens till x is 1... Now, first x is 0 executed for cout and at last x as 4..so, output is 01234
feel free to ask if you have any query
+ 3
that is kept in stack by compiler.. for example, in five line of code, compiler do not go to line 3 till the line 2 is not fully executed....
0
Ketan Lalcheta, I have a question, how something is printed in the code that he mentioned in his post. I mean, in if statement func is called first before cout and how still cout is executed,