Consider the translation scheme shown below.
- num (num.val)
Here num is a token that represents an integer and num.val represents the corresponding integer value. For an input string ‘’, this translation scheme will print
View worked solution
Answer: B
To find the output printed by the translation scheme for the input string 9 + 5 + 2, we construct the parse tree and execute the semantic actions during a depth-first (left-to-right) traversal.
1. Parse Tree Construction
The input string is 9 + 5 + 2. The parse tree based on the given grammar is shown below:
S
/ \
T R
| / | \
9 + T {print('+')} R
| / | \
5 + T {print('+')} R
| |
2 ε
2. Traversal and Action Execution
We perform a left-to-right depth-first traversal of the parse tree, executing the semantic actions (enclosed in curly braces { }) as they are encountered:
- Traverse the leftmost child of , which is with .
Action:print(9)
Output so far:9 - Move to . Match the terminal symbol
+. - Traverse with .
Action:print(5)
Output so far:9 5 - Execute the action associated with .
Action:print('+')
Output so far:9 5 + - Traverse the nested . Match the terminal symbol
+. - Traverse with .
Action:print(2)
Output so far:9 5 + 2 - Execute the action associated with the nested .
Action:print('+')
Output so far:9 5 + 2 + - Traverse the innermost , which performs no action.
The final printed output is 9 5 + 2 +.
Free practice · Your answers on this page are not saved.
