How does one recursion in a forloop work? [closed] - c++

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 7 years ago.
Improve this question
I can't understand this example.I understand the principle of the recursive functions,but in this example i can't understand this recursion in the forloop.
Could someone explain me this example?
#include <iostream>
using namespace std;
void f(int n)
{
cout << n;
for (int i=3; i<n; i=i+1)
f(n-1);
cout << n;
}
int main()
{
f(5);
return 0;
}

f(5) will call f(4) twice, i.e. for i=3 and 4
f(4) will call f(3) once, i.e. for i=3
f(3) will not do further calls of f because 3<3 is false
So you have
f(5)
f(4)
f(3)
f(4)
f(3)
So now just add the print:
f(5)
5 // on entry
f(4) // because i is 3, n is 5
4 // on entry
f(3) // because i is 3, n is 4
3 // on entry
// no further call because i is 3, n is 3
3 // on return
// no further call because i is 4, n is 4
4 // on return
f(4) // because i is 4, n is 5
4 // on entry
f(3) // because i is 3, n is 4
3 // on entry
// no further call because i is 3, n is 3
3 // on return
// no further call because i is 4, n is 4
4 // on return
// no further call because i is 5, n is 5
5 // on return
so the output is
5433443345

It works the same way recursion works anywhere else. The function calls itself. Since it's in a loop it may do so multiple times.
What's causing you confusion?
I would suggest stepping through with a piece of paper and just writing down what the output should be. Follow the logic all the way through.

Sorry this is in java and not in C but I already had this typed up.
This is probably the most understandable recursive algorithm in my opinion.
the factorial of 5 is 120 for reference.
1. run through the code
2. write down the value of variables at each point
3. check the output with the correct answer
once you understand this simpler recursive algorithm run through your convoluted example again and see if it makes a little more sense.
Java Example:
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(fact(5));
}
public static int fact(int n){
if(n < 1){
return 1;
}
else{
return n*fact(n-1);
}
}
}
Hope this helps!

Related

DFS Traversal in graph [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am trying to do dfs traversal using recursive call, My Graph, and vector<int>visited are global variables. num_v variable corresponds to number of vertices,num_e corresponds to number of edges I tried calling two DFS calls in main, but my output matches to the correct DFS order for the first case. and it gives incorrect out for the other, kindly help where I'm getting wrong in the implementation of it.
sample input: first line is a number of vertices and number of edges. next, each line is directed nodes between two-point.
5 5
1 2
2 4
4 5
5 3
1 3
expected output:
1 2 4 5 3
2 4 5 3
my wrong output
1 2 4 5 3
2
code:
#include<iostream>
#include<vector>
#include<stack>
using namespace std;
int mx=1e5;
//int num_v;
vector<vector<int>>Graph(mx);
vector<int>visited;
void dfs(int v,vector<int>&vec){
visited[v]=1;
vec.push_back(v);
for(int neigh:Graph[v]){
if(visited[neigh]!=1){
dfs(neigh,vec);
}
}
}
int main(){
int num_v;int num_e;
cin>>num_v>>num_e;
visited.resize(num_v + 1);
for(int i=0;i<num_e;i++){
int u,v;
cin>>u>>v;
Graph[u].push_back(v);
}
vector<int>vec;
dfs(1,vec);
for(auto x:vec){
cout<<x<<" ";
}
visited.clear();
cout<<endl;
vector<int>tt;
dfs(2,tt);
for(auto y:tt){
cout<<y<<" ";
}
}

Function call in for loop declaration [closed]

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.

Output of the c program [closed]

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 4 years ago.
Improve this question
When running the following code, the output is 2 4 6. I expected it to be 2 5 and so on...
Why the difference?
#include <iostream>
using namespace std;
int main() {
static int i;
for (i++; ++i; i++) {
printf("%d ", i);
if (i == 6)
break;
}
return 0;
}
I did the same thing here, without the for loop, from 2nd iteration. The result is 5.
Why is that?
#include <iostream>
using namespace std;
int main() {
static int i=2;
i++;
i++;
cout<<++i;
return 0;
}
Each time the loop is traversed you increase i by two, not three (I guess you expected the latter to happen).
In a general case
for ( init_statement ; condition ; iteration_expression ) {
loop_statements
}
is equivalent to
init_statement
for ( ; condition ; ) {
loop_statements
iteration_expression
}
and
init_statement
while ( condition ) {
loop_statements
iteration_expression
}
See, e.g., this.
In your case,
for (i++; ++i; i++) {
...
}
is equivalent to
i++
for ( ; ++i; ) {
...
i++
}
and
i++
while ( ++i ) {
...
i++ ;
}
As for your second piece of code, you mention that "The result is 5". It appears you expect otherwise, perhaps 4. If so, try replacing
cout<<++i;
with
cout<<i++;
(incrementing prior vs. after other operations in the sentence).
When you see the syntax of for loop which is
for(initialize;condition;inc/decrement)
the statement in initialize block only executes once at the starting of for loop that's why it is increamenting i by 2.
Hopefully that help
In a for loop you've got 4 parts. I forget the "official" name for the individual pieces but I typically refer to them as:
Initialization
Anchor Statement
Body
Follow-up
effectively:
for(Initialization (1); Anchor Statement (2); Follow-up (4))
{
Body (3)
}
It's going to hit in the following order:
1, 2, 3, 4, [2, 3, 4]... until step 2 evaluates to false or a break statement is hit. Then it exits.
So i starts as 0.
You hit step 1 and 2, making i evaluate to 2 in step 3 (the body).
Then you hit step 4 and 2, making i evaluate to 4 in step 3.
Then you hit step 4 and 2, making i evaluate to 6 in step 3.
Then you have a break statement that will exit the loop.
The important part that seems to be the confusion, is that the initialization step only runs once.

What is the logic behind this recursive program to find factorial in c++? [closed]

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.

recursion and return statement in C++ [closed]

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 ..