Correctness and Loop Invariants
Pedro Ribeiro
DCC/FCUP
2018/2019
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 1 / 23
Correctness and Loop Invariants Pedro Ribeiro DCC/FCUP 2018/2019 - - PowerPoint PPT Presentation
Correctness and Loop Invariants Pedro Ribeiro DCC/FCUP 2018/2019 Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 1 / 23 On Algorithms What are algorithms? A set of instructions to solve a problem . The problem is the
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 1 / 23
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 2 / 23
′
′
′
′
′
′
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 3 / 23
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 4 / 23
◮ Given an algorithm, it is not often obvious or trivial to know if it is
◮ By learning how to reason about correctness, we also gain insight into
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 5 / 23
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 6 / 23
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 7 / 23
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 8 / 23
◮ For the example sum loop, it could be: sum =
i−1
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 9 / 23
◮ For the example sum loop: sum=0 which is =
◮ For the example sum loop:
i−1
i
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 10 / 23
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 11 / 23
◮ For the example sum loop: we could simply use the value of i, which
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 12 / 23
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 13 / 23
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 14 / 23
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 15 / 23
◮ If both marbles chosen are the same, the number of blue marbles either
◮ If the marbles are different, the number of blue marbles stays the same
◮ If it was odd, it stays odd ◮ If it was even, it stays even Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 16 / 23
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 17 / 23
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 18 / 23
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 19 / 23
◮ Red responds by connecting (i − 1, j + 1) with (i, j + 1)
◮ Red responds by connecting (i + 1, j − 1) with (i + 1, j)
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 20 / 23
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 21 / 23
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 22 / 23
Pedro Ribeiro (DCC/FCUP) Correctness and Loop Invariants 2018/2019 23 / 23