Introduction to the Go Programming Language

Save this PDF as:
 WORD  PNG  TXT  JPG

Size: px
Start display at page:

Download "Introduction to the Go Programming Language"

Transcription

1 Introduction to the Go Programming Language Basics, Concurrency and Useful Packages Fabian Wenzelmann April 6, 2017 F. Wenzelmann Introduction to Go April 6, / 114

2 Why Go? What is Go? Go is a programming language developed at Google It is free and open source, available for Linux, Windows and Apple OS X Some buzzwords Compiled Statically typed Provides garbage collection Features concurrent programming F. Wenzelmann Introduction to Go April 6, / 114

3 Hello World package main import ( fmt ) f u n c main ( ) { fmt. P r i n t l n ( H e l l o World! ) Try on Go Playground: F. Wenzelmann Introduction to Go April 6, / 114

4 Installing Go I We will do some small exercises togehter, to follow this you need to install Go I recommend using Go 1.7 Follow instructions here: install from.tar Don t forget to set $GOPATH git clone in your src directory... or clone it somewhere and use docker: 1 docker-compose up 2 docker-compose exec golang /bin/bash F. Wenzelmann Introduction to Go April 6, / 114

5 Installing Go II Test your installation: go install golangsrc/examples/helloworld Execute /go/bin/helloworld (or whatever your gopath is) We ll discuss how to organize go code a bit All the examples from the slides can be found in golangsrc/examples Exercise templates (most of them can t be compiled until you do the exercise) in golangsrc/exercises F. Wenzelmann Introduction to Go April 6, / 114

6 Defining Functions Function definition with the func keyword The type of a variable / function comes after the variable name / function name You don t use a semicolon to end a statement f u n c IntMax ( a i n t, b i n t ) i n t { i f a > b { r e t u r n a e l s e { r e t u r n b Playground: F. Wenzelmann Introduction to Go April 6, / 114

7 Variables and Types Builtin Types Many types for ints and floats (numeric types) int8, int16, int32, int64: architecture-independent for n-bit integers There are also unsigned n-bit integers like uint8, uint16,... float32, float64 complex64, complex128 byte is an alias of uint8 bool predeclared constants true and false string is a sequence of bytes. We ll come to that later. Numeric Types When working with ints or floats you usually work with the implementation-specific types int and uint which is either a 32 or 64 bit integer. F. Wenzelmann Introduction to Go April 6, / 114

8 Variables and Types Defining a Variable There are different ways of defining a variable: f u n c main ( ) { v a r i i n t = 21 v a r j i n t j = 42 k := 84 // s h o r t a s s i g n m e n t s t a t e m e n t fmt. P r i n t l n ( i, j, k ) Playground: Short assignment statements can be used inside function definitions, the type in this example is int. F. Wenzelmann Introduction to Go April 6, / 114

9 Variables and Types About Types and Conversions Go doesn t do automatic type conversions, you have to do it explictly int is a new type that is set to be either int32 or int64, but it is not an alias for it! v a r i i n t 6 4 = 42 v a r j i n t = i cannot use i (type int64) as type int in assignment v a r j i n t = i n t ( i ) An exception is byte which is really an alias for uint8 F. Wenzelmann Introduction to Go April 6, / 114

10 Case Distinction If-Else and Switches I If-Else statements don t require parentheses, but braces are required There is no thing like pythons elif, a switch statement is heavily used in Go You can only use type bool in if statements f u n c RateNumber (num i n t ) { i f num == 42 { fmt. P r i n t l n ( The answer to e v e r y t h i n g ) e l s e i f num == 21 { fmt. P r i n t l n ( Only h a l f the t r u t h ) e l s e { fmt. P r i n t l n ( What a lame number ) F. Wenzelmann Introduction to Go April 6, / 114

11 Case Distinction If-Else and Switches II f u n c RateNumber (num i n t ) { s w i t c h num { c a s e 4 2 : fmt. P r i n t l n ( The answer to e v e r y t h i n g ) c a s e 2 1 : fmt. P r i n t l n ( Only h a l f the t r u t h ) d e f a u l t : fmt. P r i n t l n ( What a lame number ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

12 Case Distinction About the Switch Statement I Switches work with many types, for example strings (and something like a type switch) Cases are evaluated from top to bottom and the switch stops when a case succeeds If you want a fallthrough behaviour like in C++ use the fallthrough keyword at the end of the case If no variable is specified, a switch on the first case that evaluates to true is performed You can specifiy multiple values in one case, separated by comma F. Wenzelmann Introduction to Go April 6, / 114

13 Case Distinction About the Switch Statement II f u n c WakeUp( h i n t ) { s w i t c h { c a s e h < 1 1 : fmt. P r i n t l n ( Eeeew, t h a t e a r l y? ) c a s e h > 1 5 : fmt. P r i n t l n ( Had some fun l a s t n i g h t? ) d e f a u l t : fmt. P r i n t l n ( Seems p r e t t y normal to me. ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

14 Loops The For Loop I There is only one statement in Go for a loop, for There are different variations of this statement: f u n c PrintNumbers ( s t a r t, end i n t ) { f o r i := s t a r t ; i < end ; i++ { fmt. P r i n t l n ( i ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

15 Loops The For Loop II The init and post statements are optional Just put the ; there and leave the commands blank continue and break are supported f u n c F a c t o r i a l ( n u i n t ) u i n t { v a r r e s u i n t = 1 v a r i u i n t = 1 f o r ; i <= n ; i++ { r e s = i r e t u r n r e s Playground: F. Wenzelmann Introduction to Go April 6, / 114

16 Loops The For Loop III If you want something like a while loop use for with just a condition: f o r i < n { // your code h e r e For an infinite loop skip even that: f o r { // your code h e r e F. Wenzelmann Introduction to Go April 6, / 114

17 Loops Switches in a for-loop I Caution Be careful that the break statement breaks a switch statement as well as a for loop! So using break in a switch statement inside a for loop breaks the switch, not the for! F. Wenzelmann Introduction to Go April 6, / 114

18 Loops Switches in a for-loop II We want define a function that prints the first number i between start and end that is divisible by num The following code is wrong f u n c P r i n t D i v i s i b l e ( s t a r t, end, num i n t ) { f o r i := s t a r t ; i <= end ; i++ { s w i t c h { c a s e i%num == 0 : fmt. P r i n t f ( F i r s t number d i v i s i b l e by %d i s %d\n, num, i ) b reak Playground: F. Wenzelmann Introduction to Go April 6, / 114

19 Loops Switches in a for-loop III You have to create a label for breaking the loop in this case: f u n c P r i n t D i v i s i b l e ( s t a r t, end, num i n t ) { Loop : f o r i := s t a r t ; i <= end ; i++ { s w i t c h { c a s e i%num == 0 : fmt. P r i n t f ( F i r s t number d i v i s i b l e by %d i s %d\n, num, i ) b reak Loop Playground: F. Wenzelmann Introduction to Go April 6, / 114

20 Loops Switches in a for-loop IV The same problem with break occurs when using a select statement (later) When working with switches in loops it s usually a good idea to use a label and use break / continue with the label F. Wenzelmann Introduction to Go April 6, / 114

21 Loops Exercise Session 1 I Before we start the exercises: You should either copy the template from the exercises directory into mysolutions... or edit the template files directly, make sure to keep the directory structure Sample solutions are in solutions, but this spoils the fun The exercises are not very challenging, you should just get familiar with Go cd into the directory containing the.go file and compile with go build FILENAME.go This creates an executable called FILENAME F. Wenzelmann Introduction to Go April 6, / 114

22 Loops Exercise Session 1 II Exercise Template: exercises/prime (a) Implement a function I s P r i m e ( n u i n t ) b o o l that tests if n is prime number (b) In the main() function print the first 100 prime numbers F. Wenzelmann Introduction to Go April 6, / 114

23 Loops Exercise Session 1 III Exercise Template: exercises/exp Implement a method Exp ( x, e p s i l o n f l o a t 6 4 ) f l o a t 6 4 That computes e x with the following sum: e x = Stop when two consecutive sums differ by a value < ε where ε > 0. n=0 x n n! F. Wenzelmann Introduction to Go April 6, / 114

24 Strings, Arrays and Slices Arrays Arrays are very important, but you don t use them very often directly - instead you use slices An array of type T of size n is declared as var array [n]t Note that var array [n]t and var array [m]t are different types for n m The elements are initialized with a default value (0 for numbers) Access as in other languages: array[i] Example: F. Wenzelmann Introduction to Go April 6, / 114

25 Strings, Arrays and Slices Working With Arrays Arrays are not passed by reference, you ll always get a copy when passing it to a function / assigning an existing array to a variable Example: Instead of arrays you usually use a slice F. Wenzelmann Introduction to Go April 6, / 114

26 Strings, Arrays and Slices Slices I A slice describes a part of an array A slice itself is not an array, but uses an array defined somewhere else A slice of type T has the signature []T and it can be created from an array given the start and end position Slices are always passed by reference Create a slice from an array with a[start:end] Chaning the value s[i] = something changes the value in the underlying array Example: F. Wenzelmann Introduction to Go April 6, / 114

27 Strings, Arrays and Slices Slices II You can also create a slice from an existing one and get / set an element out of a slice using the same notation as with arrays: v a r a r r a y [ 4 ] i n t a r r a y [ 0 ] = 1 a r r a y [ 1 ] = 2 a r r a y [ 2 ] = 3 a r r a y [ 3 ] = 4 s1 := a r r a y [ 1 : 4 ] s2 := s1 [ 1 : 2 ] fmt. P r i n t l n ( s2 ) fmt. P r i n t l n ( s1 [ 0 ] ) fmt. P r i n t l n ( s2 [ 0 ] ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

28 Strings, Arrays and Slices Slices in Action A slice can be used as you use a vector in other programming languages You can append elements to a slice, if the underlying array is not big enough a new one will be allocated This especially means that if a slice grows bigger than its capacity you don t reference the same array as before! You can determine the size of a slice with the len method: len(s) A slice also has a capacity, which stores how much space the underlying array has Further reading: F. Wenzelmann Introduction to Go April 6, / 114

29 Strings, Arrays and Slices Slice Examples I To create an empty slice of type T you can use the make method: s := make ( [ ] i n t, 5) This will create a slice containing five elements (all 0) You can also specify the a capacity (the size of the underlying array): s := make ( [ ] i n t, 5, 10) The length of this slice is 5, but if you append another element there is no need to create a new array Example on Playground: F. Wenzelmann Introduction to Go April 6, / 114

30 Strings, Arrays and Slices Slice Examples II The append function appends an element to a slice and returns a new slice (remember that the array underneath can grow) You can also pass more than one element to append s := make ( [ ] i n t, 1, 1) s = append ( s, 1) fmt. P r i n t l n ( s :, s ) s2 := s [ : ] s [ 0 ] = 21 s2 = append ( s2, 2, 3) fmt. P r i n t l n ( s2 :, s2 ) s [ 1 ] = 42 fmt. P r i n t l n ( s a f t e r m o d i f i c a t i o n o f s :, s ) fmt. P r i n t l n ( s2 a f t e r m o d i f i c a t i o n o f s :, s2 ) Try on the Playground: F. Wenzelmann Introduction to Go April 6, / 114

31 Strings, Arrays and Slices Iterating Over Slices You can iterate over a slice with for i := 0; i < len(s); i++ Or you can use the function range (more common): f o r i, v := range s { fmt. P r i n t f ( Element on p o s i t i o n %d i s %v\n, i, v ) An example on the Playground: If you re not interested in the position of an element name the variable There is an alternative method for creating a slice given an enumeration of its values: s := [ ] f l o a t 6 4 { 0. 5, , , 42.5 F. Wenzelmann Introduction to Go April 6, / 114

32 Strings, Arrays and Slices Strings The builtin type string is often used in the wrong way... For Go a string is just a (read-only) slice of bytes Go doesn t care if it is encoded in ASCII, UTF-8 or something else The notation str[k] returns the k-th byte in the string: v a r s t r s t r i n g = f o o bar fmt. P r i n t l n ( s t r ) fmt. P r i n t l n ( s t r [ 4 : ] ) fmt. P r i n t l n ( l e n ( s t r ) ) fmt. P r i n t l n ( s t r [ 1 ] ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

33 Strings, Arrays and Slices Strings and UTF-8 We can use UTF-8 in strings: s t r := e fmt. P r i n t l n ( s t r ) fmt. P r i n t l n ( l e n ( s t r ) ) Playground: UTF-8 uses a different number of bytes, depending on the encoded char (e for example requires three bytes) So a for loop f o r i := 0 ; i < l e n ( s t r ) ; i++ {... should not be used to iterate over each character! F. Wenzelmann Introduction to Go April 6, / 114

34 Strings, Arrays and Slices rune Go uses a special type rune, which is an int32. This is a unicode codepoint The words character, codepoint etc. are used in an ambiguous way... What you know as a character in other languages can be thought of as a Go rune Rune constants are enclosed in single quotes in Go. For example 本 is mapped to the integer value (requires three bytes) Further reading: F. Wenzelmann Introduction to Go April 6, / 114

35 Strings, Arrays and Slices Using Strings You can concatenate strings with +: H e l l o + World We can also use the range function, this however treats strings in a special way! Instead of iterating over the bytes the function decodes one UTF-8 encoded rune in each iteration, the index of the loop is the starting position of the current rune. Note that some byte sequences are not valid UTF-8 points The package unicode/utf8 has some useful functions for working with strings and runes Other useful packages: 1 strings: Manipulate UTF-8 encoded strings 2 strconv: Conversion from and to basic types 3 regexp: Regular expressions F. Wenzelmann Introduction to Go April 6, / 114

36 Strings, Arrays and Slices Strings and Memory It s important to note that strings are just slices Therefor they refer to an array somewhere in the memory This can lead to memory problems: For example you load a big file in memory but you re only interested in some part of it If you get the part you re interested in by creating a slice, using some method from strings that only returns a slice of the existing string... the big array referenced by that slice will never be deleted by the garbage collection In such cases you should make a copy, use the copy function F. Wenzelmann Introduction to Go April 6, / 114

37 Other Basic Stuff Advanced Function Definitions I A function can have multiple return values (like tuples in python) and you can define multiple variables at once However there is no tuple type which you can use outside a function definition / variable initialization (kind of sad) A function can take an arbitrary number of arguments (of a certain type) Those elements are passed to the function as a slice F. Wenzelmann Introduction to Go April 6, / 114

38 Other Basic Stuff Advanced Function Definitions II f u n c MinMax ( a i n t, e l e m e n t s... i n t ) ( i n t, i n t ) { min, max := a, a f o r, v a l := range e l e m e n t s { s w i t c h { c a s e v a l < min : min = v a l c a s e v a l > max : max = v a l r e t u r n min, max Playground: F. Wenzelmann Introduction to Go April 6, / 114

39 Other Basic Stuff Advanced Function Definitions III Functions can be passed as arguments to functions and functions can return functions. Go also supports anonymous functions and closures F. Wenzelmann Introduction to Go April 6, / 114

40 Other Basic Stuff Advanced Function Definitions IV f u n c Chain ( f, g f u n c ( i n t ) i n t ) f u n c ( i n t ) i n t { r e t u r n f u n c ( n i n t ) i n t { r e t u r n f ( g ( n ) ) f u n c main ( ) { d o u b l e := f u n c ( n i n t ) i n t { r e t u r n 2 n addone := f u n c ( n i n t ) i n t { r e t u r n n + 1 fmt. P r i n t l n ( Chain ( double, addone ) ( 5 ) ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

41 Other Basic Stuff Advanced Function Definitions V f u n c F i b o n a c c i ( ) f u n c ( ) u i n t { v a r a, b u i n t = 0, 1 r e t u r n f u n c ( ) u i n t { r e s := a a, b = b, a+b r e t u r n r e s f u n c main ( ) { f i b := F i b o n a c c i ( ) f o r i := 0 ; i < 1 5 ; i++ { fmt. P r i n t l n ( f i b ( ) ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

42 Other Basic Stuff Exercise Session 2 I Exercise Template: exercises/mutliplyslice Implement a function M u l t i p l y S l i c e ( s [ ] i n t, num i n t ) [ ] i n t that repeats the slice s num times and returns the new slice. s := [ ] i n t {1, 2, 3 fmt. P r i n t l n ( M u l t i p l y S l i c e ( s, 3 ) ) [ ] F. Wenzelmann Introduction to Go April 6, / 114

43 Other Basic Stuff Exercise Session 2 II Exercise Template: exercises/palindrome Implement a function I s P a l i n d r o m e ( s s t r i n g ) b o o l that checks if s is a palindrome (ignoring cases). A palindrome is a string that reads the same backwards and forwards. Hint: Use []rune(s) to convert a string to a slice of runes. F. Wenzelmann Introduction to Go April 6, / 114

44 Other Basic Stuff Exercise Session 2 III Exercise Template: exercises/curry Implement a function Curry ( f f u n c ( x, y i n t ) i n t, x i n t ) f u n c ( y i n t ) i n t s.t. Curry(f, x)(y) evaluates to f(x, y). F. Wenzelmann Introduction to Go April 6, / 114

45 Other Basic Stuff Maps I The type map[keytype]valuetype implements dictionaries The KeyType is rather restricted, more information may be found here: However we can use int, string, pointers Short example: age := map [ s t r i n g ] i n t { Bob : 42, Susan : 21 age [ John ] = 84 fmt. P r i n t l n ( age [ Bob ] ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

46 Other Basic Stuff Maps II Remove an entry for key (if this is not a valid key nothing will happen): d e l e t e ( age, Bob ) d e l e t e ( age, George ) F. Wenzelmann Introduction to Go April 6, / 114

47 Other Basic Stuff Maps III To check if a value exists you can use a two-value assignment: agesusan, hassusan := age [ Susan ] agebob, hasbob := age [ Bob ] i f hassusan { fmt. P r i n t l n ( Age o f Susan i s, agesusan ) e l s e { fmt. P r i n t l n ( No e n t r y f o r Susan ) i f hasbob { fmt. P r i n t l n ( Age o f Bob i s, agebob ) e l s e { fmt. P r i n t l n ( No e n t r y f o r Bob ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

48 Other Basic Stuff Maps IV Iterate over a map with range: f o r key, v a l u e := range age { fmt. P r i n t l n ( Age o f, key, i s, v a l u e ) Playground: It is safe to delete keys from a map when iterating over it with range Maps are not safe to read / write concurrently from different goroutines, protected for example with a RWMutex F. Wenzelmann Introduction to Go April 6, / 114

49 Other Basic Stuff Pointers A pointer holds the memory address of a variable For a type T there is also a type *T The operator & generates a pointer from a variable, the operator * denotes the underlying value f u n c Swap ( a, b i n t ) { a, b = b, a f u n c main ( ) { a := 21 b := 42 Swap(&a, &b ) fmt. P r i n t l n ( a =, a, b =, b ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

50 Other Basic Stuff nil The special type nil is what you know as null pointer from other languages Technically nil is not a type, nil can be used for different types such as pointers, slices, maps A slice can be nil and the slice functions will treat it as empty So an empty slice can be defined like: v a r s [ ] i n t = n i l Or even just v a r s [ ] i n t F. Wenzelmann Introduction to Go April 6, / 114

51 Structs and Interfaces Structs Structs are used to group fields They don t work as classes as you know them from Java or other languages! You can define functions for your structs and they can be called with the dot notation F. Wenzelmann Introduction to Go April 6, / 114

52 Structs and Interfaces Defining Structs t y p e R e c t a n g l e s t r u c t { Width, Height f l o a t 6 4 f u n c ( r R e c t a n g l e ) Area ( ) f l o a t 6 4 { r e t u r n r. Width r. Height f u n c main ( ) { r1 := R e c t a n g l e {5, 10 r2 := R e c t a n g l e {Width : 10, Height : 20 fmt. P r i n t l n ( r1. Area ( ), r2. Area ( ) ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

53 Structs and Interfaces Receivers Area is a so called pointer receiver, because the Rectangle object is passed by pointer In contrast a value receiver does not receive a pointer but an actual struct value However in this case a copy of the struct is created and passed to the function, thus changes made to the struct are not present in the object you called the method on In most cases pointer receivers are the best option Slices and Maps Note that slices, strings and maps are always passed by reference, so you don t have to pass them by pointer. F. Wenzelmann Introduction to Go April 6, / 114

54 Structs and Interfaces Constructors I There is no such thing as a constructor in Go Instead for a struct T you usually define a method NewT(args) that returns a pointer to a new object: f u n c NewRectangle ( width, h e i g h t f l o a t 6 4 ) R e c t a n g l e { r e t u r n &R e c t a n g l e {Width : width, Height : h e i g h t F. Wenzelmann Introduction to Go April 6, / 114

55 Structs and Interfaces Constructors II You may have noticed the two different ways to create a new object: r1 := R e c t a n g l e {5, 10 r2 := R e c t a n g l e {Width : 10, Height : 20 The first one lists the elements in the order as defined in the struct definition, the second one uses name / value pairs The second one is much cleaner and easier to read! I don t know why this feature is not available for function calls... F. Wenzelmann Introduction to Go April 6, / 114

56 Structs and Interfaces Interfaces I An interface is a collection of method signatures You don t have to specify that a struct implements an interface, Go determines by itself if this is the case t y p e TwoDObject i n t e r f a c e { Area ( ) f l o a t 6 4 P e r i m e t e r ( ) f l o a t 6 4 Assuming we also defined the Perimeter function, a *Rectangle could be used as a TwoDObject F. Wenzelmann Introduction to Go April 6, / 114

57 Structs and Interfaces Interfaces II t y p e C i r c l e s t r u c t { Radius f l o a t 6 4 f u n c N e w C i r c l e ( r a d i u s f l o a t 6 4 ) C i r c l e { r e t u r n &C i r c l e { Radius : r a d i u s f u n c ( c C i r c l e ) Area ( ) f l o a t 6 4 { r e t u r n math. Pi c. Radius c. Radius f u n c ( c C i r c l e ) P e r i m e t e r ( ) f l o a t 6 4 { r e t u r n 2. 0 math. Pi c. Radius F. Wenzelmann Introduction to Go April 6, / 114

58 Structs and Interfaces Interfaces III f u n c P r i n t I n f o ( o b j e c t TwoDObject ) { fmt. P r i n t f ( TwoDObject : Area = %.3 f, P e r i m e t e r = %.3 f \n, o b j e c t. Area ( ), o b j e c t. P e r i m e t e r ( ) ) f u n c main ( ) { r := NewRectangle ( 5, 10) c := N e w C i r c l e ( 5 ) P r i n t I n f o ( r ) P r i n t I n f o ( c ) Complete code on Playground: F. Wenzelmann Introduction to Go April 6, / 114

59 Structs and Interfaces Interfaces IV Note that if you used a pointer receiver for type T to implement methods for an interface the type *T implements the interface, not T When using interfaces in functions you don t have to pass a pointer to that interface A variable of an interface type can have the value nil F. Wenzelmann Introduction to Go April 6, / 114

60 Structs and Interfaces Delegators I You can use delegators to delegate methods to another type: t y p e A s t r u c t { f u n c ( a A) Foo ( ) { fmt. P r i n t l n ( Foo on A ) a. Bar ( ) f u n c ( a A) Bar ( ) { fmt. P r i n t l n ( Bar on A ) t y p e B s t r u c t { A // d e l e g e methods to A f u n c ( b B) Bar ( ) { fmt. P r i n t l n ( Bar on B ) F. Wenzelmann Introduction to Go April 6, / 114

61 Structs and Interfaces Delegators II As seen before, all methods not defined in A and don t exist in B are delegated to the A instance Feels like overwriting and inheritance? It isn t! It s the so called composition pattern B is always of type B, and not of type A! F. Wenzelmann Introduction to Go April 6, / 114

62 Structs and Interfaces Defining an Alias for a Type You can define a new type by defining it as something like an alias for that type t y p e I n t S e t map [ i n t ] s t r u c t { But it is a completely new type that only is something like an alias for map[int]interface You can define functions explictly for this type like f u n c ( s e t I n t S e t ) I n s e r t ( v a l i n t ) { s e t [ v a l ] = s t r u c t {{ Playground: F. Wenzelmann Introduction to Go April 6, / 114

63 Structs and Interfaces Consts There are different ways to define const values, see for details Usually you define something like c o n s t GolangHome = h t t p s : / / g o l a n g. org / c o n s t ( Red = r e d Blue = b l u e ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

64 Structs and Interfaces Enum-like Types I Go doesn t support enum types Instead you usually define an alias of type int Go has an identifier iota that helps you generat sequences Details: We define an enumeration of all days of the week (though this is already done in the time package) F. Wenzelmann Introduction to Go April 6, / 114

65 Structs and Interfaces Enum-like Types II Define a const block and enumrate the possible values, use ioata to enumerate the concrete values: t y p e Weekday i n t c o n s t ( Monday = Weekday ( i o t a ) Tuesday Wednesday Thursday F r i d a y Saturday Sunday ) F. Wenzelmann Introduction to Go April 6, / 114

66 Structs and Interfaces Enum-like Types III Define some new methods for our new type Hint: It is always useful to define a method String() string, this value will be used by the print functions: f u n c ( day Weekday ) S t r i n g ( ) s t r i n g { s w i t c h day { c a s e Monday : r e t u r n Monday c a s e Tuesday : r e t u r n Tuesday... d e f a u l t : r e t u r n Unknown day Actually there is a tool for generating code for such types automatically, stringer F. Wenzelmann Introduction to Go April 6, / 114

67 Structs and Interfaces Enum-like Types IV Why the default case? In Go Weekday is just something like an alias for int You can still pass literals to a function that expects such a type (like an arbitrary integer in this example) This is however not so easy to understand, but is not needed that much You can read more about this here Full code example on the Playground: F. Wenzelmann Introduction to Go April 6, / 114

68 Structs and Interfaces Some Words About Types Go does not support generics There are some hacks which use interface{ and then you can use a cast This is however not very clean But it can be really annoying to define types like IntSet and StringSet and leads to code duplication No operator overloading You can use different types for keys in a dictionary, but the behaviour is rather confusing: See the Comparison Operators in the language spec and the blog post about maps F. Wenzelmann Introduction to Go April 6, / 114

69 Structs and Interfaces Exercise Session 3 I Exercise Template: exercises/twodobject Implement a new type RightTriangle. Implement all the methods for TwoDObject and use a value receiver (either just save c or compute it from a and b). F. Wenzelmann Introduction to Go April 6, / 114

70 Structs and Interfaces Exercise Session 3 II Exercise Template: exercises/bintree Implement a type BinTree that implements a binary search tree that stores values of type int. Implement that following methods: NewBinTree ( ) BinTree Add ( elem i n t ) C o n t a i n s ( elem i n t ) b o o l F. Wenzelmann Introduction to Go April 6, / 114

71 Structs and Interfaces Errors I Go doesn t use try / catch exception handling Instead functions that could encounter errors use multiple return values Usually one of this return values is of type error: t y p e e r r o r i n t e r f a c e { E r r o r ( ) s t r i n g F. Wenzelmann Introduction to Go April 6, / 114

72 Structs and Interfaces Errors II New errors can be created with the package errors: e := e r r o r s. New( This i s an e r r o r ) Or if formatting is needed with the fmt package: e := fmt. E r r o r f ( I n d e x out o f bounds : %d, i ) Or of course you can create your own error type and implement the interface F. Wenzelmann Introduction to Go April 6, / 114

73 Structs and Interfaces Error Example I f u n c P a r s e I n t ( s t r s t r i n g ) { v a l, e r r := s t r c o n v. A t o i ( s t r ) i f e r r!= n i l { fmt. P r i n t l n ( E r r o r :, e r r ) e l s e { fmt. P r i n t l n ( Value i s, v a l ) f u n c main ( ) { P a r s e I n t ( 42 ) P a r s e I n t ( 4a ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

74 Structs and Interfaces Error Example II There is also a special syntax for if statements that is used often in this context: f u n c P a r s e I n t ( s t r s t r i n g ) { i f v a l, e r r := s t r c o n v. A t o i ( s t r ) ; e r r!= n i l { fmt. P r i n t l n ( E r r o r :, e r r ) e l s e { fmt. P r i n t l n ( Value i s, v a l ) f u n c main ( ) { P a r s e I n t ( 42 ) P a r s e I n t ( 4a ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

75 Structs and Interfaces Type Assertions I If you want to know which concrete type an interface value has you can perform a type check For example you may have a type that implements error and do something specific if a certain type is returned Note: This is not the normal way to do this in Go... F. Wenzelmann Introduction to Go April 6, / 114

76 Structs and Interfaces Type Assertions II t y p e A c c e s s D e n i e d E r r o r s t r u c t { protectedname s t r i n g f u n c ( e A c c e s s D e n i e d E r r o r ) E r r o r ( ) s t r i n g { r e t u r n fmt. S p r i n t f ( A c c e s s to %s d e n i e d, e. protectedname ) f u n c E v a l E r r ( e r r e r r o r ) { i f e r r == n i l { r e t u r n i f a c c e s s E r r, ok := e r r. ( A c c e s s D e n i e d E r r o r ) ; ok { fmt. P r i n t l n ( E v i l! C a l l i n g :, a c c e s s E r r ) e l s e { fmt. P r i n t l n ( e r r ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

77 Structs and Interfaces Type Assertions III Can also be used in switch: f u n c P r e t t y ( a n y t h i n g i n t e r f a c e {) { s w i t c h v := a n y t h i n g. ( t y p e ) { c a s e i n t : fmt. P r i n t l n ( I n t :, v ) c a s e f l o a t 6 4, f l o a t 3 2 : fmt. P r i n t f ( F l o a t : %.2 f \n, v ) c a s e R e c t a n g l e : fmt. P r i n t f ( R e c t a n g l e : Width = %.2 f, Height = %.2 f \n, v. Width, v. Height ) d e f a u l t : fmt. P r i n t l n ( Something e l s e :, a n y t h i n g ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

78 Structs and Interfaces Reading a File and the defer Statement I The defer statement is used to defer the execution of function call until the surrounding function returns In the following example we show how to read a file line by line Golang has an interface called io.reader, see GoDoc It has a single function: t y p e Reader i n t e r f a c e { Read ( p [ ] b y t e ) ( n i n t, e r r e r r o r ) Which reads up to len(p) bytes into p and returns the number of bytes read Often you don t read directly from a Reader but use a bufio.reader or bufio.scanner F. Wenzelmann Introduction to Go April 6, / 114

79 Structs and Interfaces Reading a File and the defer Statement II f u n c main ( ) { f, e r r := os. Open ( t e s t. t x t ) i f e r r!= n i l { fmt. P r i n t l n ( E r r o r opening f i l e :, e r r ) os. E x i t ( 1 ) d e f e r f. C l o s e ( ) s c a n n e r := b u f i o. NewScanner ( f ) f o r s c a n n e r. Scan ( ) { fmt. P r i n t l n ( s c a n n e r. Text ( ) ) i f e r r = s c a n n e r. E r r ( ) ; e r r!= n i l { fmt. P r i n t l n ( E r r o r w h i l e r e a d i n g f i l e :, e r r ) os. E x i t ( 1 ) F. Wenzelmann Introduction to Go April 6, / 114

80 Structs and Interfaces Reading a File and the defer Statement III In the above example we first opened the file with os.open(...) Once sucessfully opened we defer the call to the Close function, that s to say we wait until the function finishes and then close the file We create a bufio.scanner, by default this will scan for line breaks, but you may set a different split function See GoDoc Note You can use multiple defer statements, even with the same variable name. The deferred call s arguments are evaluated immediately. But the function call is not executed until the surrounding function returns! a a F. Wenzelmann Introduction to Go April 6, / 114

81 Structs and Interfaces Reading a File and the defer Statement IV There is also a mechanism called panic and recover We will not discuss it here, here s some reading: F. Wenzelmann Introduction to Go April 6, / 114

82 Concurrency in Go What is Concurrency Wikipedia Concurrent computing is a form of computing in which several computations are executed during overlapping time periods concurrently instead of sequentially (one completing before the next starts). Source: We may think of it as many things happening simultaneously Many languages and models today are not very good at expressing this view F. Wenzelmann Introduction to Go April 6, / 114

83 Concurrency in Go The go Statement Go is most popular for its mechanism for concurrent programming, it s very easy to write concurrent programs in Go It provides the go statement for running things concurrently And it also has an easy way to communicate between things happening concurrently Go was strongly influenced by the paper Communicating Sequential Processes by C. A. R. Hoare, first published 1985 Electronic version: Further reading on the Go blog: Don t confuse concurrency and parallelism! F. Wenzelmann Introduction to Go April 6, / 114

84 Concurrency in Go Concurrency vs. Parallelism In what follows there are some quotes from Rob Pike s wonderful video Concurrency Is Not Parallelism : Concurrency is a way of thinking and designing / structuring software The goal of concurrency is a good structure (Concurrency) Is the execution of independently executing processes Parallelism on the other hand is the simultaneous execution of multiple things, possibly related, possibly not Dealing with a lot of things at once, vs doing a lot of things at once But often parallelism helps you because things run faster (they don t have to) when you execute concurrent go programs F. Wenzelmann Introduction to Go April 6, / 114

85 Concurrency in Go The go Statement - A Simple Example I The go statement starts a new goroutine and runs it concurrently It s as simple as this: Use go f(args) to run something concurrent, you don t wait for the routine to finish, you just start it and it does something for you A pretty easy example: f u n c main ( ) { go f u n c ( ) { f o r i := 0 ; i < 1 0 ; i++ { fmt. P r i n t l n ( i ) ( ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

86 Concurrency in Go The go Statement - A Simple Example II If you run the program, what happens? You ll probably see nothing, as mentioned before a new goroutine starts, the current goroutine will not wait for another one to finish! Add time.sleep() and we should see something f u n c main ( ) { go f u n c ( ) { f o r i := 0 ; i < 1 0 ; i++ { fmt. P r i n t l n ( i ) ( ) time. S l e e p (2 time. Second ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

87 Concurrency in Go The go Statement - A Simple Example III Of course using time.sleep is no proper way to wait for a goroutine to finish We need a way to communicate But first look at another simple example where we start multiple goroutines at once F. Wenzelmann Introduction to Go April 6, / 114

88 Concurrency in Go The go Statement - A Simple Example IV package main import ( fmt time ) f u n c main ( ) { f o r i := 0 ; i < 1 0 ; i++ { go f u n c ( v a l i n t ) { fmt. P r i n t l n ( v a l ) ( i ) time. S l e e p (2 time. Second ) Let s try it local, not in the Playground F. Wenzelmann Introduction to Go April 6, / 114

89 Concurrency in Go The go Statement - A Simple Example V You don t know in which order the goroutines are executed, so you get a more or less random sequence of outputs You can think of a goroutine as a lightweight thread, but it is not a thread as in other programming languages! Go will internally take care of everything, starting multiple threads on your OS for example goroutines are cheap. Of course they prodocue some overhead, but starting them is not very expensive. You can start even tens of thousands of such goroutines F. Wenzelmann Introduction to Go April 6, / 114

90 Concurrency in Go The go Statement - A Simple Example VI Why did we pass i as an argument to the function we started as a goroutine? If you don t pass an argument the functions uses i from the closure, but this closure is the same for all goroutines! This is a common mistake, you should always pass an argument to functions you start in a different goroutine inside a loop F. Wenzelmann Introduction to Go April 6, / 114

91 Concurrency in Go Introduction to Channels The most basic type for communicating between different goroutines are channels Think of them as conduits or assembly belts You can put an element of a certain type on the channel and receive an element from a channel They re safe for concurrent use, so many goroutines may write and read from a channel Go principle Do not communicate by sharing memory; instead, share memory by communicating. F. Wenzelmann Introduction to Go April 6, / 114

92 Concurrency in Go Unbuffered Channels I Create an (unbuffered) channel with make: c := make ( chan i n t ) This creates a channel in which you can write integer values For writing and receiving values there is the operator <- Write to channel: ch < 1 Read from channel: v := < ch F. Wenzelmann Introduction to Go April 6, / 114

93 Concurrency in Go Unbuffered Channels II f u n c main ( ) { ch := make ( chan i n t ) go f u n c ( ) { ch < 1 ( ) v := < ch fmt. P r i n t l n ( v ) Playground: Why is the write operation in a goroutine? Otherwise you get an error like fatal error: all goroutines are asleep - deadlock! This is because channels block F. Wenzelmann Introduction to Go April 6, / 114

94 Concurrency in Go Unbuffered Channels III The write operation blocks until the value is received by a read to that channel The read operation blocks until it reads a value from the channel This way you can synchronize goroutines I.e. they have to wait for each other to finish That leads to a simple pattern in Go: One goroutine waits for a read and one goroutine writes to that channel once it s finished F. Wenzelmann Introduction to Go April 6, / 114

95 Concurrency in Go Unbuffered Channels IV f u n c main ( ) { done := make ( chan b o o l ) // s t a r t a go r o u t i n e go f u n c ( ) { f o r i := 0 ; i < 1 0 ; i++ { fmt. P r i n t l n ( i ) // once done w r i t e to c h a n n e l done < t r u e ( ) // w a i t u n t i l g o r o u t i n e i s done < done Playground: F. Wenzelmann Introduction to Go April 6, / 114

96 Concurrency in Go Unbuffered Channels V After we start the goroutine we read from a channel - so the main goroutine blocks until a value on the channel appears The gouroutine first does some stuff and then informs the channel that it s done Let s look at a more complex example F. Wenzelmann Introduction to Go April 6, / 114

97 Concurrency in Go Computing the Minimum from a Slice of Ints I We want to compute the minimum from a slice of int values We will make some simplification and assume that the slice contains some elements Sequential approach: f u n c S l i c e M i n ( s [ ] i n t ) i n t { min := s [ 0 ] f o r, v := range s [ 1 : ] { i f v < min { min = v r e t u r n min F. Wenzelmann Introduction to Go April 6, / 114

98 Concurrency in Go Computing the Minimum from a Slice of Ints II Why don t we cut the slice into smaller pieces and run the method concurrent for all pieces? Use a channel to communicate the result of the concurrent methods F. Wenzelmann Introduction to Go April 6, / 114

99 Concurrency in Go Computing the Minimum from a Slice of Ints III f u n c main ( ) { s :=... n := l e n ( s ) ch := make ( chan i n t ) // s t a r t to go r o u t i n e s t h a t w r i t e t h e r e s u l t to ch go f u n c ( ) { ch < S l i c e M i n ( s [ : n / 2 ] ) () go f u n c ( ) { ch < S l i c e M i n ( s [ n / 2 : ] ) () res1 := < ch res2 := < ch i f res1 < res2 { fmt. P r i n t l n ( S m a l l e s t v a l u e :, r e s 1 ) e l s e { fmt. P r i n t l n ( S m a l l e s t v a l u e :, r e s 2 ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

100 Concurrency in Go Does Parallelism Help? In the above example we have the hope that our concurrent approach helps to improve the execution time due to parallelism Another question: Why only use two pieces? Why not split into even more? Parallelism Parallelism may help to improve your runtime, but this does not mean that a concurrent approach is always faster! Gos aim is to provide clear structured code via concurrency, not to improve your runtime using parallelism, but often enough this is the case! F. Wenzelmann Introduction to Go April 6, / 114

101 Concurrency in Go Buffered Channels Until now we ve only seen unbuffered channels Provide the buffer size as the second argument to make to create an unbuffered channel ch := make ( chan i n t, 10) Sends block only when the buffer is full, reads when the channel is empty Example: Coordinate n workers that work concurrently F. Wenzelmann Introduction to Go April 6, / 114

102 Concurrency in Go range and Closing Channels I If it is unkown how many arguments you have to read from a channel, you can use range ch to iterate over all its values This reads until the channel gets closed by close(ch) Example: Read values from a search of unkown size You can also close a channel and still retrieve the remaining results F. Wenzelmann Introduction to Go April 6, / 114

103 Concurrency in Go range and Closing Channels II f u n c main ( ) { ch := make ( chan i n t ) go f u n c ( ) { f o r i := 0 ; i < 1 0 ; i++ { ch < i c l o s e ( ch ) ( ) f o r v a l := range ch { fmt. P r i n t l n ( v a l ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

104 Concurrency in Go Read / Write Channels If you want to signal that a function only reads / writes to a channel you can use the type chan<- string for a channel were strings can be written <-chan string for a channel were strings can be read F. Wenzelmann Introduction to Go April 6, / 114

105 Concurrency in Go Running Multiple goroutines I Sometimes you need to run multiple goroutines that don t return anything / don t write to a channel In this case you can use a WaitGroup from the sync package F. Wenzelmann Introduction to Go April 6, / 114

106 Concurrency in Go Running Multiple goroutines II f u n c dosomething ( ) { time. S l e e p ( time. Second 3) f u n c main ( ) { v a r wg sync. WaitGroup wg. Add ( 5 ) f o r i := 0 ; i < 5 ; i++ { go f u n c ( ) { d e f e r wg. Done ( ) dosomething ( ) ( ) wg. Wait ( ) Playground: F. Wenzelmann Introduction to Go April 6, / 114

107 Concurrency in Go Running Multiple goroutines III With wg.add(n) you add n events to wait for After all our go routines are started you use wg.wait(). This operation blocks until the counter reaches zero. A call to wg.done() reduces the counter by one. If you have to dynmaically Add new values make sure that the counter can t reach zero until you call Add This means usually: calls to Add should execute before the statement creating the goroutine or other event to be waited for F. Wenzelmann Introduction to Go April 6, / 114

108 Concurrency in Go Running Multiple goroutines IV Make sure to always call wg.done defer is a good way to achieve this Read the doc for more details F. Wenzelmann Introduction to Go April 6, / 114

109 Concurrency in Go Exercise Session 4 I Exercise Template: exercises/matrix Implement matrix multiplication for two matrices A R n m and B R m k. In the template you ll find an implementation that doesn t use concurrency. Improve this implementation by starting a goroutine for each row in A and column in B. The main function creates some big matrices and compares the execution time of both implementations. F. Wenzelmann Introduction to Go April 6, / 114

110 Concurrency in Go Exercise Session 4 II Exercise Template: exercises/bintree Go has no iterator interface. There are two common approaches: 1 Implement a function that writes all values in a channel 2 Implement a function that accepts a function and applies a function to all values in the collection Implement both approaches for your BinTree type. Both versions should iterate the values sorted. I t e r a t e V a l u e s ( ch chan< i n t ) Apply ( f f u n c ( v a l i n t ) ) Implement the following with those methods (choose one or do both) 1 Print all values 2 Build the sum of all values F. Wenzelmann Introduction to Go April 6, / 114

111 Organzing Your Go Code Where to Put Your Go Code Usually all your Go code is in one src directory, usually in a directory go in your home Put your own code in a directory github.com/youraccount/yourpackage A package contains multiple source files, each file must have package line package PACKAGENAME You can add subpackages, but for small project this is sufficient Add a cmd directory and add subdirectory for each command For example if you have an executable helloworld, add cmd/helloworld/helloworld.go This file must have package main and a function main() F. Wenzelmann Introduction to Go April 6, / 114

112 Organzing Your Go Code Function and Struct Names Functions, Interfaces, Structs,... that begin with a capital letter are exported, i.e. can be used in other packages Everything that starts with a lowercase letter can only be used inside your package You should also format your Go code with gofmt helloworld.go or gofmt PACKAGE This shows you how the could should look like, add -w to apply the formatting directly to your file See F. Wenzelmann Introduction to Go April 6, / 114

113 Organzing Your Go Code Installing Third Party Packages Use go get github.com/..., for example to install the MySQL driver: gogetgithub.com/go-sql-driver/mysql Use go install github.com/... to also compile the main files See F. Wenzelmann Introduction to Go April 6, / 114

114 Organzing Your Go Code Documenting Your Code Document each function / struct with a comment starting with the name: // HelloWorld p r i n t s H e l l o World to the s t a n d a r d output f u n c HelloWorld ( ) { fmt. P r i n t l n ( H e l l o World ) If you upload your code to github.com your documentation can be found on godoc.org F. Wenzelmann Introduction to Go April 6, / 114

Go Forth and Code. Jonathan Gertig. CSC 415: Programing Languages. Dr. Lyle

Go Forth and Code. Jonathan Gertig. CSC 415: Programing Languages. Dr. Lyle J o n a t h a n G e r t i g P a g e 1 Go Forth and Code Jonathan Gertig CSC 415: Programing Languages Dr. Lyle 2013 J o n a t h a n G e r t i g P a g e 2 Go dogs Go or A Brief History of Go 6 years ago

More information

GO IDIOMATIC CONVENTIONS EXPLAINED IN COLOR

GO IDIOMATIC CONVENTIONS EXPLAINED IN COLOR GO IDIOMATIC CONVENTIONS EXPLAINED IN COLOR REVISION 1 HAWTHORNE-PRESS.COM Go Idiomatic Conventions Explained in Color Published by Hawthorne-Press.com 916 Adele Street Houston, Texas 77009, USA 2013-2018

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Go Tutorial. Arjun Roy CSE 223B, Spring 2017

Go Tutorial. Arjun Roy CSE 223B, Spring 2017 Go Tutorial Arjun Roy arroy@eng.ucsd.edu CSE 223B, Spring 2017 Administrative details TA Office Hours: EBU3B B250A, Tuesday 5-7PM TA Email: arroy@eng.ucsd.edu All labs due by 2359 PDT. Lab 1 due: 4/13/2017.

More information

The Go Programming Language. Frank Roberts

The Go Programming Language. Frank Roberts The Go Programming Language Frank Roberts frank.roberts@uky.edu - C++ (1983), Java (1995), Python (1991): not modern - Java is 18 years old; how has computing changed in 10? - multi/many core - web programming

More information

Go Cheat Sheet. Operators. Go in a Nutshell. Declarations. Basic Syntax. Hello World. Functions. Comparison. Arithmetic. Credits

Go Cheat Sheet. Operators. Go in a Nutshell. Declarations. Basic Syntax. Hello World. Functions. Comparison. Arithmetic. Credits Credits Go Cheat Sheet Most example code taken from A Tour of Go, which is an excellent introduction to Go. If you're new to Go, do that tour. Seriously. Original HTML Cheat Sheet by Ariel Mashraki (a8m):

More information

A Fast Review of C Essentials Part I

A Fast Review of C Essentials Part I A Fast Review of C Essentials Part I Structural Programming by Z. Cihan TAYSI Outline Program development C Essentials Functions Variables & constants Names Formatting Comments Preprocessor Data types

More information

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309 A Arithmetic operation floating-point arithmetic, 11 12 integer numbers, 9 11 Arrays, 97 copying, 59 60 creation, 48 elements, 48 empty arrays and vectors, 57 58 executable program, 49 expressions, 48

More information

Program Fundamentals

Program Fundamentals Program Fundamentals /* HelloWorld.java * The classic Hello, world! program */ class HelloWorld { public static void main (String[ ] args) { System.out.println( Hello, world! ); } } /* HelloWorld.java

More information

GO SHORT INTERVIEW QUESTIONS EXPLAINED IN COLOR

GO SHORT INTERVIEW QUESTIONS EXPLAINED IN COLOR GO SHORT INTERVIEW QUESTIONS EXPLAINED IN COLOR REVISION 1 HAWTHORNE-PRESS.COM Go Short Interview Questions Explained in Color Published by Hawthorne-Press.com 916 Adele Street Houston, Texas 77009, USA

More information

Let s Go! Akim D le, Etienne Renault, Roland Levillain. June 8, TYLA Let s Go! June 8, / 58

Let s Go! Akim D le, Etienne Renault, Roland Levillain. June 8, TYLA Let s Go! June 8, / 58 Let s Go! Akim Demaille, Etienne Renault, Roland Levillain June 8, 2017 TYLA Let s Go! June 8, 2017 1 / 58 Table of contents 1 Overview 2 Language Syntax 3 Closure 4 Typed functional programming and Polymorphism

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Introduzione a Go e RPC in Go

Introduzione a Go e RPC in Go Università degli Studi di Roma Tor Vergata Dipartimento di Ingegneria Civile e Ingegneria Informatica Introduzione a Go e RPC in Go Corso di Sistemi Distribuiti e Cloud Computing A.A. 2017/18 Valeria Cardellini

More information

Haskell Making Our Own Types and Typeclasses

Haskell Making Our Own Types and Typeclasses Haskell Making Our Own Types and Typeclasses http://igm.univ-mlv.fr/~vialette/?section=teaching Stéphane Vialette LIGM, Université Paris-Est Marne-la-Vallée January 13, 2015 Making Our Own Types and Typeclasses

More information

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I BASIC COMPUTATION x public static void main(string [] args) Fundamentals of Computer Science I Outline Using Eclipse Data Types Variables Primitive and Class Data Types Expressions Declaration Assignment

More information

At full speed with Python

At full speed with Python At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3

More information

understanding

understanding understanding nil @francesc thanks welcome every single one of you agenda what is nil? what is nil in Go? what does nil mean? is nil useful? nil? you misspelled null how I learn words how I learn words

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java

OCaml Data CMSC 330: Organization of Programming Languages. User Defined Types. Variation: Shapes in Java OCaml Data : Organization of Programming Languages OCaml 4 Data Types & Modules So far, we ve seen the following kinds of data Basic types (int, float, char, string) Lists Ø One kind of data structure

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

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

CS 360: Programming Languages Lecture 12: More Haskell

CS 360: Programming Languages Lecture 12: More Haskell CS 360: Programming Languages Lecture 12: More Haskell Geoffrey Mainland Drexel University Adapted from Brent Yorgey s course Introduction to Haskell. Section 1 Administrivia Administrivia Homework 5 due

More information

8. The C++ language, 1. Programming and Algorithms II Degree in Bioinformatics Fall 2017

8. The C++ language, 1. Programming and Algorithms II Degree in Bioinformatics Fall 2017 8. The C++ language, 1 Programming and Algorithms II Degree in Bioinformatics Fall 2017 Hello world #include using namespace std; int main() { } cout

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

MySQL: an application

MySQL: an application Data Types and other stuff you should know in order to amaze and dazzle your friends at parties after you finally give up that dream of being a magician and stop making ridiculous balloon animals and begin

More information

COMP-520 GoLite Tutorial

COMP-520 GoLite Tutorial COMP-520 GoLite Tutorial Alexander Krolik Sable Lab McGill University Winter 2019 Plan Target languages Language constructs, emphasis on special cases General execution semantics Declarations Types Statements

More information

William Kennedy. Brian Ketelsen Erik St. Martin Steve Francia FOREWORD BY MANNING WITH

William Kennedy. Brian Ketelsen Erik St. Martin Steve Francia FOREWORD BY MANNING WITH SAMPLE CHAPTER William Kennedy WITH FOREWORD BY Brian Ketelsen Erik St. Martin Steve Francia MANNING Go in Action by William Kennedy with Brian Ketelsen and Erik St. Martin Chapter 2 Copyright 2015 Manning

More information

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

Fall 2017 CISC124 9/16/2017

Fall 2017 CISC124 9/16/2017 CISC124 Labs start this week in JEFF 155: Meet your TA. Check out the course web site, if you have not already done so. Watch lecture videos if you need to review anything we have already done. Problems

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

Java+- Language Reference Manual

Java+- Language Reference Manual Fall 2016 COMS4115 Programming Languages & Translators Java+- Language Reference Manual Authors Ashley Daguanno (ad3079) - Manager Anna Wen (aw2802) - Tester Tin Nilar Hlaing (th2520) - Systems Architect

More information

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02 Hello, in this lecture we will learn about some fundamentals concepts of java.

More information

Lecture Overview Methods and Interfaces Methods review Interfaces Example: using the sort interface Anonymous fields in structs

Lecture Overview Methods and Interfaces Methods review Interfaces Example: using the sort interface Anonymous fields in structs 1 Lecture Overview Methods and Interfaces Methods review Interfaces Example: using the sort interface Anonymous fields in structs Generic printing using the empty interface Maps Creating a map Accessing

More information

Lecture 12: Data Types (and Some Leftover ML)

Lecture 12: Data Types (and Some Leftover ML) Lecture 12: Data Types (and Some Leftover ML) COMP 524 Programming Language Concepts Stephen Olivier March 3, 2009 Based on slides by A. Block, notes by N. Fisher, F. Hernandez-Campos, and D. Stotts Goals

More information

CS 360: Programming Languages Lecture 10: Introduction to Haskell

CS 360: Programming Languages Lecture 10: Introduction to Haskell CS 360: Programming Languages Lecture 10: Introduction to Haskell Geoffrey Mainland Drexel University Thursday, February 5, 2015 Adapted from Brent Yorgey s course Introduction to Haskell. Section 1 Administrivia

More information

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language 1 History C is a general-purpose, high-level language that was originally developed by Dennis M. Ritchie to develop the UNIX operating system at Bell Labs. C was originally first implemented on the DEC

More information

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program Syntax What the Compiler needs to understand your program 1 Pre-Processing Any line that starts with # is a pre-processor directive Pre-processor consumes that entire line Possibly replacing it with other

More information

Computer Programming C++ (wg) CCOs

Computer Programming C++ (wg) CCOs Computer Programming C++ (wg) CCOs I. The student will analyze the different systems, and languages of the computer. (SM 1.4, 3.1, 3.4, 3.6) II. The student will write, compile, link and run a simple C++

More information

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/ CS61C Machine Structures Lecture 4 C Pointers and Arrays 1/25/2006 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L04 C Pointers (1) Common C Error There is a difference

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

Fundamental Concepts and Definitions

Fundamental Concepts and Definitions Fundamental Concepts and Definitions Identifier / Symbol / Name These terms are synonymous: they refer to the name given to a programming component. Classes, variables, functions, and methods are the most

More information

Lecture Topics. Administrivia

Lecture Topics. Administrivia ECE498SL Lec. Notes L8PA Lecture Topics overloading pitfalls of overloading & conversions matching an overloaded call miscellany new & delete variable declarations extensibility: philosophy vs. reality

More information

The Warhol Language Reference Manual

The Warhol Language Reference Manual The Warhol Language Reference Manual Martina Atabong maa2247 Charvinia Neblett cdn2118 Samuel Nnodim son2105 Catherine Wes ciw2109 Sarina Xie sx2166 Introduction Warhol is a functional and imperative programming

More information

Summary of Go Syntax /

Summary of Go Syntax / Summary of Go Syntax 02-201 / 02-601 Can declare 1 or more variables in same var statement Variables Can optionally provide initial values for all the variables (if omitted, each variable defaults to the

More information

Lecture 22 Go http://xkcd.com/979/ Go developed ~2007 at Google by Robert Griesemer, Rob Pike, Ken Thompson open sourced in 2009 compiled, statically typed very fast compilation C-like syntax garbage collection

More information

Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso

Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso Design and development of embedded systems for the Internet of Things (IoT) Fabio Angeletti Fabrizio Gattuso Why C? Test on 21 Android Devices with 32-bits and 64-bits processors and different versions

More information

Programming with Math and Logic

Programming with Math and Logic .. Programming with Math and Logic an invitation to functional programming Ed Morehouse Wesleyan University The Plan why fp? terms types interfaces The What and Why of Functional Programming Computing

More information

BLM2031 Structured Programming. Zeyneb KURT

BLM2031 Structured Programming. Zeyneb KURT BLM2031 Structured Programming Zeyneb KURT 1 Contact Contact info office : D-219 e-mail zeynebkurt@gmail.com, zeyneb@ce.yildiz.edu.tr When to contact e-mail first, take an appointment What to expect help

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

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements Programming, Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science and Engineering Indian Institute of Technology, Madras Lecture 05 I/O statements Printf, Scanf Simple

More information

Introduction to the C++ Programming Language

Introduction to the C++ Programming Language LESSON SET 2 Introduction to the C++ Programming Language OBJECTIVES FOR STUDENT Lesson 2A: 1. To learn the basic components of a C++ program 2. To gain a basic knowledge of how memory is used in programming

More information

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please

More information

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

COMP322 - Introduction to C++ Lecture 02 - Basics of C++ COMP322 - Introduction to C++ Lecture 02 - Basics of C++ School of Computer Science 16 January 2012 C++ basics - Arithmetic operators Where possible, C++ will automatically convert among the basic types.

More information

C++ for Java Programmers

C++ for Java Programmers Basics all Finished! Everything we have covered so far: Lecture 5 Operators Variables Arrays Null Terminated Strings Structs Functions 1 2 45 mins of pure fun Introduction Today: Pointers Pointers Even

More information

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014 Lesson 10A OOP Fundamentals By John B. Owen All rights reserved 2011, revised 2014 Table of Contents Objectives Definition Pointers vs containers Object vs primitives Constructors Methods Object class

More information

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS

More information

6. Pointers, Structs, and Arrays. 1. Juli 2011

6. Pointers, Structs, and Arrays. 1. Juli 2011 1. Juli 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 50 Outline Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings Einführung

More information

Ch. 12: Operator Overloading

Ch. 12: Operator Overloading Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42

More information

Procedures, Parameters, Values and Variables. Steven R. Bagley

Procedures, Parameters, Values and Variables. Steven R. Bagley Procedures, Parameters, Values and Variables Steven R. Bagley Recap A Program is a sequence of statements (instructions) Statements executed one-by-one in order Unless it is changed by the programmer e.g.

More information

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc. Chapter 1 GETTING STARTED SYS-ED/ Computer Education Techniques, Inc. Objectives You will learn: Java platform. Applets and applications. Java programming language: facilities and foundation. Memory management

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

Topic 7: Algebraic Data Types

Topic 7: Algebraic Data Types Topic 7: Algebraic Data Types 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 5.5, 5.7, 5.8, 5.10, 5.11, 5.12, 5.14 14.4, 14.5, 14.6 14.9, 14.11,

More information

Full file at

Full file at Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

More information

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011 CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part II) Instructors: Randy H. Katz David A. Patterson http://inst.eecs.berkeley.edu/~cs61c/sp11 Spring 2011 -- Lecture

More information

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics COMP-202 Unit 1: Introduction Announcements Did you miss the first lecture? Come talk to me after class. If you want

More information

QUIZ Friends class Y;

QUIZ Friends class Y; QUIZ Friends class Y; Is a forward declaration neeed here? QUIZ Friends QUIZ Friends - CONCLUSION Forward (a.k.a. incomplete) declarations are needed only when we declare member functions as friends. They

More information

Programming refresher and intro to C programming

Programming refresher and intro to C programming Applied mechatronics Programming refresher and intro to C programming Sven Gestegård Robertz sven.robertz@cs.lth.se Department of Computer Science, Lund University 2018 Outline 1 C programming intro 2

More information

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */ Overview Language Basics This chapter describes the basic elements of Rexx. It discusses the simple components that make up the language. These include script structure, elements of the language, operators,

More information

COMP520 - GoLite Type Checking Specification

COMP520 - GoLite Type Checking Specification COMP520 - GoLite Type Checking Specification Vincent Foley April 8, 2018 1 Introduction This document presents the typing rules for all the language constructs (i.e. declarations, statements, expressions)

More information

Variables and Constants

Variables and Constants HOUR 3 Variables and Constants Programs need a way to store the data they use. Variables and constants offer various ways to work with numbers and other values. In this hour you learn: How to declare and

More information

printf( Please enter another number: ); scanf( %d, &num2);

printf( Please enter another number: ); scanf( %d, &num2); CIT 593 Intro to Computer Systems Lecture #13 (11/1/12) Now that we've looked at how an assembly language program runs on a computer, we're ready to move up a level and start working with more powerful

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CHAPTER 4 FUNCTIONS. 4.1 Introduction CHAPTER 4 FUNCTIONS 4.1 Introduction Functions are the building blocks of C++ programs. Functions are also the executable segments in a program. The starting point for the execution of a program is main

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

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program

More information

Question No: 1 ( Marks: 1 ) - Please choose one One difference LISP and PROLOG is. AI Puzzle Game All f the given

Question No: 1 ( Marks: 1 ) - Please choose one One difference LISP and PROLOG is. AI Puzzle Game All f the given MUHAMMAD FAISAL MIT 4 th Semester Al-Barq Campus (VGJW01) Gujranwala faisalgrw123@gmail.com MEGA File Solved MCQ s For Final TERM EXAMS CS508- Modern Programming Languages Question No: 1 ( Marks: 1 ) -

More information

What we already know. more of what we know. results, searching for "This" 6/21/2017. chapter 14

What we already know. more of what we know. results, searching for This 6/21/2017. chapter 14 What we already know chapter 14 Files and Exceptions II Files are bytes on disk. Two types, text and binary (we are working with text) open creates a connection between the disk contents and the program

More information

Type Checking and Type Equality

Type Checking and Type Equality Type Checking and Type Equality Type systems are the biggest point of variation across programming languages. Even languages that look similar are often greatly different when it comes to their type systems.

More information

CS349/SE382 A1 C Programming Tutorial

CS349/SE382 A1 C Programming Tutorial CS349/SE382 A1 C Programming Tutorial Erin Lester January 2005 Outline Comments Variable Declarations Objects Dynamic Memory Boolean Type structs, enums and unions Other Differences The Event Loop Comments

More information

Computer Components. Software{ User Programs. Operating System. Hardware

Computer Components. Software{ User Programs. Operating System. Hardware Computer Components Software{ User Programs Operating System Hardware What are Programs? Programs provide instructions for computers Similar to giving directions to a person who is trying to get from point

More information

Computer Programming : C++

Computer Programming : C++ The Islamic University of Gaza Engineering Faculty Department of Computer Engineering Fall 2017 ECOM 2003 Muath i.alnabris Computer Programming : C++ Experiment #1 Basics Contents Structure of a program

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

Programming in C and C++

Programming in C and C++ Programming in C and C++ Types, Variables, Expressions and Statements Neel Krishnaswami and Alan Mycroft Course Structure Basics of C: Types, variables, expressions and statements Functions, compilation

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

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG 1 Notice Reading Assignment Chapter 1: Introduction to Java Programming Homework 1 It is due this coming Sunday

More information

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

6. Pointers, Structs, and Arrays. March 14 & 15, 2011 March 14 & 15, 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 47 Outline Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings Einführung

More information

Embedded type method, overriding, Error handling, Full-fledged web framework, 208 Function defer, 31 panic, 32 recover, 32 33

Embedded type method, overriding, Error handling, Full-fledged web framework, 208 Function defer, 31 panic, 32 recover, 32 33 Index A Alice package, 108, 110 App Engine applications configuration file, 258 259 goapp deploy command, 262 Google Developers Console project creation, 261 project details, 262 HTTP server, 257 258 task

More information

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics Java Programming, Sixth Edition 2-1 Chapter 2 Using Data At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional Projects Additional

More information

Java Bytecode (binary file)

Java Bytecode (binary file) Java is Compiled Unlike Python, which is an interpreted langauge, Java code is compiled. In Java, a compiler reads in a Java source file (the code that we write), and it translates that code into bytecode.

More information

An introduction introduction to functional functional programming programming using usin Haskell

An introduction introduction to functional functional programming programming using usin Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dkau Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program

More information

Matlab for FMRI Module 1: the basics Instructor: Luis Hernandez-Garcia

Matlab for FMRI Module 1: the basics Instructor: Luis Hernandez-Garcia Matlab for FMRI Module 1: the basics Instructor: Luis Hernandez-Garcia The goal for this tutorial is to make sure that you understand a few key concepts related to programming, and that you know the basics

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

Chapter 2: Introduction to C++

Chapter 2: Introduction to C++ Chapter 2: Introduction to C++ Copyright 2010 Pearson Education, Inc. Copyright Publishing as 2010 Pearson Pearson Addison-Wesley Education, Inc. Publishing as Pearson Addison-Wesley 2.1 Parts of a C++

More information

LECTURE 02 INTRODUCTION TO C++

LECTURE 02 INTRODUCTION TO C++ PowerPoint Slides adapted from *Starting Out with C++: From Control Structures through Objects, 7/E* by *Tony Gaddis* Copyright 2012 Pearson Education Inc. COMPUTER PROGRAMMING LECTURE 02 INTRODUCTION

More information

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont.

5/3/2006. Today! HelloWorld in BlueJ. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. HelloWorld in BlueJ, Cont. Today! Build HelloWorld yourself in BlueJ and Eclipse. Look at all the Java keywords. Primitive Types. HelloWorld in BlueJ 1. Find BlueJ in the start menu, but start the Select VM program instead (you

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information