This code is giving an absurd answer [duplicate] - c

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
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>
count(int);
main(){
int x=10,z;
z=count(x);
}
count(int m){
if(m>0)
return count(m-1);
}
When count is called for the first time with argument 10, it fulfils the condition and the recursion starts. What happens really when a function calls itself? I dont get it. What does the statement return count(m-1) mean? Where does it tranfer the control?

The return value of the function count is undefined, because there is no default return if (m <= 0) is true.
C11, ยง 6.9.1 Function definitions
If the } that terminates a function is reached, and the value of the
function call is used by the caller, the behavior is undefined.
Besides, to understand how a recursive function works, you have to take a paper and try to execute the code by yourself (see also here).

You need count to return something when m <= 0. You should declare the return type of count and compile with -Wall so the compiler will help you find mistakes in your code.

recursion means that the function will call itself, mostly at the end of itself, if it's tail recursion.
So your count function checks that the input argument is > 0 and then if it is, it will call count(m-1). Now it starts at the top of count with m=9. It does the same thing, and then calls count with m=8, etc.
Until the end condition is reached, which should normally be explicitly catered for in your function, such as if (m == 0) return m; or some such thing. At that point the recursion ends and the function terminates.
Also, count should have a return type, such as int count (int m)

what does the statement return count(m-1) mean ? where does it tranfer the control?
That seems to be your only question.
it means that it is calling "count" with the value m-1. So if m was 10, then it is calling "count" with 9.
It is transferring the control recursively to the count method.
You also don't have a return for the every possible path in the "count" method.
What happens if m is <= 0?

Related

Recursive function for finding factorial of a number

I am getting an output of 24 which is the factorial for 4, but I should be getting the output for 5 factorial which is 120
#include <stdio.h>
int factorial(int number){
if(number==1){
return number;
}
return number*factorial(--number);
}
int main(){
int a=factorial(5);
printf("%d",a);
}
Your program suffers from undefined behavior.
In the first call to factorial(5), where you have
return number * factorial(--number);
you imagine that this is going to compute
5 * factorial(4);
But that's not guaranteed!
What if the compiler looks at it in a different order?
What it if works on the right-hand side first?
What if it first does the equivalent of:
temporary_result = factorial(--number);
and then does the multiplication:
return number * temporary_result;
If the compiler does it in that order, then temporary_result will be factorial(4), and it'll return 4 times that, which won't be 5!. Basically, if the compiler does it in that order -- and it might! -- then number gets decremented "too soon".
You might not have imagined that the compiler could do things this way.
You might have imagined that the expression would always be "parsed left to right".
But those imaginations are not correct.
(See also this answer for more discussion on order of evaluation.)
I said that the expression causes "undefined behavior", and this expression is a classic example. What makes this expression undefined is that there's a little too much going on inside it.
The problem with the expression
return number * factorial(--number);
is that the variable number is having its value used within it, and that same variable number is also being modified within it. And this pattern is, basically, poison.
Let's label the two spots where number appears, so that we can talk about them very clearly:
return number * factorial(--number);
/* A */ /* B */
At spot A we take the value of the variable number.
At spot B we modify the value of the variable number.
But the question is, at spot A, do we get the "old" or the "new" value of number?
Do we get it before or after spot B has modified it?
And the answer, as I already said, is: we don't know. There is no rule in C to tell us.
Again, you might have thought there was a rule about left-to-right evaluation, but there isn't. Because there's no rule that says how an expression like this should be parsed, a compiler can do anything it wants. It can parse it the "right" way, or the "wrong" way, or it can do something even more bizarre and unexpected. (And, really, there's no "right" or "wrong" way to parse an undefined expression like this in the first place.)
The solution to this problem is: Don't do that!
Don't write expressions where one variable (like number) is both used and modified.
In this case, as you've already discovered, there's a simple fix:
return number * factorial(number - 1);
Now, we're not actually trying to modify the value of the variable number (as the expression --number did), we're just subtracting 1 from it before passing the smaller value off to the recursive call.
So now, we're not breaking the rule, we're not using and modifying number in the same expression.
We're just using its value twice, and that's fine.
For more (much more!) on the subject of undefined behavior in expressions like these, see Why are these constructs using pre and post-increment undefined behavior?
How to find the factorial of a number;
function factorial(n) {
if(n == 0 || n == 1 ) {
return 1;
}else {
return n * factorial(n-1);
}
//return newnum;
}
console.log(factorial(3))

Can someone explain output of this C program? [duplicate]

This question already has answers here:
unexpected output in C (recursion)
(3 answers)
Closed 4 years ago.
#include <stdio.h>
int main()
{
static int i = 5;
if (--i)
{
main();
printf("%d\n", i); // will this line executes ?
}
return 0;
}
Output:
0
0
0
0
does code below main(); printf statement instructions is placed to stack every time when main recursive calls happens and executed while terminated from this program?
i is reduced by successive calls to main until zero is reached.
Then printf is called for each level of recursion.
(Note that the behaviour of calling main from itself is well-defined although ill-advised in C, in C++ the behaviour is undefined.)
if (--i)
This will evaluate true the first time (--i == 4). The code recurses into main(). (Recursion: A function calling itself.)
As i is static, it will retain its value of 4 (as opposed to an automatic variable, which would be initialized to 5 again). The if (--i) in this second execution of main() will again be true (evaluating to 3), and will again call main() (for a third execution of the function).
The same for --i == 2 and --i == 1, for four executions of main() (including the first, non-recursive one) total that are evaluating the if condition to true.
The next recursion will evaluate the if condition to --i == 0, and thus false. Skipping the if clause, the function call will just return. i is zero at this point, and -- being static, i.e. only one persistent i for all instances of main() -- will remain at that value.
The main() call one level up the stack -- the one that evaluated --i == 1, then called main() and was waiting for it to return -- will now continue with the statement after the call to main(), and printf() the current value of i... which is 0.
The same happens three more times (for a total of four) until the top-most main() returns. You get four times the current value of i, which is 0.
Note that calling main() from your program is allowed in C, but not in C++. This is specifically for calling main() recursively; for other functions, it is allowed in either language.
(--i) will decrease the value of i to 4 when it is called for the first time and it will continue the decrement of i until (i==0) due to recursion.
Since you have declared the variable i with static keyword and hence a single memory is allocated to it and all the changes are reflected back to it

count_calls() function and the return value

im going through an old exam past paper and had this question
int c = 0;
int count_calls()
{
c = c + 1;
return c;
}
Now it asks why would this go wrong i.e. the number of calls counted is incorrect? is it right to say that no matter what c is set to in the count_calls() function it will always be zero due to the fact c is always defined as 0 outside the class? and would changing it to ++c or +CC fix this issue?
function increments global variable (and it will be correctly incremented by 1 every time the function was called), but when it returns, it creates local copy.
in the range of int type, it can count calls
generally speaking, it's bad code (it can't be used in parallel)
it wouldn't changed with moving to ++c

Why does this recursive function loop infinitely rather than printing numbers in reverse?

int reverse(int);
void main()
{
int no =5;
reverse(no);
}
int reverse(int no)
{
if(no == 0)
return 0;
else
printf("%d",no);
reverse(no--);
}
This program goes in infinite loop.Why is that so? I am not able to get the desired ouput.
Desired output should be 5 4 3 2 1.Thank you in advance
In this recursive call:
reverse(no--);
You are passing the value of no--. Since this uses the postfix -- operator, this means "decrement no, then pass the original value of no into the recursive call to reverse." This causes infinite recursion, since you are constantly making a recursive call with reverse set to the same value.
To fix this, change this to read
reverse(no - 1);
Notice that there's no reason to decrement no here, since within the current recursive call you will never read no again. You can just pass the value of no - 1 into the function. In fact, you might want to in general avoid using -- in recursive calls, since it almost always indicates an error in the code.
Hope this helps!
You're using the post-decrement operator on no. That first gets the value of no and uses that as the value of the expression and then decrements no (still using the undecremented value as the value of the expression). You probably want to use --no or even just no - 1. (The former will modify no, whereas the latter will not, but it does not matter because no is not referenced after that point.)
Change:
reverse(no--);
to:
reverse(no-1);
no-- returns the original value before the decrement occurred. So this line will always call reverse(5). Hence, infinite loop.
n-- is post increment which first use n as argument of the function and then decrement n.
So n-- essentially does is
reverse(n);
n = n - 1;
What you want is --n
You are using post-decrement. First evaluates, then reduces value.
Change this:
reverse(no--);
to this:
return reverse(--no);
--no is pre-decrement. First decrease "no", then pass the value to reverse.
Note that I'm RETURNING the result value, you function always have to return an int, due to its declaration.
You want to do
int reverse(int);
int main()
{
int no =5;
reverse(no);
}
int reverse(int no)
{
if(no == 0)
return 0;
else
printf("%d",no);
return reverse(--no);
}
So that you're returning a number every time you call reverse and you decrement no before you use it.

Recursion in C with Pre increment [duplicate]

This question already has answers here:
Why are these constructs using pre and post-increment undefined behavior?
(14 answers)
Closed 5 years ago.
int fact_rec(int n)
{
printf("%d\n",n);
if(n==1) return n;
else return fact_rec(--n)*n;
//else return n*fact_rec(--n); gives same result
//correct output comes for n*fact(n-1)
}
In the above recursive implementation of the factorial function,
fact_rec(5) returns 24. Whereas, if I use
n*fact_rec(n-1)
in place of
n*fact_rec(--n)
the output is correct : 120.
Also, it doesn't matter whether I use
n*fact_rec(--n)
or
fact_rec(--n)*n.
Shouldn't it matter if I use
n*fact_rec(--n)
or
fact_rec(--n)*n?
And shouldn't the output have
been 120 in all the cases?
return fact_rec(--n)*n
is dangerous. The order of argument evaluation is undefined in C (except for &&, ||, comma and ternary operators) so value for second occurrence of n could vary.
The rule of thumb: never use variable you are incrementing/decrementing twice in one expression.
Your confusion seems to be about the order - unlike the other answers, I am assuming you already know what --n does...
The compiler knows it needs the value of fact_rec(--n) before it can evaluate fact_rec(--n)*n whichever way round you write it, so the function is evaluated first, and the value of n multipled has always already been decremented.
There is actually no need to modify n at all. return n * fact_rec(n - 1) takes care of it and is the right way to do it.
--n in your function really means:
int fact_rec(int n) {
printf("%d\n",n);
if(n==1) {
return n;
} else {
n = n - 1; /* <---- effect of --n */
return fact_rec(n)*n;
}
}
The problem is here:
else return fact_rec(--n)*n;
you're decrementing n before the multipliation
so if n starts as 5 it runs as
return fact_rec(4)*4;
Edit: Down voted for a correct answer to the question? I don't get it.

Resources