C programming | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

C programming

void main (){ int a =3; fun(a); } void fun(int n){ if(n>0){ fun(--n); printf("%d ",n); } } Why the output : 012

3rd May 2023, 6:53 AM
Test Bug
Test Bug - avatar
4 Answers
+ 5
FIRST READ THIS: Recursive functions. What an interesting part of programming. Look: in void main you call the function with n = 3 Now you call fun: void fun(3) { if (n > 0 (true)) { fun(--n); // n now is 2 prinf(“%d”, n); // this line isn’t executed yet because you called fun in the previous line } } //NOW n = 2 void fun(2) { if (n > 0 (true)) { fun(--n); // n now is 1 prinf(“%d”, n); // this line isn’t executed yet because you called fun in the previous line } } void fun(1) { if (n > 0 (true)) { fun(--n); // n now is 0, but when n reached if block it was 1. Calls fun(0) prinf(“%d”, n); // this line isn’t executed yet because you called fun in the previous line } } void fun(0) { if (n > 0 (false)) { // this isn’t executed } } Wait a moment I’m continuing this in the next message
3rd May 2023, 7:08 AM
Ugulberto Sánchez
Ugulberto Sánchez - avatar
+ 5
LAST READ THIS: Now that void fun(0) didn’t continued the recursion, the printf line of each fun() call is executed. void fun(1) { if (n > 0 (true)) { fun(--n); // n now is 0. This line is already executed. prinf(“%d”, n); // it prints the value of n, 0. It doesn’t print a new line. Now the output is 0. } } void fun(2) { if (n > 0 (true)) { fun(--n); // n now is 1. This line is already executed. prinf(“%d”, n); // it prints the value of n, 1. It doesn’t print a new line. Now output is 01. } } void fun(3) { if (n > 0 (true)) { fun(--n); // n now is 2. This line is already executed. prinf(“%d”, n); // it prints the value of n, 2. It doesn’t print a new line. So the output is 012. } } // END OF RECURSION Output of the code: 012
3rd May 2023, 7:12 AM
Ugulberto Sánchez
Ugulberto Sánchez - avatar
+ 1
Thank you , for answer
3rd May 2023, 2:50 PM
Test Bug
Test Bug - avatar
0
The code use the stack memory , by branches instructions
3rd May 2023, 2:43 PM
Test Bug
Test Bug - avatar