Output of the c program [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 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.

Related

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.

Strange behaviour with decrement operator [closed]

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
My code is meant to print an array in reverse but for some reason the decrement operator isn't working as expected. According to my understanding --var decrements the variable var before anything is done to it while var-- decrements the variable var after an operation has been completed such as a for loop.
Here is my code:
#include <iostream>
int main() {
int arrLen;
int arr[4];
scanf("%d\n %d %d %d %d", &arrLen, &arr[0], &arr[1], &arr[2], &arr[3]);
for (; arrLen >= 0; --arrLen)
printf("%d %d\n", arr[arrLen], arrLen);
return 0;
}
And here are my results (the right value in the output is the decremented variable, I added it to check):
0 4
2 3
3 2
4 1
1 0
Without the decremented variable being printed it should be:
0 2 3 4 1
Here are my expected results:
2 3 4 1
The reason this is not behaving as you expect is because of how for loops work.
for (statement_1; condition; statement_2) {
body;
}
statement_1 is called only once before the loop begins.
condition is evaluated at the beginning of each pass in the loop. If it is true, body is evaluated. If not the loop exits.
statement_2 is evaluated after the body at the end of each pass in the loop, just before re-evaluating the condition.
So while --var does decrement and return the decremented value, it is only actually called after the body of your for loop each time it is run.
This means that --var and var-- will have the same effect on the behaviour of a for loop when part of statement_2.
To produce your desired behaviour you could change your for loop to this:
while (--arrLen >= 0)
printf("%d %d\n", arr[arrLen], arrLen);
Try with the following line. I think your for loop was not proper.
for (; arrLen > 0; --arrLen) printf("%d %d\n", arr[arrLen - 1], arrLen);
It will now have the following output
2 4
3 3
4 2
1 1

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.

I am not able to understand why output is coming 10 in this for loop [closed]

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
can anybody clear my doubt .. why this program is giving 10 as output.
can you please explain the mechanism .. for loop is also having ; before the statements also
#include <iostream>
using namespace std;
int main() {
int i ;
for ( i =0 ; i<10 ; i++);
{
cout<<i ;
}
return 0;
}
for ( i =0 ; i<10 ; i++);
This is a complete loop, the semicolon at the end indicates an empty body. Hence it simply increments i eventually to 10. The reason it's 10 (rather than 9) is because that is when the continuation condition i < 10 becomes false.
Which means that this little snippet:
{
cout<<i ;
}
is a once-executed statement outputting the contents of i (left at 10 by the loop).
The braces in this case simply put the statement into an enclosed scope, they are not related to the loop at all.
So, if you want to output i each time through the loop, simply get rid of the semicolon so that the braces and their contents become the body of that loop.
for ( i =0 ; i<10 ; i++); // This means loop till i = 10 at which point loop breaks. This is because of ending the for loop with ';'
{ // start of scope
cout<<i ; // Print the value of i which is 10 now
} // end of scope
Consider that the loop has reached a point where i = 9, so, 'i < 10' condition is true.
Therefore, for the next iteration 'i++' will increment it to 10.
Now again the test 'i < 10' is checked. At this point '10 < 10' test returns false and the for loop breaks and the value of i is 10.

How does one recursion in a forloop work? [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 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!