Can someone explain the reason for this output?

I don't understand how this code is outputting 11. I keep thinking it should be 7. Here is the code

[code]
#include<iostream>
using namespace std;


int main() {
int n = 3;
if (n >= 2) // I just set n as equal to three, so this should be true?
n + 4;
if (n = 5)
n += 6;
else
n = 12;
cout << n << endl;



system("pause");
return 0;

}
11 is indeed the expected output from the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
using namespace std;

int main() {
int n = 3;
if (n >= 2) // this is true
n + 4; // this statement does not affect the value of n, as its not assigned back to n
if (n = 5) // this is an assignment statement, thus n is now 5, which is 'true'
n += 6; // 6 + 5 is assigned back to n; n is now 11
else
n = 12;
cout << n << endl; // prints 11

system("pause");
return 0;
} 


I believe what you intended was this, but output is still not 7:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
using namespace std;

int main() {
     int n = 3;
     if (n >= 2) // true
          n = n+4; // 4 is added to n, the result of which is assigned to n; n = 7
     if (n == 5)   // notice the double equals sign. This is false
          n += 6;
     else
          n = 12;   // n is now 12
     cout << n << endl;  // prints 12

system("pause");
return 0;

} 
Last edited on
Thanks. But for line 7 I am not understanding why n + 4 is not affecting its value. What would need to be done to change this?
I've edited my above post to show the 'correct' version of your code. Take a look, and I'll think you'll see why simply writing n+4 does not affect the value of n.
Thank you. And this was code on a mid term not written by me but by my teacher. It was a trick question intended to confuse the test taker I believe.
One last question. How is

if (n = 5)

assigning 5 as the new value to n? Isn't it just checking IF n is equivalent to 5, and not setting n as being equal to 5?
The assignment operator works everywhere, even if they are in the if-condition like if (n = 5).

However, if we intend to compare only (if the two values are equal), we use == not =.
Topic archived. No new replies allowed.