Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I know a little bit about recursion ,but I don;t understand the return statement in which function is calling again and again, could any body help me please to understand this?
The return statement in recursion has different use.
To get termination condition or stop recursion from infinite call.
Return some data which is used by calling step before current call.
Example:
int recursion_demo(int x)
{
// Termination condition
if(x <= 0)
return 0;
print x;
//This statement return sum of 1 to x
return x + recursion_demo(x-1);
}
Suppose we call this function as recursion_demo(5). It will print numbers from 5 to 1. Now if we will not have termination condition this recursion will keep running. The last line is recursively calculation sum of numbers from 1 to 5. so it will finally return 15. Internally function call will be in this order:
recursion_demo(5);
5 + recursion_demo(4);
4 + recursion_demo(3);
3 + recursion_demo(2);
2 + recursion_demo(1);
1 + recursion_demo(0);
recursion_demo(0) will terminate this call and their will be no further recursive call. Now it will start roll back. recursion_demo(0) has return 0
so
1 + recursion_demo(0) will be 1 + 0; = 1;
1 will return to 2 + recursion_demo(1); and this will become 2 + 1 and so on and finally recursion_demo(5) will return 5+4+3+2+1 = 15.
This is an example of recursion where a function is calling again and again in C++.
int foo() { //1.
return foo(); //2.
}
Let's go over an explanation of the code (the comments match up with the numbers).
Control arrives at foo().
foo() has started, and it arrives at the line return foo();. Whoops, looks like it is time to run foo() again!
Go back to line 1. Repeat until the computer runs out of battery, memory, etc.
Recursion contains an if statement ... a base case and a recursive case. for e.g
int num(int x)
{
if (x==0)
return 0;
else
return num(x-1);
}
here the num function is once again called in the num function but with a decremented value. The output will be 5,4,3,2,1,0 for x = 5; here the "0" is the base case where the function stops ..
Related
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 1 year ago.
Improve this question
I dont really understand i have written return in the end but still it gives error
CODE :
int factorial(int num)
{
int N;
if (num > 1)
{
N = (num * factorial(num--));
}
else
return N;
}
int main()
{
cout << factorial(5);
return 0;
}
ERROR : warning: control reaches end of non-void function [-Wreturn-type]
16 | }
Your issue is that you don't return anything. If you look at the flow of the program you can see that for num > 1 you do the factorial stuff and for num <= 1 you just return N. For num > 1 the return statement is never reached. This issue can be fixed by removing the else, BUT that leaves an other issue mentioned, namely that for num <= 1 N is never initialised. If you initialise it to 1 that should solve that, but as people pointed out you don't need N, you can do return num * factorial(num - 1); and simply return 1 for num <= 1. The final problem with your code is that you do num * factorial(num--). factorial(num--) will call factorial(num), when you would need factorial(num-1), because num-- is the post-decrement operator.
Other suggestions in the comments are good to heed as well, like implementing guards from integer overflow and the like.
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 2 years ago.
Improve this question
I came across this code:
#include<iostream>
using namespace std;
int main()
{
int a=5,
b=a++ - 2;
cout << b;
return 0;
}
The output is 3. Why is it not 4?
-2 or - 2 should not give any error
see there are two types of operator post increment and pre increment
a++ is post increment it means first it will assign the value then it will increase the value by 1
meaning b = 5 - 2;
a will get get increased by 1
a=6 now but in the equation it will be 5
but if you do ++a
then it will first increase the value then assign
meaning b = 6 - 2;
-2 or - 2 wont give any error
check here
Lets break it down step by step.
These type of comma separated expressions happen from left to right. So its the same as this,
int a = 5;
int b = a++ - 2;
In this, a++ increments the value of a by one and then assigns it to it. Then the - 2 happens. Simply what happens under the hood is,
// Here 5 is the value of a.
int b = 5 - 2, a = a + 1;
More info: Incrementing in C++ - When to use x++ or ++x?
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 2 years ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
Could anybody explain me how this code is actually working?
when I run it, It gives me 52 as an output.
#include <iostream>
using namespace std;
int Fun(void){
static int x=7;
return x--;
}
int main(void)
{
for(Fun();Fun();Fun())
cout<<Fun();
return 0;
}
Every "regular" for loop has 3 parts :
initialization
condition
iteration
On entering x is 7, initialization will return 7, decrement and go on with the condition where x is now 6. Upon condition it will return 6 (which is truthy), decrement and go on with the body where x is now 5. Upon printing, it will return 5, decrement and go on with the iteration where x is now 4.
Upon iteration it will return 4, decrement and go on with the condition where x is now 3. Upon condition it will return 3 (which is truthy), decrement and go on with the body where x is now 2. Upon printing it will return 2, decrement and go on with iteration where x is now 1.
Upon iteration it will return 1, decrement and go on with the condition where x is now 0. Upon condition it will return 0, which is falsy, and thus break out of the loop.
One of the important things to understand is that x is static and thus is part of the "state" of the function. It is initialized on first call and reused on each call.
probably you better understand with this code, since you are doing cout << Fun(); you see only the value at that time, you can see the return value at each phase with below code.
first initialization of for you get 7,
second condition check you get 6, since its non zero enters into loop.
inside loop call Fun which prints 5
then go to update part of for loop where we receive is 4
after that go to condition check it gives 3, since its non zero enter the loop
inside loop this time it will print 2
then go to update part of for which return 1
then go to condition check which gets 0, loop terminates.
#include <iostream>
using namespace std;
int Fun()
{
static int x=7;
return x--;
}
int main( )
{
int x, y, z = 0;
for( x = Fun(); y = Fun();z = Fun())
cout<<"x = " <<x<<" y = "<<y<<" z = "<< z<<" and Fun ="<<Fun()<<endl;
return 0;
}
After each call of the function Fun the static variable x is decremented. The function returns the value of the variable x before decrementing.
So in this for loop
for(Fun();Fun();Fun())
cout<<Fun();
Before the body of the loop gets the control the function Fun was called two times
for(Fun();Fun();Fun())
1 2
So after these calls the value of the variable x is equal to 5. This value is outputted in the statement
cout<<Fun();
and after the call of the function used in this statement the value of x becomes equal to 4.
Then again the function Fun was called two times
for(Fun();Fun();Fun())
2 1
So the value of the x becomes equal to 2. This value is outputted in the statement
cout<<Fun();
And after the call of the function in this statement the value of x is equal to 1. Then in the first call of Fun
for(Fun();Fun();Fun())
2 1
the value of x becomes equal to 0. This value is returned by the second call of the function. So the condition evaluates to boolean false.
Thus the loop outputted two numbers 5 and 2. The result value of the static variable x is -1. (0 was returned in the last call of Fun and after that the variable x was decremented)
To understand, you can "unroll" the loop:
int Fun()
{
static int x = 7;
return x--;
}
int main()
{
Fun(); // x is 6
if (!Fun()) return 0; // x is 5
std::cout << Fun(); // prints 5, x is 4
Fun(); // x is 3
if (!Fun()) return 0; // x is 2
std::cout << Fun(); // prints 2, x is 1
Fun(); // x is 0
if (!Fun()) return 0; // end
}
Note that Fun() returns a value which equals x+1.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have a task to make a code which will write 100 first numbers of an equation (or a function, I don't know what this is)
A(n) = (A(n-1))^2 -n*A(n-2) where A(1) = 1 and A(2) = 1
It has to be solved recursively. I have written this code so far
#include <iostream>
using namespace std;
int rekurzija(int n){
if(n=1){
return 1;
}
if(n=2){
return 1;
}
if(n>2){
return rekurzija(n-1)*rekurzija(n-1)-n*rekurzija(n-2);
}
}
int main(){
for(int n=1;n<101;n=n+1){
cout << rekurzija(n) << endl;
}
}
The problem is that the program returns 1 hundred times instead of 1,1,-2,0,...(instead of actually solving this function). What is wrong in this code?
You are using simple assignment operator = instead of Is equals to relational operator == in your rekurzija() function for if conditions
if(n = 1) //here `n = 1`is an assignment statement
{
//something...
}
What happens if you use = instead of ==?
The if condition will always evaluate to be true if the assigned value in the assignment statement is non-zero number.
Note: An assignment to zero evaluates to be false i.e, for if(n = 0), the if block will not be entered. You don't have any such if blocks in your code.
So your first if is always evaluated to be true because you are assigning a non-zero value i.e, 1 and thus your function always returns 1. that's the reason why you get 100 1's as your answer.
So, instead try changing all the if conditions to something like:
if(n == 1)
{
//something...
}
This would check if n is equals to 1 or not. If n is equal to 1 then the if block is entered, else it would not enter the if block and the next if condition is checked.
Note: Just remember this while using the = and == operators
= is for assignment
== is for comparison
When you compare things in C++ you need to do it like:
if (a == b)
and not
if (a = b)
The latter will assign b to a and return the value of a.
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 6 years ago.
Improve this question
#include<iostream>
using namespace std;
int factorial(int x)
{
if(x == 1)
{
return 1;
}
else
{
return x*factorial(x-1);
}
}
int main()
{
cout<<factorial(5)<<endl;
}
I don’t get the part when the value reaches 1. Why doesn't the program print 1 as the output, because when 1 is reached it returns 1. Consider the below steps.
5*factorial(4)=5*4*factorial(3)=5*4*3*factorial(2)=5*4*3*2*factorial(1)
So now, when the x value becomes 1 and goes into if , condition becomes true and 1 is returned. So why doesn't it output 1? Is it that the value of the 5*4*3*2*factorial(1) is stored somewhere and the returned value of just gets multiplied with 5*4*3*2*1 and outputs 120?
Also please explain, what happens when we pass 0 instead of 5,how will it output 1? (0!=1)
it is exactly like you said:
5*factorial(4)=5*4*factorial(3)=5*4*3*factorial(2)=5*4*3*2*factorial(1)
So if it reaches 1 then this will be replaced by
5*factorial(4)=5*4*factorial(3)=5*4*3*factorial(2)=5*4*3*2*1
so the result of the last step goes into the second last step.... where 2*1 will be calculated... After that the 3rd last step gets the value of 2*1 = 2 and multiplies 3 on in and so on.
If you insert smaller or equal 0 into your function, you will get an endless recursion because if(0 == 1). But if you replace this code with
int factorial(int x)
{
if(x <= 1)
{
return 1;
}
else
{
return x*factorial(x-1);
}
}
Then also 0 and -numbers will work
The stack stores in some sense all pending operations. As soon as fact(2) gets 1 from the call, it multiplies it by 2 and returns 2. fact(3) receives that 2, multiplies it by 3 and returns 6. fact(4) receives that 6, multiplies it by 4 and returns 24. And so on...
Passing a 0 was not thought of in the current form of the program and will actually cause the program to crash (most likely). Changing the if(x==1) line to if(x==0) will fix this.