Please explain: Extend the grammar of Figure 1 to include if statements and whil
ID: 3792058 • Letter: P
Question
Please explain:
Extend the grammar of Figure 1 to include if statements and while loops, along the lines suggested by figure 2. The grammar should support the six standard comparison operations in conditions, with arbitrary expressions as operands. It should also allow an arbitrary number of statements in the body of an if or while statement.
Figure 1:
1.program -> stmt_list $$
2. stmt_list -> stmt_list stmt
3. stmt_list -> stmt
4. stmt -> id:= expr
5. stmt -> read id
6. stmt -> write expr
7. expr -> term
8. expr -> expr add_op term
9. term-> factor
10. term-> term mult_op factor
11. factor -> (expr)
12. factor-> id
13. factor -> number
14. add_op -> +
15. add_op -> -
16. mult_op -> *
17. mult_op -> /
Figure 2:
abs:= n
if n < 0 then abs:= 0 - abs fi
sum:= 0
read count
while count > 0 do
read n
sum := sum + n
count := count -1
od
write sum
Explanation / Answer
<program> ::=<stmt,list>$$
<stmt_list> ::=<stmt><stmt_list> |
<program> ::=<stmt.list> $$
<stmt_list> :==<stmt><stmt_list> |
<stmt> ::=id :=<expr> | read id | write <expr>
<expr> ::=<term><term_tail>
<term_tail> ::=<add.op><term>|
<term> ::=id | number
<add.op> ::=+ | -
FIRST SETS:
<program> --> {$$,id,read,write}
<stmt_list>-->{,id,read,write}
<stmt>-->{id,read,write}
<expr>-->{id,number}
<term_tail>-->{,+,-}
<term>-->{id,number}
<add_op>-->{+,-}