Explanation regarding output of C program - c

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);
}

Related

Unexpected answer

I took a C Advanced Course on Udemy, and there is a question from there:
What will be the output of the following code?
#include <stdio.h>
int main(void){
static int i=5;
if(--i){
main();
printf("%d ", i);
}
}
The right answer is 4 3 2 1, but when I run this code in my IDE (and online compilers), it prints 0 0 0 0.
In the course lector uses cygwin compiler and I have g++. May it be the reason of the inconsistency?
Also I'm wondering if if(--i) method is faster then for loop by the concept of performance?
Thank you.
The reason is main() is called before printf("%d ", i). So when if block is executed, main() function is called before printing the value of i and it's continue to do so until if-condition is false. Here if-condition became false when i is equal to 0. When the if-contidion is false the function return to the previous state from where it have been called and then print the value of i, which is now 0.
To print 4 3 2 1, print the values before calling main() funtion like bellow
int main(void){
static int i=5;
if(--i){
printf("%d ", i);
main();
}
}
The posted code shall print 0 0 0 0 because the printf is after the recursive call, i.e.
main(); // Recursive call
printf("%d ", i); // Print after
If you instead do:
printf("%d ", i); // Print before
main(); // Recursive call
the output will be 4 3 2 1
So I think your lector used the last form and you used the first form, i.e. different code, different results

how does recursion retain value even after some cycle

Can some one explain the execution of this program .
OUTPUT is:
1
2
3
4
3
2
1
how does function retain value 3,2,1 in the end
main(){
int h=0;
g(h);
}
g(int n){
n++;
printf("%d\n",n);
if (n ==4)return 88;
g(n);
printf("%d\n",n);
}
You are getting the above output because at the 8th line of your code you are calling the function agian recursively so the remaining code after the 8th line is saved in the call stack in your memory. So, when you get the output 1 2 3 4, the remaining code that is left (in call stack) is executed hence you are getting this output.
below is the call stack of your program
when n = 0 the stack will place 1
|___|
|___|
|_1_|
when n = 1 the stack will place 2
|___|
|_2_|
|_1_|
when n = 2 the stack will place 3
|_3_|
|_2_|
|_1_|
when n = 4 the stack will not place anything as it encounters the return statement
now, we have some values in our stack
so the program starts popping the top most value in stack (here n = 3) and continue the execution where it left off (i.e it will print the value) and this process will go on until the stack is empty.
NOTE: You can visit this video to understand more effectively about recursion https://www.youtube.com/watch?v=Mv9NEXX1VHc
g(int n){
n++;
printf("%d\n",n); // n=1 print 1 & call g(n) with 1 now g(1) make its own n=2 print 2 & call g(2)
//... print 3 & call g(3) becomes 4 print 4 return 88
if (n ==4)return 88;
g(n);
// now after the return we get back to the 3rd call that called g(3)
//so it print 3 at the end 3 ends
//we go back to the one that called g(2) so we print 2 at the end... & same for 1
printf("%d\n",n);
}
You can read above answers they are pretty good, but here is another way to get you head around it. Simplest answer is the same way that caller function retains its value when calling any function. For example if you have:
int main (void) {
int a = 5;
fun1 (a);
}
void fun1 (a) {
fun2 (a);
printf("%d\n", a); // output would be 5
}
void fun2 (int a) {
a+=1;
fun3 (a);
printf("%d\n", a);
}
void fun3 (int a) {
a+=1;
printf("%d\n", a);
}
So fun1 () would print out 5, fun2 () 6 and fun3() 7. Recursion function is similar to above from perspective of caller and called function, instead of calling function with different name it is calling the function with same name, or in other words it is calling itself.
Look at this code:
void recFun (int a) {
if (a > 6)
printf("%d\n", a);
recFun (a + 1);
printf("%d\n");
}
Some people when I was in school would rewrite above to following (on a piece of paper of course this would yell at you if you try to compile it):
void recFun (int a) {
recFun (a + 1);
printf("%d\n");
}
void recFun (int a) {
recFun (a + 1);
printf("%d\n");
}
void recFun (int a) {
printf("%d\n");
}
In C the function arguments acts as local variables inside the function. Further C uses call-by-value which means that the value of variable used by the caller as argument is copied to the functions argument variable. Consequently the two variables are completely independent variables.
Consider this code:
void foo(int x)
{
x++;
printf("%d", x);
}
void bar(int y)
{
y++;
printf("%d ", y);
foo(y);
printf("%d", y);
}
bar(0);
This will output "1 2 1"
Most people find that it's obvious that changes to x will not change y. They are by name two different variables. So no surprise in that.
If we change the code to use the same name for variables - like:
void foo(int x)
{
x++;
printf("%d", x);
}
void bar(int x)
{
x++;
printf("%d ", x);
foo(x);
printf("%d", x);
}
bar(0);
The output is still "1 2 1"
Simply because the variable x inside foo is another variable than x inside bar. The only relation ship they have is that x inside foo is initialized with a copy of the value of x inside bar. No matter what kind of change you make to x inside foo it will/can not change x inside bar.
Exactly the same goes for the recursion. Each function call creates its own variable n - completely independent of the n variable in previous calls.
Most implementations use a stack for implementing this functionality. Do a search for "stack frame" to get more information. Also see
Explain the concept of a stack frame in a nutshell

I really don't get how we got these outputs

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.

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

Recursion in C programming Language

I am learning recursion now-a-days. Here are three codes. The first and third is giving me the expected output but the second is not? Can somebody tell me what is just the difference in them.
Code 1:
void tail(int i){
if (i>0) {
printf("%d\n",i);
tail(i-1);
}
}
int main()
{
tail(5);
}
Code 2:
void tail(int i){
if (i>0) {
printf("%d\n",i);
tail(i--);
}
}
int main()
{
tail(5);
}
Code 3:
void tail(int i){
if (i>0) {
printf("%d\n",i);
tail(--i);
}
}
int main()
{
tail(5);
}
output of Code 1:
5
4
3
2
1
output of Code 2:
5
5
5
.
.
. Infinite
output of Code 3:
5
4
3
2
1
Please help me out. I am confused!
Result is as expected
decrement is post decrement so it would first use current value and then decrement. So function gets repeatedly called with current value so infinite loop.
Working fine for me . Similar to first
Of course code number 2 won't. In code number 2 you typed tail(i--); what -- operator (after the variable name) does is first using him in the line you requested and THEN decrease him by one.
Let's say I have the line printf("%d", i--); It'll print i in it's current value and only after printing it, it will be decreased, it first uses I, and then decreases it - same would happen if you would just type:
printf("%d", i);
i--;
About the -- operator BEFORE the variable. It'll first decrease and then do the requested action - so printf("%d", --i); will decrease i by one and then print it.
We all agree code 1 works well, code 2 actually is in an infinite loop BECAUSE you decrease the variable AFTER calling the function - so it decreases in one function only.
Basically, what it does is like:
printf("%d", i); //which is 5
tail(i);//which is still 5
i--; //will never get to this line because we called another function with variable 5
and so on.
About code number 3, it works perfectly, it's like code number 1 (but code number one won't actually decrease the variable, just call the function with the variable-1).
EDIT:
for more information, you can search in this article :)
The 3 have to work. The 2 don't work because i is decremented after been passed to the function.
You should work with pointers in second case. Each time you are passing the same value into recursive function ... first goes function call and after that you have decrement operation. As a result you have the same value (5) in each recursive call.
The second doesn't give you your desired output because you are using post-decrement operator i--.
This means "use i and then decrement i" as opposed to --i which means "decrement i and then use i".
So in your third case, i whose value is 5, gets decremented to 4, and then tail(4) is called.
In the second case, tail(i--) is called, which means call tail(5) and then do i-=1; .
If i-- and --i are given as standalone statements, they are equivalent, for example
for(int i=5;i>0;i--)
is effectively the same as
for(int i=5;i>0;--i)
But in cases such as follows:
int i=5;
int a=i--;
printf("%d %d", i, a);
This gives out put 4 5 whereas
int i=5;
int a=--i;
printf("%d %d", i, a);
will give output 4 4.

Resources