Основы Perfect Developer

Size: px
Start display at page:

Download "Основы Perfect Developer"

Transcription

1 Основы Perfect Developer Краткий курс

2 Содержание Session 1: начало работы Configuring Perfect Developer and creating a project Expressions, types, constants, functions, properties Classes, data, invariants, functions, schemas, constructors Session 2: погружение Interfacing to a Java front-end Sequences and recursion Session 3: корректировка методов и данных Statement lists, statement types, loops, nested refinement. Internal data, retrieve functions Session 4: наследование Derived and deferred classes Defining and redefining inherited methods

3 Конфигурация Конфигурация Perfect Developer заключается в выборе редактора Загрузите Project Manager Выберите Options Editor Найдите исполняемый файл редактора Выберите тип редактора Конфигурация редактора для автоматического распознавания файлов Perfect Developer См. инструкции в папке Editor Customizations где установлен Perfect Developer

4 Создание проекта Выберите New project из меню или иконку Выберите папку для записи файлов, задайте имя проекта и щелкните Save и OK Щелчком на иконку Create file создайте файл Examples Добавьте текст: property (a, b, c: int) pre a < b, b < c assert a < c; Сохраните файл Щелкните на иконку Verify для запуска проверки

5 Некоторые предопределенные классы bool char int real set of X bag of X seq of X map of (X -> Y) Set, bag, sequence и map типы являются конечными коллекциями. См. Language Reference Manual

6 Выражения Все обычные арифметические операции a < b < c означает точно то, что вы ожидали a / b (integer) и a % b удовлетворяют precondition b > 0 a / b (integer) округляется в сторону - a.. b обозначает последовательность {a, a+1, a+2 b} #c обозначает cardinality или длину коллекции c a # c обозначает число появлений a в c

7 Booleans, Conditionals etc. Boolean операции: & ==> <== <==> Conditional выражения: ( [a > 0]: a, [b > 0]: b, []: 0) Let-декларация: ( let t ^= a - b; t * t ) Embedded assertion: ( assert a > 0, b > 0; a / b ) Законченный пример: ( let t ^= a - b; assert t > 0; [t > 10]: 1, []: 10 / t )

8 Вызовы конструктора Вызов конструктора возвращает объект заданного типа Без параметров: seq of int{} MyClass{} С параметрами: seq of int{a, b, c} MyClass{42} Некоторые классы предполагают наличие предусловий (preconditions) int{s} это ok при s = "123" но не для s = "lemon"! [precondition is: ~s.empty & (forall c::s :- c.isdigit)]

9 Квантификаторы и etc. Если c имеет тип set of T, bag of T или seq of T, и p(x) это Boolean выражение содержащее x: Expression forall x::c :- p(x) forall x: T :- p(x) exists x::c :- p(x) exists x: T :- p(x) that x::c :- p(x) T any x::c :- p(x) those x::c :- p(x) Return type bool bool set / seq / bag of T for x::c yield v(x) set / seq / bag of type of v for those x::c :- p(x) yield v(x)

10 Декларация констант и функций Декларация констант: const four: int ^= 2 + 2; const smallprimes: seq of int ^= those x:: :- ~(exists y::2..<x :- x % y = 0); const two ^= 2; Type can be omitted in simple cases Декларация функций: function half(x: int): int pre x > 0 Precondition (if needed) ^= x / 2;

11 Декларация свойств (properties) Используйте декларацию свойств для формулировки теорем: property assert half(four) = two; Неявная универсальная квантификация всех параметров property (x: int) pre x > 0, Предпологаемые данные x % 2 = 0 assert half(x) < x, (let h ^= half(x); h + h = x); Следствия, трующие доказательства

12 Exercise 1: см. лаб 10 All the integers from 0 to 100 inclusive, in ascending order. Verify that your solution contains 42 but does not contain 101. The integer j (which is known to be greater than 0) divides the integer i exactly. The squares of all the prime numbers from 2 to 100 inclusive. The highest integer in a set S of integers that is known to be non-empty

13 Декларация перечислений class Currency ^= enum unspecified, euro, pound, USdollar end; const localcurrency ^= localcurrency.tostring

14 Декларация классов class Money ^= abstract interna l confined interface end; variables, invariants, methods, constructors [never mind for now] [never mind for now] access redeclarations, methods, constructors, properties Декларируемые здесь переменные, образуют абстрактную модель данных класса Инварианты здесь являются ограничениями на данные Эти методы и конструкторы для использования в confined и/или interface методах и конструкторах Access redeclarations позволяют получить доступ к данным и методам извне класса Эти методы и конструкторы могут вызываться извне класса Обязательной является только секция interface

15 Декларирование данных и Переменная amt типа int abstract var amt: int, ccy: Currency; инвариантов Пременная ccy типа Currency invariant amt = 0 ccy ~= unspecified@currency; Ограничения на amt и ccy

16 Функции и операторы Name No () if no parameters Return type function worthhaving: bool ^= amt > 0; function plus(m: Money): Money pre m.ccy = ccy ^= Currency{amt + m.amt, ccy} assert result.ccy = ccy; operator (n: int) * : Money ^= Currency{amt * n, ccy}; Result expression Optional precondition Optional postassertion Operator declarations are the same as function declarations apart from the header Use nonmember prefix for methods & properties with no self object

17 Декларация Schema No self object No () if no parameters Parameter is modified nonmember schema swap(a!, b!: Money) pre a.ccy = b.ccy post change a,b satisfy a =b, b =a assert a.plus(b) = b.plus(a ); Postcondition includes frame This one modifies instance variables schema!inflate(howmuch: int) pre 0 < howmuch < 200 post amt! = (amt * howmuch)/100; Сокращение для: change amt satisfy amt = (amt * howmuch)/100

18 Декларация конструкторов Note parameter list in {} build{a: int, c: Currency} pre a > 0 post amt! = a, ccy! = c; build{!amt: int} post ccy! = euro@currency; build{} ^= Money {0, unspecified@currency}; This constructor is defined in terms of another one Postcondition must initialise all instance variables* Initialise instance variable directly from the parameter Сокращение для: change amt satisfy amt = a We do use {} if no parameters *except for variables whose when-guards are false

19 Использование access redeclarations abstract переменные могут быть redeclared в interface: function v1; selector v2; разрешает чтение v1 разрешает чтение и запись v2 Разрешение записи в переменную следует избегать Except for convenience classes, e.g. class pair Разрешение чтения переменной сложного типа следует избегать Поскольку это приводит к трудностям ее дальнейшего преобразования Константы могут быть redeclared как nonmember functions Use access redeclarations sparingly!

20 Exercise 2: Specification (followed by coffee break) (см. лаб.10) You have been provided with a Perfect specification of class Money Try to verify it (there will be 3 verification errors) Fix the specification to remove the verification errors Verify that multiplying a Money object by 2 is equivalent to adding it to itself Declare a + operator that works like the plus function except that if the amount of either operand is zero, we don t care what the corresponding currency is

21 Использование Perfect с графическим UI Java front-end class MyApp implements ActionListener MyApp() Button 1 Button 2 constructor calls when pressed calls when pressed calls Perfect back-end class Application ^= interface build{} function f ( ) schema! s ( ) Избегайте предусловий для методов, вызываемых в Java!

22 Использование Perfect с графическим UI Декларируйте Perfect класс Application Декларируйте интерфейс функции/схемы для вызова в Java Декларируйте интерфейс конструктор для вызова в Java В графической среде: Import Application.java Instantiate a single Application object during initialisation Call member functions/schemas when buttons are pressed Convert parameter types as necessary Имеется пример в файле TutorialExample.java

23 Exercise 3: Build the sample program Open project TutorialExample.pdp Verify the project Click the Build tool icon Check for error messages Locate and run output\app.jar Try making your own changes to Application.pd e.g. print some of the expressions you wrote earlier [tips follow ]

24 Tips To use constants and functions from Examples.pd: Add file Examples.pd to the project Add to Application.pd: import "Examples.pd"; You can convert any expression to a string By calling.tostring on it To make your application robust: Verify your version of Application.pd Don t add any preconditions to the methods called from Java!

25 Sequences and Strings The standard collection types are: set of X, bag of X, seq of X (where X is any type you like) string seq of char Members of class seq of X include: head tail front back append(x) prepend(x) ++(s) # (x)in take(n) drop(n) slice(offset, length) isndec isninc permndec permninc isordered(cp)!sort(cp) findfirst(x) findlast(x) Useful global functions include: flatten(ss: seq of seq of X) interleave(ss, s) See the Library Reference for details

26 Recursive and templated functions Indicates that T can be any type function reverse(s: seq of class T): seq of T decrease #s ^= ( [#s <= 1]: s, []: reverse(s.front).prepend(s.last) ); Recursion variant Recursive call

27 Рекрсивные варианты Общая форма: decrease e1, e2, e3 e1, e2 один из типов int, bool, char или перечисление Вариант должен убывать на каждом шаге рекурсии Либо e1 должен убывать либо e1 остается прежним, но e2 убывает либо e1 и e2 остаются прежними, но e3 убывает Целочисленные компоненты не могут становиться отрицательными

28 Exercise 4: Sequences Specify the following functions: numleadingspaces(s: string): nat returns the index of the first character in s that is not a space, or the length of s if it is all spaces removeleadingspaces(s: string): string returns s with any leading spaces removed firstword(s: string): string returns the leading characters of s up to but not including the first space character in s splitintowords(s: string): seq of string splits the sentence s into individual words (hint: use recursion!)

29 Lunch break!

30 Refinement There are three types of refinement in Perfect: Refining result expressions to statement lists Refining postconditions to statement lists Refining abstract data to implementation data When you refine the abstract data of a class, you normally need to refine the method specifications as well So we will start with refining specifications

31 Refining specifications Specification refinement serves these purposes: To implement a specification where Perfect Developer fails to To implement a specification more efficiently To take account of data refinement in affected methods You can refine these sorts of specification: Expressions that follow the ^= symbol Postconditions To refine a specification, append to it: via statement-list end

32 Some simple refinements function square(x: int): int ^= x^2 via value x*x end; schema swap(a!, b!: class X) post a!= b, b!= a via let temp ^= a; a! = b; b! = temp end; value statement returns a value from the via..end Semicolon separates and sequences the statements A postcondition can be used as a statement

33 Nested Refinements You can refine not just method specifications but also: Postcondition statements Let-declarations in statement lists function fourth(x: int): int ^= x^4 via let x2 ^= x^2 via value x*x end; value x2*x2 end; value yielded by the inner via..end value yielded by the outer via..end

34 Types of Statement Let-declaration Assertion Variable declaration Postcondition pass statement Exactly the same as in bracketed expressions Same as in postconditions Omit the post keyword! Does nothing If-statement value and done statements Loop statement Block statement

35 If-statement if [c in `a`..`z`]: isaletter! = true; valid! = true; Guard Statement list [c in `0`..`9`]: isaletter! = false; valid! = true; []: valid! = false fi Optional else part [] fi means the same as []: pass fi

36 value statement function max(a,b,c: class X): X satisfy result >= a & result >= b & result >= c & (result=a result=b result=c) via if [a > b]: value max(a, c); []: value max(b, c) fi end; Every path in an expression refinement must end at a value statement

37 done statement schema max(a!,b,c: class X) post change a satisfy a >= a & a >= b & a >= c & (a = a a = b a = c) via if [a > b]: a!= max(a, c); done; [] fi; a!= max(b, c) end; A postcondition refinement may contain one or more done statements Implicit done statement here

38 Loop statement // Calculate a^b Start of loop statement var rslt: int! = 1; loop var j: nat! = 0; change rslt keep rslt = a^j until j = b decrease b - j ; rslt! * b, j! + 1 end; End of loop statement Loop variable declaration List of what the loop can change Loop invariant list Termination condition Loop variant Loop body

39 Loop statement loop local variable declarations (optional) change list (optional) invariant termination condition (optional) variant body statements end If no change list is given, only the local variables can be changed If no termination condition is given, the loop terminates when the variant can decrease no more

40 Designing loop invariants Variables in loop invariants may be primed or unprimed Primed = current values at the start of an iteration Unprimed = value before the loop started The invariant is the only source of information about current values of changing variables The state when the loop completes is given by: invariant & until-part The invariant should comprise: A generalisation of the state that the loop is meant to achieve; Additional constraints needed to make the invariant, until-part, variant and body well-formed

41 Example of invariant design Given s: seq of int we wish to achieve total = + over s Generalise this to tot = + over s.take(j ) for some loop counter j When j = #s then the generalisation becomes the required state because s.take(#s) = s This generalisation forms part of the invariant But s.take(j ) has precondition 0 <= j <= #s So we must either add this precondition as an earlier invariant Or as a type constraint in the declaration of j

42 Loop example (incorrect) var totl: int! = 0; loop var j: int! = 0; change totl keep totl = + over s.take(j ) until j = #s decrease #s - j ; totl! + s[j], j! + 1 end; Problem! These expressions are not universally wellformed

43 Loop example (version 1) var totl: int! = 0; loop var j: int! = 0; change totl keep 0 <= j <= #s, totl = + over s.take(j ) until j = #s decrease #s - j ; totl! + s[j], j! + 1 end; Added this extra invariant at the start This is now well-formed This is also well-formed (provided the untilcondition is false)

44 Loop example (version 2) var totl: int! = 0; loop var j: (int in 0..#s)! = 0; change totl keep totl = over s.take(j ) until j = #s decrease #s - j ; totl! + s[j], j! + 1 end; Added this type constraint This is now well-formed This is also well-formed (provided the untilcondition is false)

45 Refining recursion to loops function rev(s: seq of int): seq of int decrease #s ^= ([s.empty]: s, []: rev(s.tail).append(s.head)) via var rslt: seq of int! = seq of int{}; loop var j: (nat in 0..#s)! = 0; change rslt keep rslt = rev(s.take(j )) until j = #s decrease #s - j ; rslt! = rslt.prepend(s[j]), j! + 1 end; value rslt end;

46 Refining recursion to loops Is the preceding example correct? Probably! But Perfect Developer cannot verify it! The definition builds the result from front to back Using append The implementation builds the result from back to front Using prepend They are equivalent only because of associativity (a ++ b) ++ c = a ++ (b ++ c) reverse(x.tail).append(x.head) = reverse(x.front).prepend(x.last) To prove this we need an inductive prover!

47 Refining recursion to loops function rev(s: seq of int): seq of int decrease #s ^= ([s.empty]: s, []: rev(s.tail).append(s.head)) via var rslt: seq of int! = seq of int{}; loop var j: (nat in 0..#s)! = #s; change rslt keep rslt = rev(s.drop(j )) until j = 0 decrease j ; j! - 1, rslt! = rslt.append(s[j ]) end; value rslt end;

48 Loops: a summary Getting the invariant correct is critical It must describe the relationships between all variables changed by the loop (including the local loop variables) Its main part is a generalisation of the desired state after the loop When the until condition is satisfied, the generalisation must reduce to the desired state You may also need to include constraints on variables To make expressions in the loop well-formed If refining a recursive definition, make sure that the loop builds the result in the same order as the definition

49 Exercise 5: Method refinement Refine the following specifications function min2(x, y: int): int satisfy result <= x, result <= y, result = x result = y; function findfirst(s: seq of int, x: int): int satisfy 0 <= result <= #s, result = #s s[result] = x, forall j::0..<result :- s[j] ~= x; Function numleadingspaces from exercise 4 Function splitintowords from exercise 4

50 Data refinement When designing a class, we should always use the simplest possible abstract data model Avoid redundancy! Don t be concerned with efficiency at this stage! The methods are specified in terms of this model This keeps the specifications simple! The data should not be directly accessible from outside So we can change the implementation of the data without changing the class interface [Except for very simple classes like pair]

51 Data Refinement (cont d) Perfect supports two sorts of data refinement: Replacing abstract variables by internal variables Use a retrieve function to indicate that a variable is replaced Examples: see Dictionary.pd and Queue.pd in C:\Program Files\Escher Technologies \Perfect Developer\Examples\Refinement Supplementing abstract variables by internal variables The new internal data adds no new information Declare internal invariants to specify the relationship Example: add an index to a data structure The internal data may be changed even within a function

52 Data Refinement Example We have a class that maintains a list of numbers Its constructor creates an empty list We provide a method to append a number to the list We provide a method to return the sum of all the numbers in the list

53 List of integers class function sum(s: seq of int): int decrease #s ^= ([s.empty]: 0, []: sum(s.front) + s.last); class ListOfNumbers ^= abstract var list: seq of int; interface function list; build{} post list! = seq of int{}; schema!addnumber(n: int) post list! = list.append(n); function getsum: int ^= sum(list); end;

54 Data Refinement Example Suppose that method sum is called frequently Save time by caching the sum of the list

55 Refined list of integers class class ListOfNumbers ^= abstract var list: seq of int; internal var totl: int; invariant totl = sum(list); interface function list; build{} post list! = seq of int{} via list! = seq of int{}, totl! = 0; end;

56 Refined list of integers class schema!addnumber(n: int) post list! = list.append(n) via list! = list.append(n), totl! + n end; function getsum: int ^= sum(list) via value totl end; end;

57 Exercise 6: Data Refinement Write a recursive function longest which, given a list of strings, returns the longest string in the list (or the empty string if the list is empty, or the latest one of several equal-length longest strings) Write a class that maintains a list of strings. You should provide: A constructor, which sets the list to an empty list A member schema to append a new string to the list A member function to return the longest string in the list Refine the class to make the implementation of the longest member function more efficient

58 Inheritance When declaring a class you can inherit another class Declare class UniversityMember Then class Student ^= inherits UniversityMember And class StaffMember ^= inherits UniversityMember And class Professor ^= inherits StaffMember A derived class inherits the variables of its parent But they are not [normally] visible in the derived class A derived class inherits the methods of its parent But only confined and interface members of the parent are visible

59 The confined section The confined section behaves like the interface section You can put the same types of declaration in it i.e. Methods, operators, constructors, access redeclarations Not constants, variables or invariants But confined declarations are only visible within the current class and its descendents Not to the public at large! cf. protected in Java and C++

60 Redefining methods Functions, selectors, schemas and operators that are inherited from a parent class may be redefined This must be indicated using the redefine keyword The parameter and result types in the redefinition must be identical to those in the overridden function

61 Example of overriding class UniversityMember ^= abstract var firstnames: seq of string, lastname: string; interface function getsalary: Money ^= 0; end; class StaffMember ^= inherits UniversityMember abstract var salary: Money; interface redefine function getsalary: Money ^= salary; end;

62 from types and Dynamic Binding You may declare a variable (or parameter, or result) to be of type from C where C is a class e.g. var member: from UniversityMember The variable may be assigned a value of type C or any of its descendants So member may be assigned a value of type Student, Professor from C actually means the union of all non-deferred classes in the set comprising C and its direct and indirect descendents When calling a member function on such a variable, the [re]definition appropriate to the actual type is called e.g. the relevant version of getsalary

63 Deferred methods You can also declare a method in a class deferred The method is left undefined in that class This avoids the risk of classes inheriting what may be an unsuitable definition The class itself must also be flagged deferred and may not be instantiated Descendent classes may define the method using the define keyword Any descendent class that does not define it is also a deferred class

64 Example of deferred method deferred class UniversityMember ^= abstract var firstnames: seq of string, lastname: string; interface deferred function getsalary: Money; end; class StaffMember ^= inherits UniversityMember abstract var salary: Money; interface define function getsalary: Money ^= salary; end;

65 Final classes and methods A method can be declared final to prevent it from being redefined in a descendent class final function getsalary: Money ^= You can also declare a method final when defining or redefining it define final function getsalary: Money ^= redefine final function getsalary: Money ^= You can declare a class final to mean that no other class may inherit it final class Professor ^=

66 Some consequences If D is a deferred class: var x: D is illegal But you can use var x: from D If F is a final class: var x: from F is illegal But you can use: var x: F If C is a non-final class, f is a final method and g is a nonfinal method, and given var x: from C : In x.f the prover can assume the full postcondition of f In x.g the prover can assume only the postassertion of g

67 Preconditions and inheritance When a method is inherited, by default the precondition is inherited too You may override the inherited precondition by giving a new one in the method definition or redefinition The new precondition must be satisfied whenever the old one would have been satisfied i.e. you may only weaken the precondition To get round this, have the precondition call a method that you can redefine

68 Inherited precondition example Suppose we declare a deferred method ispaid in class UniversityMember define this to return false for class Student, true for class StaffMember Add precondition pre ispaid to method getsalary

69 Inherited precondition example deferred class UniversityMember ^= abstract var firstnames: seq of string, lastname: string; interface deferred function ispaid: bool; deferred function getsalary: Money pre ispaid; end; class StaffMember ^= inherits UniversityMember abstract var salary: int; interface define function ispaid: bool ^= true; define function getsalary: Money ^= salary;

70 Inherited precondition example That worked OK for class StaffMember, but what about class Student? Method getsalary can never be called on class Student because its precondition is always false How should we declare it?

71 Absurd method example deferred class UniversityMember ^= abstract var firstnames: seq of string, lastname: string; interface deferred function ispaid: bool; deferred function getsalary: Money pre ispaid; end; class Student ^= inherits UniversityMember interface define function ispaid: bool ^= false; absurd function getsalary;

72 Absurd methods Declaring a method absurd means that its precondition is always false Repeat the parameter list of the method but not its return type An absurd method declaration has these consequences: The method is defined or redefined such that calling it will raise an exception A verification condition is generated (i.e. that the precondition is always false) It avoids the Given false, so proof is trivial warnings you will otherwise see

73 Inheritance and postassertions When defining or redefining an inherited method, by default the postassertion is inherited You may override the postassertion by giving a new one The old postassertion must be satisfied whenever the new one is i.e. you may only strengthen the postassertion You can also use: assert, q This means assert the inherited postassertion and then q

74 Inheritance tips When using inheritance, declare methods final where possible This is not necessary in leaf classes which are declared final For non-final methods of non-final classes, postassertions are very important Because the prover needs them when the methods are called on from types Does not apply to defining methods like ispaid Only use from types where you really need to allow different types at run-time

75 Inheritance exercises Design a UniversityMember or Employee class hierarchy that reflects the properties and privileges of members of your organisation Specify a family of shopping scanners, as outlined at the end of the Shopping Scanner worked example at:

76 What we didn t cover Lots! after expressions over expressions Guarded variable declarations Selectors Members of classes set and bag Declaring templated classes Other library classes, e.g. map of (X -> Y) How to solve verification problems Serialization Declaring axioms

77 Further Reading Perfect Developer 3.0 Language Reference Manual Start -> Programs -> Perfect Developer -> Documentation Or click on the book tool in the Project Manager Also available at Online tutorial via Support -> Self-help section of the web site Teaching materials via Support -> Self-help -> Teaching materials

78 Thank you for participating!

Fundamentals of Perfect Developer

Fundamentals of Perfect Developer Fundamentals of Perfect Developer A one-day hands-on tutorial Outline Session 1: Getting Started Configuring Perfect Developer and creating a project Expressions, types, constants, functions, properties

More information

The Shopping Scanner: A Worked Example using Perfect Developer

The Shopping Scanner: A Worked Example using Perfect Developer The Shopping Scanner: A Worked Example using Perfect Developer Classification Public Author D. Crocker, Escher Technologies Ltd. Issue 1 Date 1 March 2004 1 Introduction This worked example is based on

More information

Assertions & Verification & Example Loop Invariants Example Exam Questions

Assertions & Verification & Example Loop Invariants Example Exam Questions 2014 November 27 1. Assertions & Verification & Example Loop Invariants Example Exam Questions 2. A B C Give a general template for refining an operation into a sequence and state what questions a designer

More information

Assertions & Verification Example Exam Questions

Assertions & Verification Example Exam Questions 2009 November 23 Assertions & Verification Example Exam Questions 1. 2. A B C Give a general template for refining an operation into a sequence and state what questions a designer must answer to verify

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p.

Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. Introduction to Computers and C++ Programming p. 1 Computer Systems p. 2 Hardware p. 2 Software p. 7 High-Level Languages p. 8 Compilers p. 9 Self-Test Exercises p. 11 History Note p. 12 Programming and

More information

Absolute C++ Walter Savitch

Absolute C++ Walter Savitch Absolute C++ sixth edition Walter Savitch Global edition This page intentionally left blank Absolute C++, Global Edition Cover Title Page Copyright Page Preface Acknowledgments Brief Contents Contents

More information

Problem Solving with C++

Problem Solving with C++ GLOBAL EDITION Problem Solving with C++ NINTH EDITION Walter Savitch Kendrick Mock Ninth Edition PROBLEM SOLVING with C++ Problem Solving with C++, Global Edition Cover Title Copyright Contents Chapter

More information

SOFTWARE ENGINEERING DESIGN I

SOFTWARE ENGINEERING DESIGN I 2 SOFTWARE ENGINEERING DESIGN I 3. Schemas and Theories The aim of this course is to learn how to write formal specifications of computer systems, using classical logic. The key descriptional technique

More information

ОБЪЕКТНО- ОРИЕНТИРОВАННОЕ ПРОГРАММИРОВАНИЕ. Лекция 1 / г.

ОБЪЕКТНО- ОРИЕНТИРОВАННОЕ ПРОГРАММИРОВАНИЕ. Лекция 1 / г. ОБЪЕКТНО- ОРИЕНТИРОВАННОЕ ПРОГРАММИРОВАНИЕ Лекция 1 / 04 04.03.2019 г. VIRTUAL DESTRUCTOR class Shape{ int x, y; Shape(int x, int y); ~Shape(){ printf("dtor shape!\n"); class Circle: public Shape{ int

More information

Outline. Introduction. 2 Proof of Correctness. 3 Final Notes. Precondition P 1 : Inputs include

Outline. Introduction. 2 Proof of Correctness. 3 Final Notes. Precondition P 1 : Inputs include Outline Computer Science 331 Correctness of Algorithms Mike Jacobson Department of Computer Science University of Calgary Lectures #2-4 1 What is a? Applications 2 Recursive Algorithms 3 Final Notes Additional

More information

Hardware versus software

Hardware versus software Logic 1 Hardware versus software 2 In hardware such as chip design or architecture, designs are usually proven to be correct using proof tools In software, a program is very rarely proved correct Why?

More information

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004 Type Hierarchy Comp-303 : Programming Techniques Lecture 9 Alexandre Denault Computer Science McGill University Winter 2004 February 16, 2004 Lecture 9 Comp 303 : Programming Techniques Page 1 Last lecture...

More information

Lists. Michael P. Fourman. February 2, 2010

Lists. Michael P. Fourman. February 2, 2010 Lists Michael P. Fourman February 2, 2010 1 Introduction The list is a fundamental datatype in most functional languages. ML is no exception; list is a built-in ML type constructor. However, to introduce

More information

Testing, Debugging, and Verification

Testing, Debugging, and Verification Testing, Debugging, and Verification Formal Specification, Part II Srinivas Pinisetty 23 November 2017 Introduction Today: Introduction to Dafny: An imperative language with integrated support for formal

More information

Formal Methods. CITS5501 Software Testing and Quality Assurance

Formal Methods. CITS5501 Software Testing and Quality Assurance Formal Methods CITS5501 Software Testing and Quality Assurance Pressman, R. Software Engineering: A Practitioner s Approach. Chapter 28. McGraw-Hill, 2005 The Science of Programming, David Gries, 1981

More information

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions 1 CSCE 314: Programming Languages Dr. Flemming Andersen Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions

More information

Induction and Semantics in Dafny

Induction and Semantics in Dafny 15-414 Lecture 11 1 Instructor: Matt Fredrikson Induction and Semantics in Dafny TA: Ryan Wagner Encoding the syntax of Imp Recall the abstract syntax of Imp: a AExp ::= n Z x Var a 1 + a 2 b BExp ::=

More information

Building Java Programs

Building Java Programs Building Java Programs A Back to Basics Approach Stuart Reges I Marty Stepp University ofwashington Preface 3 Chapter 1 Introduction to Java Programming 25 1.1 Basic Computing Concepts 26 Why Programming?

More information

Repetition Structures

Repetition Structures Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements

More information

Software Development. Modular Design and Algorithm Analysis

Software Development. Modular Design and Algorithm Analysis Software Development Modular Design and Algorithm Analysis Precondition and Postcondition To create a good algorithm, a programmer must be able to analyse a precondition (starting state) and a postcondition

More information

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution. Repetition Structures Introduction to Repetition Structures Chapter 5 Spring 2016, CSUS Chapter 5.1 Introduction to Repetition Structures The Problems with Duplicate Code A repetition structure causes

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

How invariants help writing loops Author: Sander Kooijmans Document version: 1.0

How invariants help writing loops Author: Sander Kooijmans Document version: 1.0 How invariants help writing loops Author: Sander Kooijmans Document version: 1.0 Why this document? Did you ever feel frustrated because of a nasty bug in your code? Did you spend hours looking at the

More information

Control Structures: The IF statement!

Control Structures: The IF statement! Control Structures: The IF statement! 1E3! Topic 5! 5 IF 1 Objectives! n To learn when and how to use an IF statement.! n To be able to form Boolean (logical) expressions using relational operators! n

More information

SML A F unctional Functional Language Language Lecture 19

SML A F unctional Functional Language Language Lecture 19 SML A Functional Language Lecture 19 Introduction to SML SML is a functional programming language and acronym for Standard d Meta Language. SML has basic data objects as expressions, functions and list

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides 1B1b Inheritance Agenda Introduction to inheritance. How Java supports inheritance. Inheritance is a key feature of object-oriented oriented programming. 1 2 Inheritance Models the kind-of or specialisation-of

More information

RSL Reference Manual

RSL Reference Manual RSL Reference Manual Part No.: Date: April 6, 1990 Original Authors: Klaus Havelund, Anne Haxthausen Copyright c 1990 Computer Resources International A/S This document is issued on a restricted basis

More information

Super-Classes and sub-classes

Super-Classes and sub-classes Super-Classes and sub-classes Subclasses. Overriding Methods Subclass Constructors Inheritance Hierarchies Polymorphism Casting 1 Subclasses: Often you want to write a class that is a special case of an

More information

Shell CSCE 314 TAMU. Haskell Functions

Shell CSCE 314 TAMU. Haskell Functions 1 CSCE 314: Programming Languages Dr. Dylan Shell Haskell Functions 2 Outline Defining Functions List Comprehensions Recursion 3 Conditional Expressions As in most programming languages, functions can

More information

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

Functional programming with Common Lisp

Functional programming with Common Lisp Functional programming with Common Lisp Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 81 Expressions and functions

More information

Flow of Control. 2.1 The if Statement

Flow of Control. 2.1 The if Statement Flow of Control 2 In almost any computer program written for a scientific computing application, we need to allow the computer to execute a collection of statements if and only if some criterion is met.

More information

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

Chapter 7 Control I Expressions and Statements

Chapter 7 Control I Expressions and Statements Chapter 7 Control I Expressions and Statements Expressions Conditional Statements and Guards Loops and Variation on WHILE The GOTO Controversy Exception Handling Values and Effects Important Concepts in

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

CSE 142 Wi03 Midterm 2 Sample Solution All Versions Page 1 of 6

CSE 142 Wi03 Midterm 2 Sample Solution All Versions Page 1 of 6 CSE 142 Wi03 Midterm 2 Sample Solution All Versions Page 1 of 6 Question 1. (5 points) One of your colleagues is having a terrible time with the following code, which doesn t work properly. /** A simple

More information

Violations of the contract are exceptions, and are usually handled by special language constructs. Design by contract

Violations of the contract are exceptions, and are usually handled by special language constructs. Design by contract Specification and validation [L&G Ch. 9] Design patterns are a useful way to describe program structure. They provide a guide as to how a program fits together. Another dimension is the responsibilities

More information

CSC Advanced Object Oriented Programming, Spring Specification

CSC Advanced Object Oriented Programming, Spring Specification CSC 520 - Advanced Object Oriented Programming, Spring 2018 Specification Specification A specification is an unambiguous description of the way the components of the software system should be used and

More information

Final Exam CS 251, Intermediate Programming December 10, 2014

Final Exam CS 251, Intermediate Programming December 10, 2014 Final Exam CS 251, Intermediate Programming December 10, 2014 Name: NetID: Answer all questions in the space provided. Write clearly and legibly, you will not get credit for illegible or incomprehensible

More information

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Lecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning

Lecture 1 Contracts : Principles of Imperative Computation (Fall 2018) Frank Pfenning Lecture 1 Contracts 15-122: Principles of Imperative Computation (Fall 2018) Frank Pfenning In these notes we review contracts, which we use to collectively denote function contracts, loop invariants,

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #17. Loops: Break Statement

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #17. Loops: Break Statement Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #17 Loops: Break Statement (Refer Slide Time: 00:07) In this session we will see one more feature that is present

More information

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d)

Tail Calls. CMSC 330: Organization of Programming Languages. Tail Recursion. Tail Recursion (cont d) Names and Binding. Tail Recursion (cont d) CMSC 330: Organization of Programming Languages Tail Calls A tail call is a function call that is the last thing a function does before it returns let add x y = x + y let f z = add z z (* tail call *)

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

Z Notation. June 21, 2018

Z Notation. June 21, 2018 Z Notation June 21, 2018 1 Definitions There are many different ways to introduce an object in a Z specification: declarations, abbreviations, axiomatic definitions, and free types. Keep in mind that the

More information

Recursion and Induction

Recursion and Induction Recursion and Induction Paul S. Miner NASA Langley Formal Methods Group p.s.miner@nasa.gov 28 November 2007 Outline Recursive definitions in PVS Simple inductive proofs Automated proofs by induction More

More information

COP 2000 Introduction to Computer Programming Mid-Term Exam Review

COP 2000 Introduction to Computer Programming Mid-Term Exam Review he exam format will be different from the online quizzes. It will be written on the test paper with questions similar to those shown on the following pages. he exam will be closed book, but students can

More information

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE PART A UNIT I 1. Differentiate object oriented programming from procedure oriented programming. 2. Define abstraction and encapsulation. 3. Differentiate

More information

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003 Control Flow COMS W1007 Introduction to Computer Science Christopher Conway 3 June 2003 Overflow from Last Time: Why Types? Assembly code is typeless. You can take any 32 bits in memory, say this is an

More information

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages Harvard School of Engineering and Applied Sciences CS 152: Programming Languages Lecture 19 Tuesday, April 3, 2018 1 Introduction to axiomatic semantics The idea in axiomatic semantics is to give specifications

More information

Flow Control. CSC215 Lecture

Flow Control. CSC215 Lecture Flow Control CSC215 Lecture Outline Blocks and compound statements Conditional statements if - statement if-else - statement switch - statement? : opertator Nested conditional statements Repetitive statements

More information

CS112 Lecture: Repetition Statements

CS112 Lecture: Repetition Statements CS112 Lecture: Repetition Statements Objectives: Last revised 2/18/05 1. To explain the general form of the java while loop 2. To introduce and motivate the java do.. while loop 3. To explain the general

More information

Incremental Proof Development in Dafny

Incremental Proof Development in Dafny 15-414 Lecture 17 1 Instructor: Matt Fredrikson Incremental Proof Development in Dafny TA: Ryan Wagner In this discussion, we ll see in more detail how to go about proving the total correctness of imperative

More information

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square) CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square) Introduction This semester, through a project split into 3 phases, we are going

More information

The design of a programming language for provably correct programs: success and failure

The design of a programming language for provably correct programs: success and failure The design of a programming language for provably correct programs: success and failure Don Sannella Laboratory for Foundations of Computer Science School of Informatics, University of Edinburgh http://homepages.inf.ed.ac.uk/dts

More information

CSE 331 Final Exam 3/16/15 Sample Solution

CSE 331 Final Exam 3/16/15 Sample Solution Question 1. (12 points, 3 each) A short design exercise. Suppose Java did not include a Set class in the standard library and we need to store a set of Strings for an application. We know that the maximum

More information

Haskell Overview II (2A) Young Won Lim 8/9/16

Haskell Overview II (2A) Young Won Lim 8/9/16 (2A) Copyright (c) 2016 Young W. Lim. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published

More information

Chapter 3 (part 3) Describing Syntax and Semantics

Chapter 3 (part 3) Describing Syntax and Semantics Chapter 3 (part 3) Describing Syntax and Semantics Chapter 3 Topics Introduction The General Problem of Describing Syntax Formal Methods of Describing Syntax Attribute Grammars Describing the Meanings

More information

Program Verification. Program Verification 307/434

Program Verification. Program Verification 307/434 Program Verification Program Verification 307/434 Outline Introduction: What and Why? Pre- and Postconditions Conditionals while-loops and Total Correctness Arrays Program Verification Introduction 308/434

More information

Chapter 3. Describing Syntax and Semantics ISBN

Chapter 3. Describing Syntax and Semantics ISBN Chapter 3 Describing Syntax and Semantics ISBN 0-321-49362-1 Chapter 3 Topics Introduction The General Problem of Describing Syntax Formal Methods of Describing Syntax Attribute Grammars Describing the

More information

The pre-processor (cpp for C-Pre-Processor). Treats all # s. 2 The compiler itself (cc1) this one reads text without any #include s

The pre-processor (cpp for C-Pre-Processor). Treats all # s. 2 The compiler itself (cc1) this one reads text without any #include s Session 2 - Classes in C++ Dr Christos Kloukinas City, UoL http://staff.city.ac.uk/c.kloukinas/cpp (slides originally produced by Dr Ross Paterson) A C++ source file may contain: include directives #include

More information

Why Design by Contract! CS 619 Introduction to OO Design and Development. Design by Contract. Fall 2012

Why Design by Contract! CS 619 Introduction to OO Design and Development. Design by Contract. Fall 2012 Why Design by Contract What s the difference with Testing? CS 619 Introduction to OO Design and Development Design by Contract Fall 2012 Testing tries to diagnose (and cure) defects after the facts. Design

More information

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved.

Chapter 3. More Flow of Control. Copyright 2008 Pearson Addison-Wesley. All rights reserved. Chapter 3 More Flow of Control Overview 3.1 Using Boolean Expressions 3.2 Multiway Branches 3.3 More about C++ Loop Statements 3.4 Designing Loops Slide 3-3 Flow Of Control Flow of control refers to the

More information

9/10/2018 Programming Data Structures Inheritance

9/10/2018 Programming Data Structures Inheritance 9/10/2018 Programming Data Structures Inheritance 1 Email me if the office door is closed 2 Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same

More information

Outline. Computer Science 331. Three Classical Algorithms. The Sorting Problem. Classical Sorting Algorithms. Mike Jacobson. Description Analysis

Outline. Computer Science 331. Three Classical Algorithms. The Sorting Problem. Classical Sorting Algorithms. Mike Jacobson. Description Analysis Outline Computer Science 331 Classical Sorting Algorithms Mike Jacobson Department of Computer Science University of Calgary Lecture #22 1 Introduction 2 3 4 5 Comparisons Mike Jacobson (University of

More information

3. Java - Language Constructs I

3. Java - Language Constructs I Educational Objectives 3. Java - Language Constructs I Names and Identifiers, Variables, Assignments, Constants, Datatypes, Operations, Evaluation of Expressions, Type Conversions You know the basic blocks

More information

The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

More information

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1 A Second Look At ML Chapter Seven Modern Programming Languages, 2nd ed. 1 Outline Patterns Local variable definitions A sorting example Chapter Seven Modern Programming Languages, 2nd ed. 2 Two Patterns

More information

CSCI.6962/4962 Software Verification Fundamental Proof Methods in Computer Science (Arkoudas and Musser) Chapter p. 1/27

CSCI.6962/4962 Software Verification Fundamental Proof Methods in Computer Science (Arkoudas and Musser) Chapter p. 1/27 CSCI.6962/4962 Software Verification Fundamental Proof Methods in Computer Science (Arkoudas and Musser) Chapter 2.1-2.7 p. 1/27 CSCI.6962/4962 Software Verification Fundamental Proof Methods in Computer

More information

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #2 Examination 12:30 noon, Thursday, March 15, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)

More information

Verification Condition Generation

Verification Condition Generation Verification Condition Generation Jorge Sousa Pinto Departamento de Informática / Universidade do Minho jsp@di.uminho.pt www.di.uminho.pt/~jsp Outline (1) - From Hoare Logic to VCGen algorithms: an architecture

More information

AXIOMS OF AN IMPERATIVE LANGUAGE PARTIAL CORRECTNESS WEAK AND STRONG CONDITIONS. THE AXIOM FOR nop

AXIOMS OF AN IMPERATIVE LANGUAGE PARTIAL CORRECTNESS WEAK AND STRONG CONDITIONS. THE AXIOM FOR nop AXIOMS OF AN IMPERATIVE LANGUAGE We will use the same language, with the same abstract syntax that we used for operational semantics. However, we will only be concerned with the commands, since the language

More information

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules

Haskell: From Basic to Advanced. Part 2 Type Classes, Laziness, IO, Modules Haskell: From Basic to Advanced Part 2 Type Classes, Laziness, IO, Modules Qualified types In the types schemes we have seen, the type variables were universally quantified, e.g. ++ :: [a] -> [a] -> [a]

More information

Compiler Errors. Flash CS4 Professional ActionScript 3.0 Language Reference. 1 of 18 9/6/2010 9:40 PM

Compiler Errors. Flash CS4 Professional ActionScript 3.0 Language Reference. 1 of 18 9/6/2010 9:40 PM 1 of 18 9/6/2010 9:40 PM Flash CS4 Professional ActionScript 3.0 Language Reference Language Reference only Compiler Errors Home All Packages All Classes Language Elements Index Appendixes Conventions

More information

Wellesley College CS251 Programming Languages Spring, 2000 FINAL EXAM REVIEW PROBLEM SOLUTIONS

Wellesley College CS251 Programming Languages Spring, 2000 FINAL EXAM REVIEW PROBLEM SOLUTIONS Wellesley College CS251 Programming Languages Spring, 2000 FINAL EXAM REVIEW PROBLEM SOLUTIONS This document contains solutions to the problems on the final exam review problems posted earlier except for

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

More information

Programming in OOP/C++

Programming in OOP/C++ Introduction Lecture 3-2 Programming in OOP/C++ Arrays Part (2) By Assistant Professor Dr. Ali Kattan 1 Arrays Examples Solutions for previous assignments Write a program to enter and store your name and

More information

SPARK-PL: Introduction

SPARK-PL: Introduction Alexey Solovyev Abstract All basic elements of SPARK-PL are introduced. Table of Contents 1. Introduction to SPARK-PL... 1 2. Alphabet of SPARK-PL... 3 3. Types and variables... 3 4. SPARK-PL basic commands...

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

Our Strategy for Learning Fortran 90

Our Strategy for Learning Fortran 90 Our Strategy for Learning Fortran 90 We want to consider some computational problems which build in complexity. evaluating an integral solving nonlinear equations vector/matrix operations fitting data

More information

Softwaretechnik. Program verification. Albert-Ludwigs-Universität Freiburg. June 28, Softwaretechnik June 28, / 24

Softwaretechnik. Program verification. Albert-Ludwigs-Universität Freiburg. June 28, Softwaretechnik June 28, / 24 Softwaretechnik Program verification Albert-Ludwigs-Universität Freiburg June 28, 2012 Softwaretechnik June 28, 2012 1 / 24 Road Map Program verification Automatic program verification Programs with loops

More information

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING BCS THE CHARTERED INSTITUTE FOR IT BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING Wednesady 23 rd March 2016 Afternoon Answer any FOUR questions out of SIX. All

More information

Developing Reliable Software using Object-Oriented Formal Specification and Refinement [Extended abstract prepared 24 March 2003]

Developing Reliable Software using Object-Oriented Formal Specification and Refinement [Extended abstract prepared 24 March 2003] Developing Reliable Software using Object-Oriented Formal Specification and Refinement [Extended abstract prepared 24 March 2003] Dr. David Crocker Escher Technologies Ltd., Mallard House, Hillside Road,

More information

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions

PROGRAMMING IN HASKELL. CS Chapter 6 - Recursive Functions PROGRAMMING IN HASKELL CS-205 - Chapter 6 - Recursive Functions 0 Introduction As we have seen, many functions can naturally be defined in terms of other functions. factorial :: Int Int factorial n product

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 6A Fall 05 Structure and Interpretation of Computer Programs Final INSTRUCTIONS You have hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator, except

More information

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions

PROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions 0 Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x 2 x {1...5}} The set {1,4,9,16,25}

More information

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance Handout written by Julie Zelenski, updated by Jerry. Inheritance is a language property most gracefully supported by the object-oriented

More information

REPETITION CONTROL STRUCTURE LOGO

REPETITION CONTROL STRUCTURE LOGO CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

More information

CMSC 330: Organization of Programming Languages. Functional Programming with Lists

CMSC 330: Organization of Programming Languages. Functional Programming with Lists CMSC 330: Organization of Programming Languages Functional Programming with Lists CMSC330 Spring 2018 1 Lists in OCaml The basic data structure in OCaml Lists can be of arbitrary length Implemented as

More information

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language Categories of languages that support OOP: 1. OOP support is added to an existing language - C++ (also supports procedural and dataoriented programming) - Ada 95 (also supports procedural and dataoriented

More information

CS134 Spring 2005 Final Exam Mon. June. 20, 2005 Signature: Question # Out Of Marks Marker Total

CS134 Spring 2005 Final Exam Mon. June. 20, 2005 Signature: Question # Out Of Marks Marker Total CS134 Spring 2005 Final Exam Mon. June. 20, 2005 Please check your tutorial (TUT) section from the list below: TUT 101: F 11:30, MC 4042 TUT 102: M 10:30, MC 4042 TUT 103: M 11:30, MC 4058 TUT 104: F 10:30,

More information

CS 270 Algorithms. Oliver Kullmann. Binary search. Lists. Background: Pointers. Trees. Implementing rooted trees. Tutorial

CS 270 Algorithms. Oliver Kullmann. Binary search. Lists. Background: Pointers. Trees. Implementing rooted trees. Tutorial Week 7 General remarks Arrays, lists, pointers and 1 2 3 We conclude elementary data structures by discussing and implementing arrays, lists, and trees. Background information on pointers is provided (for

More information

Get Unique study materials from

Get Unique study materials from Downloaded from www.rejinpaul.com VALLIAMMAI ENGNIEERING COLLEGE SRM Nagar, Kattankulathur 603203. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Year & Semester : IV Section : EEE - 1 & 2 Subject Code

More information

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal Lesson Goals Understand Control Structures Understand how to control the flow of a program

More information

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning

Lecture 1 Contracts. 1 A Mysterious Program : Principles of Imperative Computation (Spring 2018) Frank Pfenning Lecture 1 Contracts 15-122: Principles of Imperative Computation (Spring 2018) Frank Pfenning In these notes we review contracts, which we use to collectively denote function contracts, loop invariants,

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information