Control Flow of if statement and function calls - c

I am getting the output ' 0,1,2,0'. Please someone help me how this function call is working. I have this doubt that after decrementing n, if statement will not execute as it will not be greater than 0. Thus there will be no output. But the result is something else.
#include <stdio.h>
void fun(int);
int main(void)
{
int a=3;
fun(a);
return 0;
}
void fun(int n)
{
if(n > 0)
{
fun(--n);
printf("%d,", n);
fun(--n);
}
}

You're calling fun() from within itself, both before and after the printf(). So you're going to see the printf from the deepest invocation of fun() first.
#ForceBru is absolutely right, you can - and, if you want to be a programmer, need to be able to - trace the code out in your head or on paper. Here's an example.
on the first invocation of fun(), as is 3. 3 > 0 so fun() is called again, with the _pre_decremented value ( so n is set to 2, and 2 is passed to fun().
The whole process happens again. 2 > 0 so --n or 1 is passed to fun.
In the 3rd invocation deep, n is 1. That's still greater than 0, so fun(--n) is run again, with n being predecremented to 0.
Now within the fourth invocation of fun(), n is finally 0. Nothing happens.
Third invocation, first fun() returns. Rember, this fun() invocation's n was 1, but it's been decremented to 0 by this time. 0 is printed. n is then decremented again ( to -1, it being a signed int) and fun(-1) is called, but since -1 > 0 is false, nothing happens. The third invocation returns.
The second invocation was passed 2 but has since decremented to 1. 1 is printed and then fun(--n) turns into fun(0) and the next fun() invcocation isfun(-1)and also does nothing. The second invocation offun()` returns.
Finally, the first invocation of fun(), the one from main, is executing agian. It started with 3, but decremented to 2. A 2 is printed. Then --n, or 1, is passed to fun() one last time. 1>0 so fun() is invoked again, and outputs--1or 0 just like it did the first time it was passed a 1. The first invocation's recursive calls tofun()then finish, and the program finishes, having output a0, 1, 2, 0`.
Do walk through that yourself on paper, as recursive functions can be pretty confusing. I didn't understand why you got that output myself until I walked through the code, and I've been programing in c for 20 years!

Related

Stacks and Recursion in C

#include <stdio.h>
void fun(int a) {
if (a > 0) {
fun(a / 10);
printf("%d", a % 10);
fun(a / 10);
}
}
int main() {
fun(12345);
return 0;
}
Here, as the function is calling itself at the start of the if block, shouldn't it print nothing, it will keep calling itself until the function argument becomes zero?
But instead, the output is 1213121412131215121312141213121
shouldn't it print nothing, it will keep calling itself until the
function argument becomes zero?
If I have understood correctly then you are right. The function will not output anything until a is equal to 0.
void fun(int a){
if(a > 0){
fun(a/10); // calls itself.
printf("%d",a % 10);
//...
Thus for this number 12345 the first output will be the most significant digit 1.
As the function calls itself twice
void fun(int a){
if(a > 0){
fun(a/10);
printf("%d",a % 10);
fun(a/10);
}
}
then for each digit of the number except the most significant digit the previous and next digits will be outputted twice on the left and on the right sides. For example
1 2 1
1 2 1 3 1 2 1
1 2 1 3 1 2 1 4 1 2 1 3 1 2 1
and so on.
I used embedded spaces for make the output more clear.
After the inner most function of the recursion has been finished (a>0) is evaluating to false it will execute the print statement and returns to the calling function.
The caller will print it's a%10 value and so on.
Not sure why you call fun(a/10) twice but this is why the output is printed twice.
Yuo do not need the second call
void fun(int a)
{
if(a)
{
fun(a/10);
printf("%d", a % 10);
}
}
https://godbolt.org/z/zWf64jjWe
Remember that it will not work for negative numbers.
The function attempts to print the decimal conversion of a but the second recursive call produces extra output.
The function will indeed produce no output for values below 10, which might not be the expected behavior. Without the second recursive call the output would be 1234.
You should use this instead:
void fun(int a) {
if (a >= 10)
fun(a / 10);
printf("%d", a % 10);
}
Note however that the above function only works for positive values.
You can implement this is 3 different ways:
Either make the recursive call before you start printing. If so the printing starts from the deepest level of recursion. This is very inefficient but ensures that you get the expected order 1,2,3... Generally, a recursive function that doesn't have the recursive call at the very end is an incorrect solution to any problem.
Or make the recursive calls after you print. This would lead to everything getting printed backwards as you've currently written the function. However, a recursive function with the call at the end, so-called "tail call", can sometimes get optimized into nearly as efficient code as a loop. You could probably do this here too, if you come up with a different algorithm.
Or you can implement it as a loop. Super-fast, super-readable, no risk of excessive stacking, no overhead. This is the correct solution in some 99% of all cases and the correct solution in 100% of all cases a beginner might be facing.

Can someone explain output of this C program? [duplicate]

This question already has answers here:
unexpected output in C (recursion)
(3 answers)
Closed 4 years ago.
#include <stdio.h>
int main()
{
static int i = 5;
if (--i)
{
main();
printf("%d\n", i); // will this line executes ?
}
return 0;
}
Output:
0
0
0
0
does code below main(); printf statement instructions is placed to stack every time when main recursive calls happens and executed while terminated from this program?
i is reduced by successive calls to main until zero is reached.
Then printf is called for each level of recursion.
(Note that the behaviour of calling main from itself is well-defined although ill-advised in C, in C++ the behaviour is undefined.)
if (--i)
This will evaluate true the first time (--i == 4). The code recurses into main(). (Recursion: A function calling itself.)
As i is static, it will retain its value of 4 (as opposed to an automatic variable, which would be initialized to 5 again). The if (--i) in this second execution of main() will again be true (evaluating to 3), and will again call main() (for a third execution of the function).
The same for --i == 2 and --i == 1, for four executions of main() (including the first, non-recursive one) total that are evaluating the if condition to true.
The next recursion will evaluate the if condition to --i == 0, and thus false. Skipping the if clause, the function call will just return. i is zero at this point, and -- being static, i.e. only one persistent i for all instances of main() -- will remain at that value.
The main() call one level up the stack -- the one that evaluated --i == 1, then called main() and was waiting for it to return -- will now continue with the statement after the call to main(), and printf() the current value of i... which is 0.
The same happens three more times (for a total of four) until the top-most main() returns. You get four times the current value of i, which is 0.
Note that calling main() from your program is allowed in C, but not in C++. This is specifically for calling main() recursively; for other functions, it is allowed in either language.
(--i) will decrease the value of i to 4 when it is called for the first time and it will continue the decrement of i until (i==0) due to recursion.
Since you have declared the variable i with static keyword and hence a single memory is allocated to it and all the changes are reflected back to it

Understanding recursion function call

Where will the value of n be stored after first call to factorial()?
When n=1 then return 1 is sent, why doesn't res becomes equal to 1 in main function?
#include<stdio.h>
int factorial(int n)
{
if(n<=1)
return 1;
else
return n*factorial(n-1);
}
int main()
{
int res =factorial(3);
printf("%d",res) ;
}
The run-time stack will have four functions in total: main(), factorial(3), factorial(2), and factorial(1). Each of these gets its own variable space. There are three instances of the variable n, one for each call to factorial.
When factorial(1) returns 1, that value isn't returned to main(), because main() is not what called it: factorial(2) called it. That instance performs the operation 2*1 and returns 2. The caller of that instance is factorial(3), which receives the 2, performs the operation 3*2, and returns a value of 6 to its caller, main().
Does that help clear it up? If not, I have two suggestions:
(1) Search this topic on StackOverflow and the internet in general; there are plenty of detailed walk-through examples of factorial.
(2) Insert print statements to trace the flow of data and execution. Within factorial, separate the computation and the return, so you can put a print in between:
catch = factorial(n-1)
result = n * catch
print n, catch, result
return result
Each time a function is called, its parameter and local variables are pushed onto the stack. In the case of a recursive function, there will be a set of the variables on the stack for each active invocation of the function.
In this example, the first call to factorial has n set to 3. Within the function, factorial is called again, this time with n set to 2. It calls itself one more time with n set to 1. In this last call, it returns a value of 1. This gets returned to the prior invocation where n is 2, which then returns 2 * 1 which is 2. This value is returned to the first invocation where n is 3 and returns 3*2 which is 6 back to main.
So the call stack looks like this:
main
|--> factorial(n==3)
|--> factorial(n==2)
|--> factorial(n==1)
return 1
return 2*1
return 3*2
print 6
n is not stored in the way of global or static variables - it's stored on the stack. Calling a function with arguments the arguments are being pushed on the stack.
See what's happening when your running your program:
factorial(3) gets called (in main)
As n is not equal or smaller to 1 factorial(2) is called and the result will be multiplied by n (is 3).
As n is not equal or smaller to 1 factorial(1) is called and the result will be multiplied by n (is 2).
As n is now equal or smaller to 1 the function returns 1
factorial(2) returns 1*2
factorial(3) returns 2*3
res will be 6

Recursion on Recursion in C

I have a hard time understanding the part of the code where the program is recalling on the recursion multiple times.
The output is 1233333. If I change the recursion line to just fun (++count;). the output is 123, which I understand the logic, but when you start calling on the recursion multiple times, I become lost.
#include <stdio.h>
int fun(int count) {
printf("%d\n", count);
if(count < 3) {
fun(fun(fun(++count)));
}
return count;
}
int main()
{
fun(1);
return 0;
}
First function calls 1 as the argument and 1 is printed
then it enters the if statement
The count gets incremented
fun(fun(fun(2)))
2 is printed and and enters if and
count is incremented to 3
fun(fun(fun(3))))
3 is printed.But this time it is doesn't enter the if instead 3 is returned
return(3)
and 3 is returned to the previous nested calls
fun(fun(3))
this happens 4 times
and hence the output
1233333
fun(fun(fun(++count)));
Is basically equivalent to:
int tmp = fun(++count);
tmp = fun(tmp);
fun(tmp);
Firstly fun(1) will be called
Print 1
Fun(fun(fun++1)=fun(fun(fun(2)))
So,
fun(2) will be called
Print 2
Fun(fun(fun(3)))
Fun(3) called
Print 3
If confition false
Return 3, now
Fun(fun(3))
Again print 3
Return 3 then
Fun(3)
Print 3
Return 3
And recursion return back to the position of fun(2)
Fun(fun(fun(2))) will be fun(fun(3) //because 3 is
returned
Fun(fun(3))
Print 3
Then return 3
Fun(3)
Print 3
And also return 3
So after all the things printed values will be
1 2 3 3 3 3 3
Calling a function like this is not really a recursion. You can say it nested function call. In your case, you are calling function fun() three times and passing the value returned by earlier call of function.
fun(fun(fun(++count)));
So, first fun() call will take a value ++count. Whereas the second fun() call will take the value returned by first call of function as parameter. Similarly, the third call will take a value returned by second call of fun() as parameter.
To understand things easily, you can consider following example
fun3(fun2(fun1(++count)));
In this example fun1() will take ++count as parameter. fun2() will take returned value by fun1() as parameter. Similarly, fun3() will take returned value by fun2() as parameter.
I hope this explains.

Explain the reason for such output of this C program

Please help me to understand the output of the following C program.
#include "stdio.h"
int fun(int x)
{
static int a=0;
return x+a++;
}
int main()
{
int i;
for(i=0;i<5;++i)
printf("%d ",fun(printf("%d",0)));
return 0;
}
output is : 01 02 03 04 05
why not : 1 2 3 4 5
The first 0 is the result of the execution of the printf() statement inside the fun() function call
fun(printf("%d",0))
and the second 1 is the result of the outer printf() which prints the return value of the fun() function call. The fun() function call sends the return value of the inner printf() which is always 1, and since you have initialized the variable a as static the value of a remains same and is added everytime with the function call.
since you are always printing 0 in the printf() inside the fun() function call, hence the 0 before the numbers.
The arguments are evaluated in order when you call printf here:
printf("%d ",fun(printf("%d",0)));
The outer printf call needs to evaluate all its arguments, which is the following:
fun(printf("%d",0))
Which then calls the inner printf to evaluate all of its arguments.
First, printf("%d",0) will be evaluated, and evaluate to the number of characters printed (since this is what printf() returns). This is passed to fun next, which will return the number of characters the printf printed (1) plus the number of times it has been called (due to the static int a). That will then be passed to the outer printf, printing the second number, then a space.
The reason is that in this statement
printf("%d ",fun(printf("%d",0)));
function printf is called twice. At first it is called as the argument expression of function fun
fun(printf("%d",0))
and outputs aways 0.
The second time the function is called with the resut of the call of function fun Take into account that the value of call
printf("%d",0)
is always equal to 1.
imagine your commands in the way that it is evaluated:
printf("%d ",fun(printf("%d",0)));
is equivalent to:
int printf_result = printf("%d",0);
int fun_result = fun(printf_result);
printf(("%d ",fun_result);
this is c. this is not python or matlab. if you assign the result value it doesn't influence the effects of the function call.

Resources