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
Related
I am trying to find the output for fun(5). But I am getting an unexpected result (19) and don't know why.
My doubt is for n =5 for instance, it would return fun(3) + 3. After that would the return fun(4) + x work or the function fun will be called again?
int fun(int n)
{
static int x = 0;
if (n<=0) return 1;
if (n>3)
{
x = n;
return fun(n-2) + 3;
}
return fun(n-1) + x;
}
This is the sequence of what happens:
call fun(5)
x=0; which, being the initialisation of a static local variable,
only happens before the very first call to fun()
5>3: x=5 (not a problem, static vars can be changed and keep the value)
return fun(3)+3
return fun(2) + 5
return fun(1) + 5
return fun(0) + 5
return 1
return 1 + 5
return 6 + 5
return 11 + 5
return 16 + 3
The exact meaning an relation of the following lines seem to be of interest to you.
static int x = 0;
/* Defines a local but static variable, initialised to 0;
the initialisation happens before the first execution of the function,
conceptually at the beginning of the whole program (credits John Bollinger).
This does NOT cause an assignment to 0 during each execution of the function.
The static attribute also means that the value at the end of one
execution will still be found in the variable at the start of the next
execution, even and especially if that start is before the end of the current execution,
which is typical for recursive functions.
*/
/* ... */
x = n;
/* This conditional (inside an if) assignment in the middle of the
recursive function changes the value of the static variable away from
the initialisation value, to e.g. 5.
If/because no other assignment occurs, the value will stay in the
for the rest of the program.
*/
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
Basically the question i found on internet is: "How we can print the numbers from 1 to 100 without using of loops and conditions?" and in the answer, I got stuck at some lines below marked with bold. Can anyone explain me what is that?
I think that the total code below is written in C as much i've my knowledge.
#include <stdio.h>
#include <stdlib.h>
void foo(int);
void f1(int x)
{
printf ("%d\n", x + 1);
foo (x + 1);
}
void f2(int x) //why we have used this fumction
{}
void (*tab[])(int) = { f1, f2 }; // what is this
void foo(int x)
{
tab[!(x < 100)](x); // what is this
}
int main()
{
foo(0);
return 0;
}
tab is an array of two function pointers.
Since you're not allowed to use if, instead you use an array of functions, and index them using the result of the !(x < 100) comparison. When that's true it evaluates to 1, so you call the function in tab[1], which is f2(). When it's false it evaluates to 0, so you call tab[0], which is f1. So it effectively the same as:
if (x < 100) {
f1(x);
} else {
f2(x);
}
f1(x) prints x+1 and then calls foo(x+1) recursively. f2(x) doesn't do anything, so the recursion ends when you get to this.
void (*tab[])(int) = { f1, f2 }; // what is this would be an array of function pointers which take an int argument.
tab[!(x < 100)](x); // what is this
this means that you are accessing function 0 or 1 depending on the evaluation of the condition (false - 0 or true - 1)
The code seems to be a recursive call which would stop at 100
How about this:
#include <stdio.h>
int p(int n) {
return printf("%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n%d\n",
n+1, n+2, n+3, n+4, n+5, n+6, n+7, n+8, n+9, n+10);
}
int main() {
return p(0), p(10), p(20), p(30), p(40), p(50), p(60), p(70), p(80), p(90), 0;
}
Or this more compact version, that prints one number at a time with a non obvious termination test:
#include <stdio.h>
int p(int n) {
return printf("%d\n", n++) - 4 && p(n);
}
int main() {
return p(1);
}
Incidentally, one can make it even more cryptic this way:
#include <stdio.h>
int main(int argc, char *argv[]) {
return printf("%d\n", argc++) - 4 && main(argc, argv);
}
The 2 versions above still use tests, just not if statements.
Here is a variant that combines the idea from the OP's code with the above approach:
#include <stdio.h>
#include <stlib.h>
static void p(int n);
static void (*f[5])(int) = { p, p, p, p, exit };
static void p(int n) {
f[printf("%d\n", n + 101)](n + 1);
}
int main(int argc, char *argv[]) {
p(-100);
}
function p takes an integer n and prints the value of n + 101, then invokes the function whose pointer is at the offset in the array f corresponding to the number of bytes output by printf, passing n + 1 to this function.
The first call gets -100 as an argument, hence prints 1 and a newline. printf returns 2, so p calls itself recursively with the value -99.
The second call prints 2, and calls itself recursively with -98.
This process repeats until printf returns 4: the function called for f[4] is exit and since printf returns 4 when it first prints the number 100, exit gets the value 0 and terminates the program with an exit status of 0, which means success.
No loops, no conditions, no tests at all.
This relies on recursion (in function f1) and dynamic array lookups (in function foo) instead of using either loops or conditionals.
void f2(int x) //why we have used this fumction
{}
The f2 function does nothing and is called when x >= 100, thus terminating the sequence when the maximum value is reached.
void (*tab[])(int) = { f1, f2 }; // what is this
That is an array initialization. tab is an array of pointers to functions taking an int parameter. The two elements of the array are pointers to functions f1 and f2.
tab[!(x < 100)](x); // what is this
This does the same thing a conditional would in this scenario. This calls either the first or second function in tab, depending on whether x < 100 or not.
When x < 100, the array subscript !(x < 100) equals !true, or 0 when converted to an int. tab[0] is the first element of the array, the function f1. The f1 function prints and increments the number, then recurses by calling foo again, thus continuing the sequence.
When x >= 100, tab[1] is called, which is the second element of the array, f2. Since f2 does nothing, the sequence ends when x >= 100.
f1 is responsible for printing and actually incrementing the count and relies on the bouncing back and forth to foo.
tab is an array of two functions, f1 and f2. Look that, in foo, this array is indexed by a boolean expression that eventually translates to execute f1(count) until count is greater than or equal to 100.
foo, tab, f1, and f2 are, therefore, just a way to support and terminate recursion.
The call stack would look like this when the program is executed:
main()
foo(0)
f1(0) -> print 1
foo(1)
f1(1) -> print 2
foo(2)
f1(2) -> print 3
....
foo(99)
f1(99) -> print 100
foo(100)
f2(100) -> do nothing
<---------------------------------------
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);
}
Static variable re initialization:In the second part of the code i reinitialize the static variable x to 5. o/p of the first code is as expected but why o/p of the second part is 6 6 why not 6 7.
void foo()
{
static int x ;
x++;
printf("%d", x);
}
int main()
{
foo();
foo();
return 0;
}
//output will be 1 2
//But if i re initialize the static variable then why the output is like this:
void foo()
{
static int x ;
x=5;
x++;
printf("%d", x);
}
int main()
{
foo();
foo();
return 0;
}
//output is 66 why not 67
The result of:
x = 5;
x++;
is that x is 6. Since you execute this code twice you get the output 66.
Note, x = 5; is an assignment, not an initialization.
The output is 6, 6 because you reinitialize it to 5 each time you call the function.
To initialize it only once (and get 6, 7) you need to write:
static int x = 5;
Furthermore, the first code may yield unexpected results, because the variable is uninitialized and may contain any value.
The result is as expected because, in the function foo(),
void foo()
{
static int x ;
// what ever be the value of x until this point is retained.
// But what you are trying to do is assign the variable x again to 5, which means
// you are overwriting the previous value of x with 5.
x=5;
x++;
// Since x is always 5 due to overwriting, x++ will always yield "6" no matter what.
printf("%d", x);
}
In this scenario, the keyword static does not have any effect on the output.
void foo()
{
static int x ; // point 0
x=5; // point-1
x++; // point -2
printf("%d", x); // point- 3
}
int main()
{
foo(); // exe-1
foo(); // exe-2
return 0;
}
The program execution flow and the value of x at that point
Irrespective of how many times foo() is called, point-0 will be called only once.
exe-1: (point-0)x=0--> (point-1)x=5 (assigned) --> (point-2)x= 6
current value of x=6 before exe-2
exe-2: this time it doesn't comes to point-0, it comes to point-1, which is overwritting the current value of x(which is 6) with 5 again. So, after this, when it comes to point-2, the value of x is incremented from 5 to 6, so it prints 6
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