Presentation is loading. Please wait.

Presentation is loading. Please wait.

Principles of programming languages 3: Answers for exercises Isao Sasano Department of Information Science and Engineering.

Similar presentations


Presentation on theme: "Principles of programming languages 3: Answers for exercises Isao Sasano Department of Information Science and Engineering."— Presentation transcript:

1 Principles of programming languages 3: Answers for exercises Isao Sasano Department of Information Science and Engineering

2 Exercise (1) Illustrate the control flow graph of the following program fragment in C. if (y==1 || y==2) if (x > 0) x = x - 1; (2) Illustrate the control flow graph of the following program fragment in C. while (x > 0) { if (x%2==0 || x%3==0) s = s + x; x = x – 1; }

3 (1) An answer Entry y==1 Exit F T x = x-1 y==2 T F x>0 T F

4 (2) An answer Entry x%2== 0 Exit F T s = s+x x%3==0 T F x>0 T F x=x-1

5 Exercises Derive (prove) the following Hoare triples. (1){ a = 0 } a := a + 2 { a = 2 } (2){ a = 3 } if a = 3 then a := a + 1 else a := a – 1 { a = 4 } (3){ a = 1 } while (a < 5) do a := a + 1 { a = 5 }

6 (1) An answer { a + 2 = 2 } a := a + 2 { a = 2 } (assign) (conseq) { a = 0 } a := a + 2 { a = 2 } a=0  a+2=2 We abbreviate (assignment axiom) as (assign) and (consequence rule) as (conseq).

7 (2) An answer (if) { a = 3 } if a = 3 then a := a + 1 else a := a – 1 { a = 4 } { a = 3  a = 3} a := a + 1 { a = 4 }{ a = 3   a = 3} a := a - 1 { a = 4 } See the next page. See the next next page. We abbreviate (conditional rule) as (if).

8 (2) Cont. (assignment) { a = 3  a = 3} a := a + 1 { a = 4 } (a = 3  a = 3)  a+1 = 4 {a+1 = 4} a := a + 1 {a = 4} a=4  a=4 (consequence)

9 (2) Cont. (assignment) (a = 3   a = 3)  a-1 = 4 {a-1=4} a := a - 1 {a=4} a=4  a=4 (consequence) { a = 3   a = 3} a := a - 1 { a = 4 } (Note) The logical expression (a = 3   a = 3)  a-1 = 4 is true because a = 3   a = 3 is false for the cases where a=true or a=false. By the definition of , the whole expression is true since the left side of  is false.

10 (3) An answer { a = 1 } while (a < 5) do a := a + 1 { a = 5 } a=1  a  5 {a  5} while (a<5) do a := a + 1 {a  5   a<5} (a  5   a<5)  a=5 (consequence) (while) {a  5  a<5} a := a + 1 {a  5} (a  5  a<5)  a+1  5 {a+1  5} a := a+1 {a  5} a  5  a  5 (consequence) (assignment)


Download ppt "Principles of programming languages 3: Answers for exercises Isao Sasano Department of Information Science and Engineering."

Similar presentations


Ads by Google