# Unambiguous Grammar

A grammar can be unambiguous if the grammar does not contain ambiguity that means if it does not contain more than one leftmost derivation or more than one rightmost derivation or more than one parse tree for the given input string.

To convert ambiguous grammar to unambiguous grammar, we will apply the following rules:

1. If the left associative operators (+, -, *, /) are used in the production rule, then apply left recursion in the production rule. Left recursion means that the leftmost symbol on the right side is the same as the non-terminal on the left side. For example,

2. If the right associative operates(^) is used in the production rule then apply right recursion in the production rule. Right recursion means that the rightmost symbol on the left side is the same as the non-terminal on the right side. For example,

### Example 1:

Consider a grammar G is given as follows:

Determine whether the grammar G is ambiguous or not. If G is ambiguous, construct an unambiguous grammar equivalent to G.

**Solution:**

Let us derive the string “aab”

As there are two different parse tree for deriving the same string, the given grammar is ambiguous.

Unambiguous grammar will be:

### Example 2:

Show that the given grammar is ambiguous. Also, find an equivalent unambiguous grammar.

**Solution:**

The given grammar is ambiguous because we can derive two different parse tree for string aa.

The unambiguous grammar is:

### Example 3:

Show that the given grammar is ambiguous. Also, find an equivalent unambiguous grammar.

**Solution:**

Let us derive the string “id + id * id”

As there are two different parse tree for deriving the same string, the given grammar is ambiguous.

Unambiguous grammar will be:

### Example 4:

Check that the given grammar is ambiguous or not. Also, find an equivalent unambiguous grammar.

**Solution:**

The given grammar is ambiguous because the derivation of string aab can be represented by the following string:

Unambiguous grammar will be: