dangling-else problem

(Dangling-else Problem) State the output for each of the following when x is 9 and y is 11 and when x is 11 and y is 9. The compiler ignores the indentation in a C++ program. The C++ compiler always associates an else with the previous if unless told to do otherwise by the placement of braces {}. On first glance, you may not be sure which if and else match, so this is referred to as the “dangling-else” problem. We eliminated the indentation from the following code to make the problem more challenging. [Hint: Apply indentation conventions you’ve learned.]

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 if ( x < 10 )
if ( y > 10 )
cout << "*****" << endl;
else
cout << "#####" << endl;
cout << "$$$$$" << endl;

b)
if ( x < 10 )
{
if ( y > 10 )
cout << "*****" << endl;
}
else
{
cout << "#####" << endl;
cout << "$$$$$" << endl;
}

Solution:

a) 
x = 9, y = 11

*****
$$$$$


x = 11, y = 9

$$$$$

b)
x = 9, y = 11

*****
x = 11, y = 99

#####
$$$$$
And what is the question?
repost it with proper indentation
my confusion is like in the first part if (9<10) the if part is empty for x portion so shouldn't print anything and (11>10) for the y portion so it should print the first line of else as c++ rule if no brackets are applied so the output should be "#####" but it is "*****" and "$$$$$" which is completely opposite of what i think.
a)
1
2
3
4
5
6
7
8
9
10
11
12
13
if ( x < 10 )
{
   if ( y > 10 )
   {
      cout << "*****" << endl;
   }
   else
   {
      cout << "#####" << endl;
   }
}

cout << "$$$$$" << endl;


b)
1
2
3
4
5
6
7
8
9
10
11
12
if ( x < 10 )
{
   if ( y > 10 )
   {
      cout << "*****" << endl;
   }
}
else
{
   cout << "#####" << endl;
   cout << "$$$$$" << endl;
}

Topic archived. No new replies allowed.