Why am I getting the output CD?

Why am I getting the output CD when n = 10?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <string>
using namespace std; 

int main ()
{
int n;
n = 10;

if (n < 10 && n > 10)
	if (n > 5)
		cout << "A";

else
	cout << "B";
	cout << "C";
	
cout << "D";




return 0;
}



Shouldn't the output be BD? Since the program reads the first statement, not the second statement.
Hi,

Add some '{' in your code.
The else stands for the second if, not for the first one as your indentation suggest. If you don't put {, only on statement is taken into account.


The statement after the first if is the entire second if : (if (n>5) ... else ... ). The statement after the first if, in this conditions, is : cout << C;



Hope it helps.





Hello andygarc1a,

My question is about line 10. How can n be less than 10 and greater than 10 at the same time? And with n = 10 the lhs of the && is false so again the second if will never be reached.

Not sure which if statement the else belongs with, but since you say it prints CD that suggests that else belongs to the second if. With out any {} only cout << "B"; is connected with the else. Thus leaving the next two line to Print.

Hope that helps,

Andy
indentation does not change the meaning of your program, but it may help you realise what's happening
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <string>
using namespace std;

int main() {
	int n;
	n = 10;

	if(n < 10 && n > 10) //always false
		if(n > 5)
			cout << "A";
		else
			cout << "B";

	cout << "C"; //always execute
	cout << "D";

	return 0;
}



> Why am I getting the output CD when n = 10?
you always get CD, regardless of the value of `n'

> Shouldn't the output be BD? Since the program reads the first statement,
> not the second statement.
you lost me, I don't understand how you may think that BD is a valid output.
If it printed B, ¿why not C?
Topic archived. No new replies allowed.