I really don't get how we got these outputs - c

can somebody explain to me how did we get this output?
OUTPUT:
Q
B C D
This is my code:
#include <stdio.h>
char x = 'A';
void fun_1(int n) {
if(n>0) fun_1(n-3);
if(n == 0 ) printf("Q\n");
printf("%c ", ++x);
};
int main()
{
fun_1(6);
return 0;
}

You have a recursive function, recursive means that at some point it calls
itself. The terminal case (when the function stops calling itself) is when n == 0.
When dealing with recursive functions, you have to think this way:
Recursion level 0 (the first call)
n == 6 ==> if(n>0) fun_1(n-3); is executed
Recursion level 1
n == 3 ==> if(n>0) fun_1(n-3); is executed
Recursion level 2
n == 0 ==>
if(n == 0 ) printf("Q\n"); is executed, output is "Q\n"
printf("%c ", ++x); is executed, x is now B, output is B
this is terminal case, therefore
(back to)
Recursion level 1
printf("%c ", ++x); is executed, x is now C, output is C
(back to)
Recursion level 0
printf("%c ", ++x); is executed, x is now D, output is D
Now the recursive calls have ended and you are back in main. As you can see
from the analysis of the recursion levels, the generated output is
Q
B C D

Here's the calls that would be made:
fun_1(n=6)//from main
fun_1(n=3)//since 6 > 0 {
fun_1(n=0){//now n is not greater than zero, so don't recurse
execute if n == 0, yes it is, so output Q
print ++x, x was A now after ++x, x would be 'B'
}
since n <> 0, don't output Q
print ++x, x was B, so print C which is after pre-incrementing x
}
since n <> 0, don't output Q
print ++x, x was C, so print D which is after pre-incrementing x
}

Guys can somebody explain to me how did we get this output?
I'm able to reproduce:
% vi aaaa.c
[ code copied in the editor ]
% gcc aaaa.c
% ./a.out
Q
B C D
I hope that helped!
(that was a joke, if it's not clear to everyone...)
You can try to add a printf in the function fun_1. You see that it's called recursively 3 times with the values 6, 3 and 0.
The last call will print the Q then the B. Then the second call will print the C and the first one the D.

void fun_1(int n) {
if(n>0) fun_1(n-3);
if(n == 0 ) printf("Q\n");
printf("%c ", ++x);
};
with the first call of this method in the main function, you send the value of 6.
if(n>0) fun_1(n-3) with this statement, because 6>0, recursive process is started and 6-3=3 is sent back to fun-1 function. But here, the most important thing to keep in mind that, the first function which is created in memory is not terminated. For each recursive step, there will be created new functions for new n values. So here;
printf("%c ", ++x);
this statement will be working with the same number of recursive loop. Because you used, pre-incrementation as "++x", the char value x = 'A' will first be incremented and then printed. So for every recursive loop step, all the functions which are created are terminated by a sequence of creation, and they printed the pre-incremented value as in output.

Related

i cant understand the behavior of printf with recursion

I cant understand why my code output is 2,2,3 and also when I remove u++ it's output is 2,5,5 I am using code_block on windows 7 with gcc
I try to dry run my code but its output is different what I calculate
int f(int);
int u = 1;
int main()
{
int n = 3;
//scanf("%d", &n);
f(n);
}
int f(int n)
{
if (n == 0)
{
return 2;
}
else
printf(" %d \n", f(n - 1));
u++;
}
I expected 2,1,0 may be I am wrong but I cant understand why output is 2,2,3 and when I remove u++ it make big confusion for me
In the n != 0 path, your function does not explicitly return a value, and the value returned will be undefined.
It is also not clear to me why you return 2 when n==0 - you do nothing with this value, and it seems arbitrary.
Consider this:
int f( int n )
{
if( n != 0 )
{
n-- ;
printf( " %d \n", n );
n = f( n ) ;
}
return n ;
}
It is both simpler (no else block), and has a single point of exit with an explicitly defined return value.
Let’s trace it through:
You call f(3)
f(3) calls printf("%d", f(2)) - f(2) must be evaluated before printf is called
f(2) calls printf("%d", f(1)) - f(1) must be evaluated before printf is called
f(1) calls printf("%d", f(0)) - f(0) must be evaluated before printf is called
f(0) returns 2
The printf call from step 4 is made with the result of f(0), which is the value 2 - this is the first 2 in the output
u is incremented and now holds 2
f(1) exits without returning a value - you’ve invoked undefined behavior here, and from now on any result is possible. What’s likely happening is that the result of u++ has been stored in the same register used to return values from a function.
The printf call from step 3 is made with the result of f(1), which is undefined.
u++ is incremented and now holds 3.
f(2) exits without returning a value.
The printf call from step 2 is made with result of f(2), which is undefined. Again, what’s likely happening is that the result of u++ has been stored in the same register used to return values from a function.
This is why you saw a different result when you took out the u++ statement.
Note - I say this is a likely explanation based on real behavior I have observed in the past; however, the key property of undefined behavior is that it is undefined - it doesn’t have to be consistent or repeatable. The output could vary from run to run without rebuilding the code. It’s possible that you’re seeing that output for a completely different reason. The key takeaway is that there is an error in your code (not returning a value from f when n > 0) that needs to be fixed.
The question is, what is f() supposed to return when n > 0? Once you figure that out, add an explicit return for that value. For example, if f() is supposed to return n, then you want something like
int f( int n )
{
if ( n == 0 )
{
return 2;
}
/**
* Don’t really need an "else" here
*/
printf( " %d\n", f( n - 1 ));
u++;
return n;
}
You’ll also want to add a check that n is not less than 0, otherwise your code will recurse until you hit INT_MIN and underflow, and guess what, the behavior on signed integer underflow (and overflow) is also undefined.
Here is the solution:
int f(int);
int main() {
int n;
scanf("%d", &n);
f(n);
}
int f(int n) {
if (n == 0) return 0;
else {
printf(" %d \n", n-1);
f(n - 1);
}
}
You should avoid global variables and there is no need for variable u.

seemingly ignored assignment to variables in head of for-loop

void main()
{
int a, b, r;
//Finf GCD by Eucledian algorithm
scanf("%d %d", &a, &b);
for( ; b == 0; (a = b), (b = r)){
r = a % b;
printf("GCD is %d", a);
}
printf("GCD is %d", a);
}
Somehow this doesn't work.
I assign a to b and b to r, but this doesn't seem to change the value of a or b.
This for(;b==0;(a=b),(b=r)) sets up the for-loop like this
do nothing to init anything
as long as b equals 0 do the loop body
between loop body executions first copy value of b to a,
then copy value of r to b
Note that the loop will never execute if b starts off non-zero.
Otherwise the loop will stop executing as soon as b becomes non-zero, from being updated with value of r.
(This is somewhat compiling an answer from comments, in order to get this out of the list of unanswered questions. Credits to dddJewelsbbb. I offer to delete this if they make an answer and ask me to.)
Find the corrected working code below, which changes the loop condition:
#include <stdio.h>
void main ()
{
int a, b, r;
//Finf GCD by Eucledian algorithm
scanf ("%d %d", &a, &b);
for (; r > 0; a = b, b = r)
{
r = a % b;
}
printf ("GCD is %d", a);
}
Test by giving inputs: 16, 12
16
12
GCD is 4
Code explanation:
The code is the direct implementation of Euclid's algorithm to find GCD. Here the divisor (one of the number) is used to obtain a remainder (after dividing the second number as dividend). Next, the remainder becomes the divisor and the earlier divisor becomes the dividend and this process continues till remainder is zero.
There is plenty of scope in the code to make it more elegant and handle corner cases. I corrected the exact same code as minimum as possible to spot the exact error (which was in the for loop condition).

Explanation regarding output of C program

void count(int n)
{
static int d=1;
printf("%d", n);
printf("%d", d);
d++;
if(n>1)
count(n-1);
printf("%d", d);
}
void main()
{
count(3);
}
Output calculated by me is 3 1 2 2 1 3 4
And Output given by book 3 1 2 2 1 3 4 4 4
I know why my answer different.
In book solution they are executing printf statement in "if" loop always. But as I study in my book scope of if, for and while loop is up to next statement if parentheses are not present.
After if statement true count is called and printf not get executed. But why they are executing it each time.
If you do not give parenthesis to your if, for, while statements they will only execute next line. After changing:
if(n>1)
count(n-1);
printf("%d", d);
To:
if(n>1){
count(n-1);
printf("%d", d);
}
Your output will become closer to what you expected it to be:
gonczor#wiktor-papu:~/tmp$ gcc main.c -o main
gonczor#wiktor-papu:~/tmp$ ./main 31221344
static d:1
count(n:3)
print(n) // 3
print(d) // 1
++d:2
count(n:2)
print(n) // 2
print(d) // 2
++d:3
count(n:1)
print(n) // 1
print(d) // 3
++d:4
print(d) // 4
print(d) // 4
print(d) // 4
The first 4 is printed because the if guard stopped the recursion. The second 4 is printed as the (recursive) function call for count(n:1) has returned. The third 4 is printed as the (recursive) function call to count(n:2) has returned.
I think your confusion is that you believe that making a recursive call causes the caller to end any further processing of its function body. But this is not the case, unless there is a return statement that ends the function early. For example, if the recursive call was guarded like this:
if (n>1) {
count(n-1);
return;
}
print("%d", d);
Then, the output would match your expectations. Only one 4 would be printed, the one that executed because the if evaluated false. All the other recursive calls would execute return after completing, so no other 4 will appear.
Also note:
if (n>1)
count(n-1);
printf("%d", d);
and
if (n>1) {
count(n-1);
}
printf("%d", d);
are equivalent. And the code means: print d after the if block completes. There are two ways for it to complete. One way is when the if condition is false. The other way is when the if condition is true, the recursive call is performed, and then that call returns. When recursive call returns, the if block completes, and then d is printed.
Further note, while very closely related, and computationally equivalent, recursion cannot be considered an ordinary "loop". A recursive call implies multiple active local stacks, while an ordinary "loop" only has the current local stack, and the loop execution block. Thus, a print statement after an ordinary "loop" will only get executed once, which is after the loop completes. However, code that follows a recursive call will get executed after the recursive call returns. So, if the recursive call is performed 2 times, there are three active local stacks that need to complete. In your code, each of those local stacks want to print d after the if block completes.
If the output by the book is '3 1 2 2 1 3 4 4 4'
#include <stdio.h>
void count(int n)
{
static int d=1;
printf("\nN IS: %d", n);
printf("\nD IS: %d", d);
d++;
if(n>1) count(n-1);
printf("\nFINAL D IS: %d", d);
}
int main()
{
count(3);
return 0;
}
if not change this:
if(n>1)
{
count(n-1);
printf("\nFINAL D IS: %d", d);
}

what should be the output for below program?

void foo(int n, int sum)
{
int k = 0, j = 0;
if (n == 0) return;
k = n % 10;
j = n / 10;
sum = sum + k;
foo (j, sum);
printf ("%d,", k);
}
int main ()
{
int a = 2048, sum = 0;
foo (a, sum);
printf ("%d\n", sum);
getchar();
}
For me this should be 4,0,2,8,0
However, when i execute it, it gives me 2,0,4,8,0
As the code stands, the argument sum to foo is not really relevant since it is passed by value so the last statement in the main function printf ("%d\n", sum) will print 0 regardless of what happens inside foo. That's the last 0 you see in the output the program generates.
Now, the function foo itself accepts an argument n, performs integer division by 10, and recursively calls itself until n is zero. This in effect means that it will print the decimal digits of the input number which is what you see in the output...
It is called as recursive call to the function.
And internally Recursion run as a stack LAST IN FIRST OUT kind
Now in your case it is first printing the output of last call to foo function
Steps in which your program is executing are like this and result will go in stack
1 - 1 st call to foo value of k = 8
2 - 2 nd call to foo value of k = 4
3 - 3 rd call to foo value of k = 0
4 - 4 th call to foo value of k = 2
And as told earlier it will work like stack so the output of the program will be
2 0 4 8 and if you want 4,0,2,8,0 this as a output you need to write the logic accordingly :)
Yes, the output you are getting is absolutely right.
In main(),foo() is called with a=2048 and sum=0.
In foo() we have n=2048, then the if condition calculates values for k,i.e.,(n%10) and j,i.e.,(n/10) till n becomes equal to 0.
Now since there is a recursive call to foo() with j and sum as parameters, the value of k in each iteration gets pushed to a stack and is popped out when n==0 condition is satisfied.
So, if you trace out the program you get values of k=8,4,0,2 which is pushed to stack in the same sequence and thus while popping the elements we have 2,0,4,8.

Getting output from recursion manually in C

So, I have two questions.
Question 1) I find recursion difficult in C. And I have this one question, that I dont know how should I go about attempting it. I want to know its output, Please help me.
#include <stdio.h>
void fun (int);
int main (void)
{
int a;
a = 3;
fun(a);
printf("\n");
return 0;
}
void fun ( int n )
{
if ( n > 0 )
{
fun(--n);
printf("%d",n);
fun(--n);
}
}
How can I solve this recursion manually?
I know during recursion, the information is stored on stack. Therefore, I tried doing it by that way. Firstly, a will be decremented all the way upto 0. But then, it will exit out of the loop. So, when will it print the values?
Question 2) Also, I Wanted to know since the topic I am studying right now is functions. If I make a function and lets suppose it returns some value, then IS IT MANDATORY that I collect its value upon calling or I can call it without collecting its return value?
For eg: Let's say I made the function as,
int foo ( int a )
{
........
return b;
}
Now, if I call this function from inside main, then is it mandatory that I store the returned value in some variable?
You had 2 questions: the first one is what happens in your code:
To your question #1: Function fun(n) could be rewritten so that it is functionally equivalent but easier to understand, as:
void fun(n) {
if (n > 0) {
fun(n - 1);
printf("%d", n - 1);
fun(n - 2);
}
}
That is:
for fun(n)
if n > 0,
first call fun(n - 1)
then print the number n - 1
lastly call fun(n - 2)
Thus the following happens when unwinding the recursion:
fun(3) ->
fun(2) ->
fun(1) ->
fun(0) ->
n <= 0 -> exits
prints 0
fun(-1) ->
n <= 0 - exits
prints 1
fun(0) ->
n <= 0 - exits
prints 2
fun(1) ->
fun(0) ->
exits as n <= 0
prints 0
fun(-1) ->
exits as n <= 0
Execution goes from up to down sequentially - thus the output 0120 from the prints lines.
Question #2:
No, return value does not need to be stored in a variable. In fact, the printf you used returns an int, that tells the number of characters written, but you did not store that return value anywhere.
For no 1 - Get a note pad and a pencil.
Start off an write fun(3) - It is in Main.
You can now cross that out an instead write
if ( 3 > 0 )
{
fun(2);
printf("%d",2);
fun(1);
}
(applying the logic of --n)
Repeat with both of those fun. You can do the leg work on this one
Number 2 - You do not have to collect the return value from a function
I would like to answer your second question About storing the value returned by the called function.
The answer returned by the called function can be displayed in two ways..
No.1-You need not store it in any variable in the calling function and print it directly as follows:
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10, b=9, add(int,int);
printf("Sum of %d and %d is : %d",a,b,add(a,b));
getch();
}
int add(int m,int n)
{
return(m+n);
}
Here,the function call has been written in the printf() function and hence the need of an extra variable has been eliminated
No.2-The other way and the code for the same-
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int a=10,b=9,c,add(int,int);
c=add(a,b);
printf("Sum of %d and %d is : %d",a,b,c);
getch();
}
int add(int m,int n)
{
return(m+n);
}
So,you do need a variable for the second method.Because there has to be something to catch the value thrown by the called function

Resources