In: Computer Science
1)Write a C++ program which clearly demonstrates how the dangling else ambiguity is resolved. Your program should print distinct results depending on if C++ uses inner-if or outer-if resolution. Turn in a listing of your program, the output, and a description of how your program demonstrates the semantic resolution of the ambiguity.
2) Give a context-free grammar describing the syntax of the following; Non-empty strings of 0’s and 1’s that represent binary numbers that have odd parity
1)
Dangling else is an ambiguity which is created when there are 2 if statements followed by single else. So the compiler cannot understand which if the else belongs to, so that is called dangling else.
Demo of program output with inner and outer if separately.
#include <iostream>
using namespace std;
int main() {
int a;
//input a number
cout<< "\nEnter a number";
cin>>a;
cout << "\nDemo of dangling else, outer if";
if(a>5)
{
cout<<"\na is greater than 5";
if(a>100)
cout<<"\na is greater than 100";
}
else
cout<<"\na is less than 100";
//example 2
cout << "\nDemo of dangling else, inner if";
if(a>5)
{ cout<<"\na is greater than 5";
if(a>100)
cout<<"\na is greater than 1000";
else
cout<<"\na is less than 1000";
}
}
To get rid of dangling else, put braces for the compiler to know which if is being referred for the else.
Sample output