(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++ com- piler 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.]

a) ```
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;
}
```


```
// Dangling-else problem.
#include
using namespace std;

int main()
{
// part A, x=9 and y=11
int x = 9;
int y = 11;
cout << "Output for part A, x=9 and y=11:" << endl;
if ( x < 10 )
if ( y > 10 )
cout << "*****" << endl;
else
cout << "#####" << endl;

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

// part A, x=11 and y=9
x = 11;
y = 9;
cout << endl << "Output for part A, x=11 and y=9:" << endl;

if ( x < 10 )
if ( y > 10 )
cout << "*****" << endl;
else
cout << "#####" << endl;

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

// part B, x=9 and y=11
x = 9;
y = 11;
cout << endl << "Output for part B, x=9 and y=11:" << endl;

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

// part B, x=11 and y=9
x = 11;
y = 9;
cout << endl << "Output for part B, x=11 and y=9:" << endl;

if ( x < 10 )
{
if ( y > 10 )
cout << "*****" << endl;
} // end outer if
else
{
cout << "#####" << endl;
cout << "$$$$$" << endl;
} // end else
} // end main
```

Computer Science & Information Technology

You might also like to view...

Which of the following statements are true?

a. A dynamic array can have a base type which is a class or a struct. b. A class or a struct may have a member which is a dynamic array. c. A and B d. Neither

Computer Science & Information Technology

The role of the ____________________ in an evaluation of a vulnerability is to prepare all of the information necessary to help the appropriate manager make the right decision and then ensure that information gets to the responsible individual.

Fill in the blank(s) with the appropriate word(s).

Computer Science & Information Technology

When the Slide Master is displayed in Normal view, the associated layouts are displayed ________

A) as thumbnails across the top of the screen B) as thumbnails on the left of the screen C) as thumbnails on the view tab D) when the New Slide button is clicked, on the Home tab , in the Slides group,

Computer Science & Information Technology

Nested tables load at the same rate that single tables load

Indicate whether the statement is true or false

Computer Science & Information Technology