Function call in for loop and static variable - c

#include <stdio.h>
int main() {
int r() {
static int num = 7;
return num--;
}
for(r(); r(); r())
printf("%d",r());
return 0;
}
The output is 52. How i m getting the output is out of my knowledge this question what i had learned about static went totally wrong.

First time you run r() it will return 7, next time 6 and so on.
The for loop will stop when r() value is 0.
The code flow is:
r() // 7 [1st expression in the for loop]
if (!r()) stop for loop; // 6, so goes into for loop [2nd expression in the for loop]
print (r()) // 5
r() // 4 [3rd expression in the for loop]
if (!r()) stop for loop // 3, continues again
print (r()) // 2
r() // 1 [3rd expression in the for loop]
if (!r()) stop for loop // 0 so exits the for loop
It first prints 5, then 2 (without newlines), hence the output is 52.

#include <stdio.h>
int r(){
static int num = 7;
return num--;
}
int main()
{
for(r();r();r())
printf("%d",r());
return 0;
}
the static var is like a global var (I mean not in the stack) but only visible for the function r
the result is 52 because it prints 5 then 2
the initial value of num is 7
the for call a first time r (init part of the for), so num is decremented to be 6 and r returns 7 for nothing,
the test is performed and num is again decremented to be 5 and because 6 is return and is not 0 the for continue,
now the print is done with again a call decrementing num to 4 with the result 5 being printed
r called (modif part of the for) decrementing num to 2 and returning 3 for nothing
again the test decrementing num to 2 and returning 3 != 0 the loop continue
again the print is done with again a call decrementing num to 1 with the result 2 being printed
r called (modif part of the for) decrementing num to 0 and returning 1 for nothing
the test is performed and num is again decremented to be -1 and because 0 is return by r the loop stops

Related

Output is 5 5 6 7 8 9 explain how?

Can someone please explain how this recursion is working in the following code?
#include<stdio.h>
func(int x)
{
if(x>5)
func(--x);
printf("%d",x);
}
int main(void)
{
func(10);
return 0;
}
The function logic works that way:
If x is bigger than 5, the function will be called again with x decremented by 1.
In the following line:
func(--x);
--x means that x will be decremented by 1 before this code line executes, different than x-- which means x will be decremented after the line.
When x will be equal to 5, it will be printed and then the function will return to the last place it was called from and continue from there, meaning x will be printed again with the value it had in the last call, then return again so on and so forth.
So the function will basically print all the numbers from 5 to the given number (if it’s bigger than 5 of course), excluding the given number, since x was decremented before it was printed.
In your case the call func(10) will result in the following output:
56789

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.

Not able to understand the output of C program

There's this code in C
int fun()
{
static int num = 40;
return num--;
}
int main()
{
for(fun(); fun(); fun())
{
printf("%d ", fun());
}
getchar();
return 0;
}
the output comes out to be: 38 35 32 29 26 23 20 17 14 11 8 5 2
I'm not able to figure out why the program doesn't continue to print beyond 2. i.e. in the negatives .shouldn't it continue printing ... -1 -4 -7....infinite loop Can anyone explain ?
fun() is evaluating to 0 here:
for(fun(); fun(); fun())
// ^
0 is the equivalent of false in C, so the loop is exiting.
The code relies on the fact that num - 1 is a multiple of 3, as fun() is evaluated once at the start of the loop and then 3 times every loop. If, for example, you changed the definition to
static int num = 41;
fun() would return 0 in the wrong place and your loop would continue into the negative numbers.
The whole magic happens inside your for() loop.
The basic format is like this:
for (<pre-iteration>; <condition>; <post-iteration>)
<code>
Code inside pre-iteration will be executed once before the first iteration/loop.
Code inside condition is evaluated before each and every iteration. If the resulting value is true, the loop continues, if it's false, the loop is left.
Code inside post-iteration is executed after each and every iteration.
To make the whole code easier to understand, it's important to know that you're able to write such a for() loop using a while() loop as well:
<pre-iteration>
while (<condition>) {
<code>
<post-iteration>
}
Back to your example:
for (fun(); fun(); fun())
{
printf("%d ", fun());
}
Using a while() this can be written like this:
fun();
while (fun()) {
printf("%d ", fun());
fun();
}
Since fun() will return the value of the static value num and then decrement it by 1 the first iteration will look like this:
// This is going to be the first call, so the static variable is initialized: num = 40
fun(); // returns 40; num = 39
while (fun()) { // returns 39; num = 38 (true -> loop continues)
printf("%d ", fun()); // returns 38; num = 37 (-> 38 is written to console)
fun(); // returns 37; num = 36
}
The next iteration (code before the loop is no longer executed for obvious reasons):
fun(); // no longer executed
while (fun()) { // returns 36; num = 35 (true -> loop continues)
printf("%d ", fun()); // returns 35; num = 34 (-> 35 is written to console)
fun(); // returns 34; num = 33
}
This continues till the last iteration:
fun(); // no longer executed
while (fun()) { // returns 0; num = -1 (false -> loop exits)
printf("%d ", fun()); // no longer executed
fun(); // no longer executed
}
I'm not able to figure out why the program doesn't continue to print beyond 2. i.e. in the negatives .shouldn't it continue printing ... -1 -4 -7....infinite loop Can anyone explain ?
Yes, it might continue, but only if that specific call to fun() wouldn't return 0, i.e. set the initial value of num to 41 and the program will run indefinitely (or at least till the return value happens to be 0 at some point).
Let's look at what happens in the second call to fun() in the for loop. The first time the loop is entered, fun() has been evaluated once already, so num is 39. The second time we get to the loop, fun() has been executed three more times, so it is now 36. This process continues, until eventually, the second call to fun() returns 0. In C, 0 means false, so the loop terminates at that stage.
When
printf("%d ", fun());
is run, fun() has value 2
Then the last fun() in the next command is executed to increase the counter (normally):
for(fun(); fun(); fun())
fun() is 1.
Then the condition to continue the for loop is performed, which is the second fun() in:
for(fun(); fun(); fun())
At this point, fun() is 0 which makes the for loop stop.
for(fun(); fun(); fun())
second part of for() loop is a condition - if fun() returns 0, which is interpreted as false, the loop terminates. lately i got a brain fart and wrote a statement that condition is true only for positive numbers.
When you print fun(), you do not see the actual value of num, but the value of num+1.
This is because you are using a postfix-decrement (num--) and not a prefix-decrement (--num).
So when you 2 is printed, the actual value of num is 1.
At the end of this iteration, fun() is invoked, setting num to 0.
At the beginning of the next iteration, num is evaluated as false and the for loop is terminated.

What is really happening in this code?

I have a code which includes a recursive function. I have wasted a lot of time on recursion but I still couldn't get it really:
#include<stdio.h>
void count(int);
int main()
{
int x=10,z;
count(x);
}
void count(int m)
{
if(m>0)
count(m-1);
printf("%d",m);
}
When the 1st time count is called with argument as 10. it fulfills the condition and then here starts the recursive part. what happens really when a function calls itself? I don't get it. Please explain with reference to stacks.
While m is greater than 0, we call count. Here is a representation of the stack calls:
count (m = 10)
count (m = 9)
count (m = 8)
count (m = 7)
count (m = 6)
count (m = 5)
count (m = 4)
count (m = 3)
count (m = 2)
count (m = 1)
count (m = 0)
printf 0
printf 1
printf 2
printf 3
printf 4
printf 5
printf 6
printf 7
printf 8
printf 9
printf 10
next time it calls itself it has a smaller value
count(int m)
{
if(m>0)
count(m-1); // now it is calling the method "count" again, except m is one less
printf("%d",m);
}
So first it will call count with 10, then it will call it with 9, then 8, then 7..... all the way until this if statement isn't true:
if(m>0)
What might be confusing you is the if statement only applies to the next line (printf isn't part of the if statement)
so you have:
count(int m)
{
if(m>0)
{
count(m-1); // now it is calling the method "count" again, except m is one less
}
printf("%d",m);
}
So, the recursive calls will stop once m is not > 0, and then it will call the printf.
After it calls printf for when m is 0, then it will return from that 'count' call, (Back to where m was equal to 1), and then it will call the printf when m is 1, and then when m is 2, .....
So the output should be:
"0 1 2 3 4 5 6 7 8 9 10"
EDIT:
In terms of a stack:
This is what the stack is doing:
count(10) // push count(10)
->
count(9) // push count(9)
count (10)
->
...
->
count(0) // push count(0)
count(1)
count(2)
count(3)
count(4)
count(5)
count(6)
count(7)
count(8)
count(9)
count(10)
-> (and then it starts printing and popping the method off the stack)
// pop count(0), and printf(0)
count(1)
count(2)
count(3)
count(4)
count(5)
count(6)
count(7)
count(8)
count(9)
count(10)
->
// pop count(1), and printf(1)
count(2)
count(3)
count(4)
count(5)
count(6)
count(7)
count(8)
count(9)
count(10)
->
...
->
// pop count(9), and printf(9)
count(10)
->
// pop count(10), and printf(10)
When a function is called the return address (of the next code to execute) is stored on the stack along with its current arguments. Once the function finishes the address and arguments are popped so the cpu will know where to continue its code execution.
Let's write the addresses of the function (for the purpose of this example only)
count(int m)
{
(address = 100) if(m>0)
(address = 101) count(m-1); // now it is calling the method "count" again, except m is one less
(address = 102) printf("%d",m);
}
For m = 1:
The if is fullfield so we execute code at address 101 with m = 1. address 102 and m = 1 are pushed to the stack and the function is executed again from address 100 with m = 0. Since m = 0 we execute address 102 and printing 0 on console. The function ends and the last return address (102) and argument m = 1 are popped and the line at address 102 is executed printing 1 on the screen.
The function count is called with an integer argument of 10.
Since the function argument m which is 10 is greater than 0 the function count calls itself with an integer argument of m which is 10 minus 1 which equals 9.
Step 2 repeats with varying arguments (m-1) until m is not greater than 0 and which point the program prints the value of m.
The recursive function just modifies the parameter given to it and calls itself with that modified value until the desired result is returned (in this case m not being greater than 0).
Each number refers to the line number.
#include<stdio.h>
count(int);
main()
{
1int x=10,z;
2count(x);
}
count(int m)
{
3if(m>0)
4 count(m-1);
5printf("%d",m);
}
The execution happens like this(with x=3) -
line number|value of x
1 3
2 3
3 3
4 2
3 2
4 1
3 1
4 0
5 0
5 1
5 2
5 3
Numbers printed on the screen 0 1 2 3
If you want a more specific answer, then you have to look into how compilers work. But generally speaking the compiler will create machine code for the function that includes a preamble, in this code enough memory is allocated on the stack (by decrementing a stack pointer) that a copy of the functions variables can be placed on the stack (we can store the state of the function).
The function will have values stored in registers and memory and these must be stored on the stack for each (recursive) call, otherwise the new call will overwrite the precious data!. So very basically the machine code looks like this (pseudo code)
//store m on the stack
store m,stack_pntr+m_offset
//put input values in designated register
a0 = m
//allocate memory on the stack
stackPntr -= stack_size_of(count_vars)
//store return address in allocated register
//jump to the first instruction of count
.
.
By changing some data used for computation we can go back and read the same instructions again and get a different result. The abstraction of recursive function allows us to manipulate the data we want to change in a nice "call by value" way so that we don't overwrite it unintentionally.
This is done by the compiler when it stores the state of the calling function on the stack so we don't have to manually store it.

Why does this recursive function generate this output?

I am trying to understand the output of the program printed below. When I look at it, I see that when printnum() is called with an argument of 1, "1" will be printed and then since 1<7, the function will call itself. This process will continue until "6" is printed and then printnum(7) is called. So, now "7" is printed and the if condition is not satisfied, so that code is skipped and we move to the second printf("%d", x) function where "7" is printed out again. There is nothing after the second printf("%d", x), so why doesn't everything end there? What makes the program keep going to print the numbers again in descending order?
#include <stdio.h>
int printnum ( int x )
{
printf("%d", x);
if ( x < 7 )
{
printnum ( x + 1 );
}
printf("%d",x);
}
int main()
{
printnum(1);
}
Output:
12345677654321
printnum(8) is never called, because it isn't true that 7 < 7.
The reason that you get the numbers printed in descending order once x = 7 is reached is, that each recursive call ends, leaving the previous call to continue.
Consider what it does for x = 1:
Print 1
Call recursively with x = 2
Print 1
If we expand this one level more:
Print 1
Print 2
Call recursively with x = 3
Print 2
Print 1
And one more:
Print 1
Print 2
Print 3
Call recursively with x = 4
Print 3
Print 2
Print 1
If you continue this expansion, you can see you get numbers in ascending order before the recursive call, and in descending order after the recursive call.
This happens because the second printf is called after your recursion exits at each level.
As your final recursive call printfs and ends, control transitions to the function that called it - the second-to-last recursive call. This call then exits the scope of the if statement, and calls printf, and then ends - upon which control transitions to the function that called it - the third-to-last recursive call. Repeat until you are inside the call to printnum(1), whose return takes you back to main.
It's recursion. When you enter the function you call printf, then you enter another level in the recursion, then you enter the printnum, so you call the printf with x+1 and so on.
When you arrive at stop condition (x==7), the function goes till the second printf (so 7 will be displayed again).
The function printnum terminates, so the program returns at the level above, then printnum at level 6 can printf again, terminate and return and so on.
Comments in-line!
int printnum ( int x ) x = 1 x = 2 x=6 x=7
{
printf("%d", x); prints 1 prints 2 prints 6 prints 7
if ( x < 7 ) Yes Yes Yes No
printnum ( x + 1 ); calls printnum(2) calls printnum(3) .... calls printnum(7) N/A
printf("%d",x); print 2 and return to print 6 and return prints 7 and returns to the
the caller which is the previous caller to the previous previous caller which is
main() which is printnum(1) caller which is printnum(x=6)
printnum(5)
}
Please check the following to print in ascending and descending order passing the starting value and the limit.. (please note that the error checking is not done!)
#include <stdio.h>
int printnum_123(int x, int limit)
{
printf("%d ", x);
if (x<limit)
printnum_123(x+1, limit);
return;
}
int printnum_321(int x, int limit)
{
if (x<limit)
printnum_321(x+1, limit);
printf("%d ", x);
return;
}
int main(void)
{
printnum_123(1, 10); printf("\n");
printnum_321(1, 10); printf("\n");
return 0;
}
$ ./a.out
1 2 3 4 5 6 7 8 9 10
10 9 8 7 6 5 4 3 2 1
$

Resources