After recursion call the next printf automatically prints the incremented values - c

I came across the strange thing in recursion, please go through the below code in printing numbers in descending order.But sooner it completes recursion and executes next printf statement it increments automatically without increment statement in the program.
int main()
{
int count=10;
counter(count);
}
int counter(int count)
{
if(count>0)
{
printf("%d\n",count);
counter(count-1);
printf("%d",count) //THIS STATMENT MAKES THE VALUE INCREMENT
//AFTER THE RECURSION
}
}
output:
10
9
8
7
6
5
4
3
2
1
1 //2nd printf results in increment without any increment operator
2
3
4
5
6
7
8
9
10

When you call
counter(count-1);
the new invocation of the function is called with the value of counter-1 but the value of counter in the current invocation of the function does not change. Hence, when the function returns, the next call to printf prints the value of counter.
If you visualize the call when count is 2, you get
printf("%d\n",2);
counter(1);
printf("%d\n",2); // I am assuming you have \n there.
If you expand the call to counter(1), you get:
printf("%d\n",2);
printf("%d\n",1);
counter(0);
printf("%d\n",1);
printf("%d\n",2);
counter(0) does not print anything. It returns without doing anything. Hence, that block of code is equivalent to:
printf("%d\n",2);
printf("%d\n",1);
printf("%d\n",1);
printf("%d\n",2);
If you start from a higher number, like 10, you get:
printf("%d\n",10);
printf("%d\n",9);
...
printf("%d\n",2);
printf("%d\n",1);
printf("%d\n",1);
printf("%d\n",2);
...
printf("%d\n",9);
printf("%d\n",10);
That explains the output.

Your answer is not accurate to explain the answer.
It will still increase the after you change the value counter directly
int main()
{
int count=10;
counter(count);
}
int counter(int count)
{
if(count>0)
{
count = count-1
printf("%d\n",count);
counter(count);
printf("%d",count) //THIS STATMENT MAKES THE VALUE INCREMENT
//AFTER THE RECURSION
}
}
above code will still make some same output with a little changing

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

Recurse loop trace

I have written the following code
#include <stdio.h>
void recurse();
int main()
{
recurse();
return 0;
}
void recurse()
{
static int n=987654321;
if(n==0)
return ;
printf("%d",n%10);
n=n/100;
int a=n;
recurse();
if(a!=0)
printf("%d",a%10);
}
I am not understanding why the output is coming 135799753?
What I thought the answer to be was 135799 because after printing the first 9 after 1357 n will become 9 and hence n/100 will be zero so the recurse function will return to the main without printing anything.
Please correct me where I am wrong.
Thanks in advance!!
Output of program is correct. Your output also consists of these values -
if(a!=0)
printf("%d",a%10);
Value of a is also printed if it is not 0. But the values are printed from last to first because of these statements after the recursion call.
You consider output to be 135799. Second 9 being value of a%10 but value of a%10 from previous recursion calls is also to be printed as those statements get executed after the end of recursion call.
You can see in this example.

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.

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.

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