Function call in for loop declaration [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 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.

Related

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.

Order of Evaluation for passing function arguments - Order of operations for F1( int F2( int& x ), int x )

Okay so I was writing some code earlier. This was the line specifically:
EnterNode( FindNode( terrain_X, terrain_Y, travel_dir ), travel_dir );
I noticed after testing my program something weird was happening. The value being received by the outer function was not the value I was reading when I inspected the stack.
I made an example program:
https://ideone.com/wNjJrE
#include <iostream>
int modifyRef(int& A)
{
A = 0;
std::cout << "\nint& A = 0";
return A;
}
void TakeValues(int X, int Y)
{
std::cout << "\nX = " << X;
std::cout << "\nY = " << Y;
}
int main()
{
int Q = 9;
TakeValues(modifyRef(Q), Q);
std::cout << std::endl;
system("pause");
return 0;
}
This is the output I receive:
int& A = 0
X = 0
Y = 9
I would expect Y to also be 0. How is the order of operations defined for parameter binding to function calls?
(My apologies if I am not using the correct terminology.)
The evaluation order of function arguments is unspecified. When you write:
TakeValues(modifyRef(Q), Q);
you are relying upon the fact that modifyRef(Q) to be evaluated before Q. But the evaluation order of function arguments is unspecified - it is not necessarily the case that modifyRef(Q) will be sequenced before Q nor vice versa.
In this case, Q (the second argument) gets evaluated first. So we read 9, and initialize the parameter Y with it. Then we evaluate modifyRef(Q), which zeros out Q and returns it, which leads to initializing X with 0.
Try changing the signature of your functions:
int ModifyRef( int& A );
void TakeValues( int X, int Y );
to the following...
int& ModifyRef( int& A );
void TakeValues( int& X, int& Y );
and see what your output will be in main when you call this line of code:
int q = 9;
TakeValues( ModifyRef(q), q );
then reverse the order of the parameters as such
TakeValues( q, ModifyRef(q) );
and compare the results.
When I did this on my machine Win 7 64bit with VS2015 Community on an Intel Core2 Quad Extreme the results I was given for both situations when using references were the same and the output I am getting is:
I changed the value of A in ModifyRef() from 0 to 7 for testing purposes.
int& A = 7
X = 7
Y = 7
for both situations where either the inner function is the first parameter and the stand alone variable is the second or the inner function is the second parameter with the stand alone variable as the first.
Since I am receiving the same results it appears to me that do to how the compiler creates and handles the stack pointer the ModifyRef() appears to be evaluated first and once that function is finished since q is now being referenced instead of being a stack copy it is being overwritten by whatever value it is being set to within the ModifyRef function.
I also modified your ModifyRef() function slightly so that I can see what its passed in parameter is instead of having a number hard coded into its print out statement.
int& ModifyRef( int& A ) {
A = 7; // Changed Value From 0 To 7 For Testing Purposes
std::cout << "n\int& A = " << A;
return A;
}
However this effect may only apply when using only references.
When I revert back to your original function signatures and I call it in this order:
q = 9;
TakeValues( ModifyRef( q ), q );
As is your original code was presented the output I am getting is:
int& A = 7
X = 7
Y = 9
However when I reverse the parameters to:
q = 9;
TakeValues( q, ModifyRef( q ) );
My output is:
int& A = 7
X = 7
Y = 7
So what I am seeing in these two situations is slightly different.
In the first order of parameters, Y or the second parameter is being set to 9 as q is initialized to 9 and Y within TakeValues() is printing out a stack copy with a value of 9. Then X is being valuated by ModifyRef() where q has a value of 9 but then it is being modified since it is a reference so when TakeValues() sets X from q, q was already changed from 9 to 7 so X is now being set to 7.
In the second order of parameters it appears that ModifyRef() is being called first and changes q from 9 to 7 so TakeValues() is setting Y to 7 and since this function is using a reference q was also changed from 9 to 7, so when the first parameter is taking q to set X q was already changed from 9 to 7.
I do not know if this is compiler dependent but at least on my machine it appears that the call stack for the parameters is happening from farthest right to left. This also makes sense when you think about it due to when functions have default values.
Example:
class foo {
void bar( int a, int b, int c = 3 ) {
std::cout << a << ", " << b << ", " << c << std::endl;
}
};
All default values in a function declaration must be to the far right for you can not have:
class foo {
void bar( int a = 1, int b, int c ) { ... } // Compile Error
};
I hope this helps to clarify what is going on within your code when you begin to call a function within a function as a parameter either if you are using passing by value(stack copy) or by reference.

C++ Pointers and reference and functions

I dont understand how this code works can you please explain it to me.
#include <iostream>
using namespace std;
int fun (int &x, int &y) {
if (y<=0)
return x;
x=x+2;
cout<<x<<y<<endl;
return x*y;
}
int main () {
int x=5, y=-1;
cout <<fun(x,y)<<endl;
fun(y,x);
fun(x,y);
fun(y,x);
cout <<fun(x,y)<<endl;
return 0;
}
the correct answers are
5
15
71
37
93
27
The first function call cout << fun(x,y) << endl; passes x as 5 and y as -1. Because y is less than 0 the function simply returns x to cout, so it prints 5.
The next function call fun(y,x) which still passes -1 and 5, however this time the values are passed in reverse so within the function x is -1 and y is 5. Because y is 5 the if statement is false and x is assigned -1 + 2, or 1. Then x as 1 and y as 5 are printed and the multiplication of the two is returned, however nothing is done with the multiplied value.
The third function call passes x and y, but in the previous function call x (as y) was changed to 1. Because the value was passed in as a reference of y, it is now 1. So, x is assinged 5 + 2 and x and y are printed as 71.
The fourth function call passes x and y again in reverse. So, recall that x was changed to 7 and y is 1. But the values are in reverse so in our function x is 1 and y is 7. So again x is assigned the value of 1 + 2 and these are printed as 3 and 7.
Finally, the last function call passes x and y, but remember that x (as y) was changed to 3. So now x is 7 and y is 3. Once more x is assigned 7 + 2, and x and y are printed as 93. Since the function was called from a cout statement the multiplication of 9 and 3 is also printed as 27.

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