Output is 5 5 6 7 8 9 explain how? - c

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

Related

Function call in for loop and static variable

#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

Cannot understand the Output of this Code

void abc(int n) {
if (n <= 10) {
abc(++n);
printf("%d\n", n);
}
}
void main() {
int m = 5;
abc(m);
}
The output shows:
11
10
9
8
7
6
I cannot understand the output. Please explain. I am a novice code lover.
The sequence of events is this:
main calls abc(5).
abc(5): n is <= 10, hence n is incremented to 6, calling abc(6).
abc(6): n is <= 10, hence n is incremented to 7, calling abc(7).
abc(7): n is <= 10, hence n is incremented to 8, calling abc(8).
abc(8): n is <= 10, hence n is incremented to 9, calling abc(9).
abc(9): n is <= 10, hence n is incremented to 10, calling abc(10).
abc(10): n is <= 10, hence n is incremented to 11, calling abc(11).
abc(11): n is not <= 10, function returns without any output.
back to abc(10): its own n variable is still 11, printf prints 11, function returns.
back to abc(9): its own n variable is still 10, printf prints 10, function returns.
back to abc(8): its own n variable is still 9, printf prints 9, function returns.
back to abc(7): its own n variable is still 8, printf prints 8, function returns.
back to abc(6): its own n variable is still 7, printf prints 7, function returns.
back to abc(5): its own n variable is still 6, printf prints 6, function returns.
main returns
Complete output:
11
10
9
8
7
6
Each instance of abc() has its own value for local variable n, which explains why the values printed by the different instances are different.
Note that you should also:
include <stdio.h>
define main with this prototype: int main(void)
for good style, add a return 0; statement at the end of main.
I would first suggest you to read basics of recursion. It will be good for you.
Now about All the recursive calling, it will be like as bellow:
abc(5);
This will call the function abc with value 5.
Now before printing it, it will make the recursive call to abc but before calling it will increment the value of n from 5 to 6. The same will happen in the next call from 6 to 7, 7 to 8, 8 to 9, 9 to 10 and 10 to 11. Now on the call for n=11, the if condition will fail and recursion will stop. On returning from recursive calls, it will print increment values but from last call to first,i.e. for 11 than 10 and so on till 6.
void abc(int n)
{
if (n<=10)
{
abc(++n);
printf("%d\n",n);
}
}
void main()
{
int m=5;
abc(m);
}
When main is called, a variable m is initialized to 5.
abc is then called and the 5 is passed to it.
When abc first executes, n = 5. If n is less than or greater than 10, abc is called again but this time with 1+n. Therefore, since 5 is less than 10, abc is called and 6 is passed to it.
First off in these lines of code, what is the output?
printf("7\n");
printf("6\n");
If you guess 7 before 6 you are correct. If you call two functions that prints something, the one called first will output first. This is very important
Lets first rewrite your function so that each line doesn't do separate things. I'm thinking of the mutating ++n:
void abc(int n) {
if (n <= 10) {
n = n + 1;
abc(n);
printf("%d\n", n);
}
}
So if you pass 9 to this it will first change n to 10, then call abc(10) and get the output of that before it prints 10. The call to abc(10) increases its n to 11 and calls abc(11) first, which doesn't do anything, then does its printf "11\n" and returns to the call where n is 10 and do its printf "10\n" before it returns to the initial call.
The output is:
11
10
If you do abc(5) it works the same. abc(6) needs to output first. And in abc(6) abc(7) needs to output first all the way to 11 thet doesn' have output and then it goes back, prints 11, 10, .... n + 1.
You can do it the other way around!
Lets say you start at the base case abc(11) and see the code doesn't do anything.
Then you look at abc(10). You see it will first increase n to 11, then call abc(11) which we previously saw does nothing and then it prints n, thus 11. Thus abc(10) prints "11\n".
If you look at abc(9) you see that n increases to 10, then it calls abc(10). You already know that that it prints "11\n", then it does its printf adding `"10\n" to the output, thus:
11
10
Now if you do this with one number lower you eventually get to abc(5).. It increases n to 6, then calls abc(6) which you know outputs "11\n10\n9\n8\n7\n" and then it does the next line that prints "6\n" making the output of abc(5) "11\n10\n9\n8\n7\n6\n"
To make the function clear exclude the recursive code of it itself the following way
void abc(int n)
{
if (n<=10){
++n;
printf("%d\n",n);
}
}
So if the function is called with argument equal to 5 then the function outputs 6. If the function is called with argument equal to 10 then the function outputs 11 due to the expression statement
++n;
Now just add the recursive call the following way
void abc(int n)
{
if (n<=10)
++n;
{abc( n);
printf("%d\n",n);
}
}
and you will get the described result.
Take into account that according to the C Standard the function main shall be declared like
int main( void )

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.

Factorial Function in C

I recently started reading Hacking: The Art of Exploitation by Jon Erickson. In the book he has the following function, which I will refer to as (A):
int factorial (int x) // .......... 1
{ // .......... 2
int i; // .......... 3
for (i = 1; i < x; i++) // .......... 4
x *= i; // .......... 5
return x; // .......... 6
} // .......... 7
This particular function is on pg. 17. Up until this function, I have understood everything he has described. To be fair, he has explained all of the elements within (A) in detail, with the exception of the return concept. However, I just don't see how (A) is suppose to describe the process of
x! = x * (x-1) * (x-2) * (x-3)
etc which I will refer to as (B). If someone could take the time to break this down in detail I would really appreciate it. Since I am asking for your help, I will go through the elements I believe I understand in order to potentially expose elements I believe I understand but actually do not but also to help you help me make the leap from how (A) is suppose to be a representation of (B).
Ok, so here is what I believe I understand.
In line 1, in (int x), x is being assigned the type integer. What I am less sure about is whether in factorial (int x), int x is being assigned the type factorial, or if even factorial is a type.
Line 3 is simple; i is being assigned the type integer.
Line 4 I am less confident on but I think I have a decent grasp of it. I'm assuming line 4 is a while-control structure with a counter. In the first segment, the counter is referred to as i and it's initial value is established as 1. I believe the second segment of line 4, i < x, dictates that while counter i is less than x, keep looping. The third segment, i++, communicates that for every valid loop/iteration of this "while a, then b" situation, you add 1 to i.
In line 5 I believe that x *= i is suppose to be shorthand for i * x but if I didn't know that this function is suppose to explain the process of calculating a factorial, I wouldn't be able to organically explain how lines 4 and 5 are suppose to interact.
'I humbly ask for your help. For any one who helps me get over this hump, I thank you in advance. '
I think the program given in the book is wrong. Theoretically, the for-loop will never terminate, as x is growing in every iteration, and much faster than i.
In practice, x will overflow after some time, thus terminating the loop.
Forget about why this calculates the factorial for a moment. First let's figure out what it does:
int factorial (int x) // .......... 1
{ // .......... 2
int i; // .......... 3
for (i = 1; i < x; i++) // .......... 4
x *= i; // .......... 5
return x; // .......... 6
} // .......... 7
Line 1:
Ignoring the part in the parenthesis for now, the line says int factorial (...) - that means this is a function called factorial and it has a type of int. The bit inside the parenthesis says int x - that means the function takes a parameter that will be called x and is of type int. A function can take multiple parameters separated by commas but this function takes only one.
Line 3:
We are creating a variable which we will call i of type int. The variable will only exist inside these curly braces so when the function is finished i will not exist any more.
Line 4:
This is indeed a looping control that uses the variable i created on line 3 to keep the count. At the start of the loop, the i=1 makes sure the count starts at 1. The i<x means it will keep looping as long as i is less than x. The i++ means each time the loop finishes the stuff in the curly braces the variable i will be incremented. The important part of this line is that the loops stops when i gets to x - which, as we will see, never happens.
Line 5:
The x*=i means the value of x will be updated by multiplying it by i. This will happen each time the loop iterates. So, for example, if x was equal to 5 the loop will make i equal to the values 1, 2, 3 and 4 (the numbers from 1 up but less than x) and the value of x will be updated by multiplying it by 1, 2, 3 and 4, making it larger and larger. But now that x is larger, the loop doesn't end here as expected - in fact, it contines looping making x larger and larger until the value of x no longer fits into an int. At that point, the program has undefined behaviour. Because compilers assume no one would want undefined behaviour, the program can do absolutely anything at that point including crashing or looping infinitely or even rewriting the whole program so it doesn't do any calculations at all.
Line 6:
We need to get that value of x back to the outside world and that is what the return command does - if the program gets to here the return statement gives the factorial function the value of x (which is the value of the factorial of 5 in the example we just used).
Then somewhere else in your program you might do this:
int f;
f = factorial(5);
Which will make the parameter called x have an initial value of 5 and will make f have the final value of the function.
So what does it return? Well, there is undefined behaviour so anything could happen - but because x gets larger and larger it definitely will NOT return the factorial. Anything could happen, but in my tests factorial(5) returns a huge negative number.
Try it online!
So how do we fix it? Well, as #JonathanLeffler said, we can't change the value of x so we need a new variable to hold the result. We will call that variable r:
int factorial (int x)
{
int r = 1;
for (int i = 1; i < x; i++)
r *= i;
return r;
}
So this program changes the value of r and doesn't change the value of x. So the loop works properly now. But it still doesn't calculate the factorial of the value passed in - if x is 5 it multiplies all the values up to but not including x.
Try it online!
So how do we fix it? The factorial has to include all the values including x, so this actually calculates the factorial:
int factorial (int x)
{
int r = 1;
for (int i = 1; i <= x; i++)
r *= i;
return r;
}
And this works as long as the value of x you pass in is small enough that the factorial can fit into a signed int.
Try it online!
You could get more range by using an unsigned long long but there is still a maximum value that can be calculated.
The program loops through integers 1 thru N-1. (Assume the input value is 'N')
Before loop starts, x=N.
After one iteration, x=N*1.
After 2 iterations, x=N*1*2.
After N-1 iterations, x=N*1*2*....(N-1).
Which is N factorial.
So N! is returned.
The fifth line is : x *= i;
You should understand here : x = x * i;
The loop will execute while i < x. Which means until reaches x - 1;
Knowing that i begins at 1 you will get this sum : x * 1 * 2 * 3 * ... * ( x - 1)
You can rearrange this so you get : 1 * 2 * 3 * ... * (x - 1) * x

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