38
Chapter 1 Practical Session 1 Questions and Exercises 1.1 1. Modify your “Hello World!” such that ‘Hello’ and ‘World!’ are written on different lines. 2. Modify your “Hello, World!" code to add a second line of text saying "How are you?". Expert: Further reading required 3. What use has returning a non-zero value from main? 4. Are other definitions of main allowed? 1

Practical Session 1 - Universiteit Twente · 2017-10-04 · Practical Session 2 Questions and Exercises 1.2 1.Removethecout linefromyour“Hello,World!” program. Initsplace, type

  • Upload
    others

  • View
    4

  • Download
    0

Embed Size (px)

Citation preview

Chapter 1

Practical Session 1

Questions and Exercises 1.1

1. Modify your “Hello World!” such that ‘Hello’ and ‘World!’ are writtenon different lines.

2. Modify your “Hello, World!" code to add a second line of text saying"How are you?".Expert: Further reading required

3. What use has returning a non-zero value from main?4. Are other definitions of main allowed?

1

Practical Session 2

Questions and Exercises 1.2

1. Remove the cout line from your “Hello, World!” program. In its place,type each one of the below commands in turn. For each command,try and work out whether or not the code will compile. Then run thecode and see if you were right, and if you can explain why!

(a)1 i n t a = 1 ;2 double a = 2 ;

(b)1 i n t a = 1 ;2 double A = 2 ;

(c)1 char c = X ;

(d)1 char ' c ' = X ;

(e)1 i n t i n t = 3 ;

(f)1 i n t Int = 3 ;

(g)1 i n t longer_name = 4 ;

2

CHAPTER 1. PRACTICAL SESSION 1 3

(h)1 i n t longer name = 4 ;

Questions and Exercises 1.3

1. Combining the skills you have learnt in the last two sections, write acode which defines an integer “i” with a value of 1 and outputs thisvalue to screen.

2. Change the value of your int to each of the below, and try to predictwhat the output will be:

(a) 3.0

(b) 3.1

(c) 3.9

(d) 3.99

(e) -3.8

(f) For the experts: ‘x’

3. What is the result of int a = 2147483647+1? Why?For experts: Further reading required

4. What is the range of an integer? (assume a width of 4 bytes)And of an unsigned integer?

5. What is the range of an double?6. What is the signedness of a char? Why?

Questions and Exercises 1.4

1. For each of the short code sections below, i) determine whether or notthey will compile, ii) predict their output and iii) write and run thecode to check if you were right.

(a)1 i n t i = 1 ;2 i n t i = 2 ;3 i n t i = 3 ;

(b)1 i = 4 ;2 i = 5 ;3 i = 6 ;

CHAPTER 1. PRACTICAL SESSION 1 4

(c)1 i n t i = 7 ;2 i = 8 ;3 i = 9 ;

(d)1 const i n t i = 10 ;2 i = 11 ;

(e)1 //Note : here `` i ' ' i s dec lared , but not ←↩

de f ined2 const i n t i ;3 i = 12 ;

Questions and Exercises 1.5

1. Copy and paste the code section below to form an executable C++program. For each step, determine what the values of a, b and c willbe.

1 i n t a = 1 ;2 i n t b = 2 ;3 double c = a + b ;4 a = b ;5 b = 4 ; // c a r e f u l !6 c = a + b ;7 c+= a ;8 b++;9 c = 5 / 2 ;

10 a = 5 / 2 ;11 c = b / a ;

Practical Session 3

Questions and Exercises 1.6

1. For each of the below, predict the end value of x and verify yourpredictions with an appropriate C++ program.

(a)1 double x = 2 .71828 ;2 x = ( in t ) x ;

(b)1 i n t x = 2 ;2 x /= 3 ;3 double x ;

(c)1 i n t x = 2 ;2 double x ;3 x /= 3 ;

(d)1 double x = −2.71828;2 x = ( in t ) x ;

(e)1 bool x = true ;2 x = ( in t ) x ;

(f)1 i n t x = 5 ;2 x = ( bool ) x ;

(g)1 i n t x = −5;

5

CHAPTER 1. PRACTICAL SESSION 1 6

2 x = ( bool ) x ;

(h)1 i n t j=3;2 i n t i = ( double ) j ;3 i=i /2 ;

2. Write a code which output the remainder of two integers after thefirst has been divided by the second. For example 22 reminder 3 is 1.

Questions and Exercises 1.7

1. For each of the below, predict whether the “test” will be true (1) orfalse (0). Write and run a simple program to let you see if you areright!

(a)1 bool test = (1 == 1) ;

(b)1 i n t a = 1 ;2 i n t b = 1 ;3 bool test = (a == b ) ;

(c)1 double a = 1 . 1 ;2 i n t b = 1 . 1 ;3 bool test = (a == b ) ;

(d)1 double a = 1 . 0 ;2 i n t b = 1 . 0 ;3 bool test = (a == b ) ;

(e)1 double a = 1 . 0 ;2 i n t b = 1 . 1 ;3 bool test = (a == b ) ;

(f)1 i n t a = 1 ;2 i n t b = 2 ;3 bool test = (a == b ) ;

CHAPTER 1. PRACTICAL SESSION 1 7

(g)1 i n t a = 1 ;2 i n t b = 2 ;3 bool test = (a != b ) ;

(h)1 i n t a = 1 ;2 i n t b = 2 ;3 bool test = (a >= b ) ;

(i)1 i n t a = 1 ;2 i n t b = 2 ;3 bool test = (a <= b ) ;

Practical Session 4

Questions and Exercises 1.8

1. Evaluate each of the below statements, deciding if they are true orfalse.

(a) (1 > 2) || (3 < 4)

(b) !(1 == 1)

(c) (1 > 2) && (3 < 4)

(d) !((2 > 1) && (1 > -10))

(e) !(1 > 2) && (1 > -10)

2. How many different combinations of logical operators and comparisonoperators can you think of which test if two values are equal?

Questions and Exercises 1.9

1. For each of the below, predict the end value of x and verify yourpredictions with an appropriate C++ program.

(a)1 bool x = (2 ∗ 2 < 8 / 4)

(b)1 i n t x = 2 ;2 i n t y = 3 ;3 i n t z = 4 ;4 x = y = z ;

(c)1 bool x = 1.0 + 2 .0 / 4 .0 == 5.0 / 2 .0 − 1 .0 && 2.0 ∗←↩

2 .0 / 1 .0 + 2 .0 < 8 .0 + 8 .0 / 1 6 . 0 ;

8

Practical Session 5

1 double n ;2 std : : cout << "Enter a number : " << std : : endl ;3 std : : cin >> n ;4 // check ing i f n i s negat ive5 i f (n < 0) {6 // i f n IS negat ive , l e t s the user know !7 std : : cout << "The number i s negat ive " << std : : endl ;8 }9 // i f n i s NOT negat ive , we sk ip to the

10 // e l s e statement . . .11 e l s e {12 // . . . and l e t the user know !13 std : : cout << "The number i s not negat ive " << std : : endl ;14 }

1 double n ;2 std : : cout << "Enter a number : " << std : : endl ;3 std : cin >> n ;4 // check ing i f n i s negat ive5 i f (n < 0) {6 // i f n IS negat ive , l e t s the user know !7 std : : cout << "The number i s negat ive " << std : : endl ;8 }9 // i f n i s NOT negat ive , we sk ip to the

10 // e l s e i f statement and check i f n i s11 // equal to zero . . .12 e l s e i f (n == 0) {13 // . . . and , i f so , l e t the user know !14 std : : cout << "The number i s 0" << std : : endl ;15 }16 // f i n a l l y , i f n i s not negat ive OR 0 ,17 //we know i t must be p o s i t i v e18 e l s e {19 std : : cout << "The number i s p o s i t i v e " << std : : endl ;20 }

Questions and Exercises 1.10

9

CHAPTER 1. PRACTICAL SESSION 1 10

1. Try running the example codes above with various values of n to geta feel for the use of the various if statements as well as the cinfunction.

2. Can you suggest a flaw in the if/else if/else version of the exampleprogram?

3. Drawing on your knowledge from previous chapters, write a programwhich can read in a number and tell the user whether or not thenumber provided is an integer.

4. Making a quiz: Write a program which asks the user a question andgives three possible answers, a, b and c. Read in the user’s answer,and tell them if they are right or wrong.

Questions and Exercises 1.11

1. Write a switch statement that prints “Hello” if the user inputs thecharacter ‘h’; “ world” if the user inputs the character ‘w’ and “Helloworld” for all other inputs.

Practical Session 6

Questions and Exercises 1.12

1. Why is it OK to use the same integer as a counter for two separatefor loops in the same program, but not if the two form a nested loop?

2. Update your quiz program from the previous section such that:

(a) The user gets a second try.

(b) Warns the user if an unlisted answer is given, before repeatingthe question.

3. Write a program to output all the possible ternary combinations ofnumbers between 1 and 4 in a single column.

4. Write a program that counts from 0 to 15 in binary, outputting eachvalue to screen alongside its decimal equivalent.

5. Write a simple program to compute the sum of the sequence 1, 1/2,1/4, 1/8, 1/16, 1/32 · · · and show that it gets closer and closer to 2;but never reaches it. Think carefully about integers and real numberfor this.

Questions and Exercises 1.13

1. Below is a badly written attempt at the odd-number-producing codeabove. Without running the code, predict what its output will be.Then, re-write the code so that it functions correctly.

1 i n t i = 1 ;2 whi le (i <= 10) {3 i f (i%2 == 0) {4 cont inue ;5 }6 cout << i << endl ;7 i++;8 }9 re turn 0 ;

11

CHAPTER 1. PRACTICAL SESSION 1 12

2. Using break statements, alter the nested for loop example fromthe previous section so that it outputs all number combinations from0 to 5, as opposed to 0 to 9. Note: this is, of course, not the bestway to do this, but is good practice for using the break statement!

Practical Session 7

Questions and Exercises 1.14

1. Our add function is written in such a way as to provide a good il-lustration of a function, as opposed to for efficiency! Re-write thefunction in the shortest form possible.

2. The code below, which is intended to take two arguments and subtractone from the other, contains a number of mistakes. See if you canfind and correct them all, then run the code to make sure you havebeen successful. The ability to debug a code is an important skill forany programmer!

1 #inc lude<iostream>2 us ing namespace std ;3 i n t main ( ) {4 double a ;5 double b ;6 cout << "Enter two numbers : "<< endl ;7 cin >> a >> b ;8 cout << a << " − " << b << " = "9 << in t subtract (b , a ) << endl ;

10 re turn 0 ;11 }12 i n t subtract ( double firstNumber , double secondNumber ) ;13 subtract ( double firstNumber , double secondNumber ) {14 answer = firstNumber−secondNumber ;15 re turn answer ;16 } ;

3. Write a function to multiply three numbers together. Write a mainfunction which calls this function to check that it works!

4. Write a function which takes two numbers as arguments and returnsthe 1st number to the power of the second number. What are thelimitations of your function?

Questions and Exercises 1.15

13

CHAPTER 1. PRACTICAL SESSION 1 14

1. A more useful header: Write, in separate files, functions similar tothe add function but which instead perform subtraction, multiplica-tion and division. Using a single header, include and use these newfunctions in a program.

Questions and Exercises 1.16

1. Is it possible to overload a function by changing the return type? Why/ why not?

2. Write a pair of functions, both named ‘add’, which find the sum of,respectively, integer and real numbers. From your main function,call the overloaded add function with both integer and non-integernumbers.

Practical Session 8

Questions and Exercises 1.17

1. Design a code which asks the user to enter an unknown number of realdoubles, computes the sum and standard deviation of these numbersand then outputs a report to the screen summarising what happened.Design this in a modular way with at least 4 separate functions.

2. Implement the code designed above.3. Add some breakpoints to the code and test out the different options

and tools included with the IDE you are using. Get used to thedifference between step and step into.

15

Practical Session 9

Questions and Exercises 1.181. Copy and paste the below code into your editor. Add comments to

the code explaining, using correct C++ terminology, what each lineof the code does. Then, predict what the output of the code will beat each stage, before executing the code to see if you are right!

1 #inc lude <iostream>2

3 i n t main ( )4 {5 i n t i ;6 i n t ∗ p_i = &i ;7 i n t ∗∗ p_p_i = (&p_i ) ;8 i = 0 ;9 std : : cout << " i = " << i << std : : endl ;

10 ∗p_i = 1 ;11 std : : cout << " i = " << i << std : : endl ;12 ∗∗p_p_i = 2 ;13 std : : cout << " i = " << i << std : : endl ;14 i n t j = 7 ;15 std : : cout << " i = " << i << std : : endl ;16 std : : cout << " j = " << j << std : : endl ;17 p_i = &j ;18 ∗p_i = 77 ;19 std : : cout << " i = " << i << std : : endl ;20 std : : cout << " j = " << j << std : : endl ;21 ∗p_p_i = &i ;22 ∗p_i = 22 ;23 std : : cout << " i = " << i << std : : endl ;24 std : : cout << " j = " << j << std : : endl ;25 ∗∗p_p_i = 222 ;26 std : : cout << " i = " << i << std : : endl ;27 std : : cout << " j = " << j << std : : endl ;28 ∗p_i = (∗ p_i ) / 111 ;29 std : : cout << " d iv i d i ng ∗p_i by 111 : " << endl ;30 std : : cout << " i = " << i << std : : endl ;31 std : : cout << " j = " << j << std : : endl ;32 re turn 0 ;33 }

16

CHAPTER 1. PRACTICAL SESSION 1 17

2. Explain the different between the last two lines of the following pro-gram

1 i n t i=3;2 i n t j=5;3 i n t ∗ pi=&i ;4 i n t ∗ pj=&j ;5 ∗pj=∗pi ;6 pj=pi ;

Questions and Exercises 1.19

1. Run this program and from the output explain the difference betweenthe functions add and add2.

Practical Session 10

Questions and Exercises 1.20

1. Write an array to store the squares of all the numbers between 1 and20 and another to store the corresponding cubes. Output the data incolumns alongside their root.

2. Harder: Write a program to find all the prime numbers between 1and 100 as efficiently as possible (Note: this question was once usedas part of the interview process to become a programmer for Google– so don’t be ashamed if you need a few hints!)

Questions and Exercises 1.21

1. Define a zero-size vector. Based on user input, resize this vector toaccommodate a given number of values. Read in values from the con-sole to fill your vector, and then calculate the average of the numbersgiven.

2. Try writing a similar program using arrays – a nice example of howmuch more efficient vectors can be!

Questions and Exercises 1.22

1. Write a program which uses the ‘brute force’ method to guess a user-input password comprising three letters. Include a function thatrecords the number of ‘attempts’ your code makes in order to breakthe password.

2. Extend your code to work with 6 letter passwords. Note the differencein the average number of tries it takes for your code to break thepassword – this is (one reason) why longer passwords are safer!

Questions and Exercises 1.23

1. C++ centipede: Write a program containing three maps – one whichtakes a string as a key value and a float as a mapped value, thenext a float as a key value and a char as a mapped value, and thethird a char as a key value and a string as a mapped value. Define

18

CHAPTER 1. PRACTICAL SESSION 1 19

elements such that the mapped value of one map may be used asthe key value of the next and so on. Try various combinations ofyour different maps and output the results to screen to check thateverything has been defined correctly, for example:

1 std : : cout << map3 [ map2 [ map1 [ " example" ] ] ] << std : : endl ;

Questions and Exercises 1.24

1. Without running the below code, try and predict its output at eachpoint, and explain why you would expect this output. Comment thecode accordingly. Then, run the code to see if you were correct!

1 #inc lude <vector>2 #inc lude <iostream>3 i n t main ( ) {4 std : : vector<int> v = {0 ,1 , 2 , 3 , 4 , 5} ;5

6 f o r ( i n t i : v ) {7 std : : cout << i << ' \ t ' ;8 }9 std : : cout << std : : endl ;

10

11 f o r ( i n t i : v ) {12 i++;13 std : : cout << i << ' \ t ' ;14 }15 std : : cout << std : : endl ;16

17 f o r ( i n t i : v ) {18 i++;19 }20

21 f o r ( i n t i : v ) {22 std : : cout << i << ' \ t ' ;23 }24 std : : cout << std : : endl ;25

26 f o r ( i n t i : v ) {27 std : : cout << i << ' \ t ' ;28 }29 std : : cout << std : : endl ;30

31 f o r ( i n t i : v ) {32 std : : cout << v [ i ] << ' \ t ' ;33 }34 std : : cout << std : : endl ;35

36 re turn 0 ;37 }

CHAPTER 1. PRACTICAL SESSION 1 20

Questions and Exercises 1.25

1. Without running the below code, comment each line and predict whatthe relevant outputs will be at each stage. Then, run the code to seeif you were right!

1 #inc lude<iostream>2 #inc lude<vector>3 i n t main ( ) {4 std : : vector<int> v = {0 ,1 , 2 , 3 , 4 , 5} ;5 std : : vector<int >: : iterator it ;6 it = v . begin ( ) ;7 whi le ( it != v . end ( ) ) {8 std : : cout << ∗it << " " << ' \ t ' ;9 ++it ;

10 }11

12 std : : cout << std : : endl ;13 it = v . begin ( ) ;14 whi le ( it != v . end ( ) ) {15 it++;16 std : : cout << ∗it << " " << ' \ t ' ;17 ++it ;18 }19 std : : cout << std : : endl ;20

21 it = v . begin ( ) ;22 whi le ( it != v . end ( ) ) {23 (∗ it )++;24 std : : cout << ∗it << " " << ' \ t ' ;25 ++it ;26 }27 std : : cout << std : : endl ;28 }

2. Using iterators, add to the above a section of code which outputs theelements of the same vector array in reverse order.

3. Re-write both the vector and general sum functions defined in sectionthe main course book to give the product of all the numbers in a givencontainer. Call both functions for i) an std::vector of your choosingand ii) a similar std::array.

Practical Session 11

Questions and Exercises 1.26

1. Write a program which outputs, to file, the numbers from one to tenin text form, each separated by a tab (i.e. one two three...). Readthe numbers back in, and then output them to screen in the oppositeorder.Expert: Further reading required

2. What is the difference between cout, cerr and clog?3. What is the difference using std::endl and \n?4. My program crashed just after having written something to a file, but

when I check the file it is empty. Why is that?

Questions and Exercises 1.27

1. Using stringstreams, manipulate the simple string defined below:

1 std : : string s = "12345" ;

to give a new string:

1 std : : string S = "2 4 6 8 10" ;

Questions and Exercises 1.28

1. Consider the following code and try to understand which block willsuccessfully read to the end of a filestream ‘fin’. What would thealternatives give?

1

2

3 std : : string s ;4

5 whi le ( ! fin . eof ( ) ) {

21

CHAPTER 1. PRACTICAL SESSION 1 22

6 cin >> s ;7 . . .8 }9

10 whi le ( ( fin >> s ) . good ( ) ) {11 . . .12 }13

14

15 whi le ( fin >> s ) {16 . . .17 }

2. Is !a.bad() exactly equivalent to a.good()?3. Copy and paste the code below into a .cpp file. For each point in the

file, predict what the output of the program will be, before runningthe program to check your answers.

1 #inc lude <iostream>2 //remember to in c lude t h i s header i f you want to3 // change the format o f output4 #inc lude<iomanip>5

6 i n t main ( ) {7 // d e f i n i n g a r e l a t i v e l y long , non−i n t e g e r ' double ' , n8 double n = 1.23456789 ;9 // outputt ing n to s c r e en − note the d e f au l t p r e c i s i o n

10 // to which the number i s dec l a r ed !11 std : : cout << n << std : : endl ;12

13 i n t prec = 7 ;14 std : : cout << std : : setprecision ( prec ) << n << std : : endl ;15

16 prec = 9 ;17 std : : cout << std : : setprecision ( prec ) ;18 std : : cout << n << std : : endl ;19 std : : cout << n << std : : endl ;20

21 double nn = 10.987654321 ;22 std : : cout << nn << std : : endl ;23 i n t width = 12 ;24 prec = 3 ;25 cout << std : : setprecision ( prec )26 << std : : setw ( width ) << n << std : : endl ;27 width = 20 ;28

29 std : : cout << std : : setw ( width ) ;30 std : : cout << n << std : : endl ;31 std : : cout << n << std : : endl ;32

33 char c = ' ∗ ' ;34 std : : cout << std : : setw (10) ;

CHAPTER 1. PRACTICAL SESSION 1 23

35 std : : cout << std : : setfill (c ) ;36 std : : cout << n << std : : endl ;37

38 c = ' | ' ;39 std : : cout << std : : setw (10) ;40 std : : cout << std : : setfill (c ) ;41 std : : cout << n << std : : endl ;42

43 c = 'A ' ;44 std : : cout << std : : setw (10) ;45 std : : cout << std : : setfill (c ) ;46 std : : cout << n << std : : endl ;47

48 re turn 0 ;49 }

Practical Session 12

Questions and Exercises 1.29

1. Add a function to the Rectangle class which calculates and returnsits perimeter. Think about what sanity checks should be performed.

2. Define a class called ‘Person’ with two private, string-type variables– firstName and secondName. Define a function which allows theaforementioned variables to be assigned values, and a function whichreturns the full name of our ‘Person’.

24

Practical Session 13

Questions and Exercises 1.30

1. Create a child of your ‘Person’ class which, in addition to a name,can also store an occupation.

25

Practical Session 14

Questions and Exercises 1.31

The code below shows an example of a code which uses ‘enum’ very badly! Todemonstrate your understanding of the enum keyword, and how it can andcan’t be used:

1. Identify which variables in the code will cause compilation errors.Temporarily change the names of these variables to see if you werecorrect. This exercise shows the potential pitfalls complexities of us-ing the conventional (pre-C++11) enum types.

2. Reinstate the original variable names and re-write the code usingstrongly typed enums.

1 #inc lude<iostream>2 enum NightOut_t {3 pub ,4 disco ,5 bar ,6 coffeeHouse ,7 club ,8 none9 } ;

10 enum Music_t {11 dubstep ,12 rock ,13 pop ,14 drumAndBase ,15 disco ,16 none17 } ;18 enum Weapon_t {19 club ,20 knife ,21 gun ,22 rock ,23 bat ,24 none25 } ;26 i n t main ( ) {

26

CHAPTER 1. PRACTICAL SESSION 1 27

27 NightOut_t place = club ;28 Music_t music = drumAndBase ;29 Weapon_t weapon = knife ;30 i f ( weapon == none ) {31 i f ( ( place != disco ) && ( music != pop ) ) {32 std : : cout << "Sounds good . " << std : : endl ;33 }34 e l s e {35 std : : cout << "No thanks . " << std : : cout ;36 }37 }38 e l s e {39 std : : cout << "So , we ' re going out in Birmingham?" ←↩

<< std : : endl ;40 }41 re turn 0 ;42 }

Practical Session 15

Questions and Exercises 1.32

1. Write a templated function which can add string, int, doubles to-gether.

2. Write a stack which can store any type of elements. A stack is a lastin first out structure. Define the methods add and remove for thisstructure

3. Output of following program?

1 #inc lude <iostream>2 us ing namespace std ;3

4 template <c l a s s T>5 c l a s s Test6 {7 pr i va t e :8 T val ;9 pub l i c :

10 s t a t i c i n t count ;11 Test ( ) { count++; }12 } ;13

14 template<c l a s s T>15 i n t Test<T>:: count = 0 ;16

17 i n t main ( )18 {19 Test<int> a ;20 Test<int> b ;21 Test<double> c ;22 cout << Test<int >: : count << endl ;23 cout << Test<double >: : count << endl ;24 re turn 0 ;25 }

4. Can an unsigned int be used as a template argument? A float?5. Can a variable be used in a template argument? Why (not)?

28

CHAPTER 1. PRACTICAL SESSION 1 29

Questions and Exercises 1.33

1. For the code below:

i Comment the code to explain what is happening at each step.ii Determine whether each assignment of a function pointer wouldsuccessfully compile.

iii Determine what will be output to the console for each ‘std::cout’.

1 #inc lude<iostream>2 i n t giveMeFive ( ) {3 re turn 5 ;4 }5 i n t giveMeTen ( ) {6 re turn 10 ;7 }8 i n t timesTwo ( i n t x ) {9 re turn (x ∗ 2) ;

10 }11 i n t plusTwo ( i n t x ) {12 re turn (x + 2) ;13 }14 i n t main ( ) {15

16 i n t (∗ functionPointer1 ) ( ) = giveMeFive ;17 std : : cout << (∗ functionPointer1 ) ( ) << std : : endl ;18

19 functionPointer1 = giveMeTen ;20 std : : cout << (∗ functionPointer1 ) ( ) << std : : endl ;21 std : : cout << functionPointer1 << std : : endl ;22

23 i n t (∗ functionPointer2 ) ( i n t ) = timesTwo ;24 std : : cout << functionPointer2 (2 ) << std : : endl ;25 std : : cout << (∗ functionPointer2 ) (2 ) << std : : endl ;26 std : : cout << functionPointer2 ( (∗ functionPointer2 ) (2 ) ) ←↩

<< std : : endl ;27

28 functionPointer2 = plusTwo ;29 std : : cout << functionPointer2 (2 ) << std : : endl ;30 std : : cout << functionPointer2 ( (∗ functionPointer2 ) (2 ) ) ←↩

<< std : : endl ;31

32 functionPointer1 = timesTwo ;33 std : : cout << functionPointer1 (2 ) << std : : endl ;34 std : : cout << functionPointer2 (2 ) << std : : endl ;35

36 }

2. Re-write the above example using exclusively std::functions.

Questions and Exercises 1.34

CHAPTER 1. PRACTICAL SESSION 1 30

1. Spot the mistake: the code below, which you have already seen in thepreceding chapter, contains a deliberate mistake, the kind of typograph-ical mistake one can easily make when coding! What would the outputof this code be, and why?

1 #inc lude<iostream>2 c l a s s UselessClass {3 pub l i c :4 bool variable = true ;5 void thisFunc ( ) {6 [ t h i s ] ( ) {7 std : : cout << variable << std : : endl ;8 } ( ) ;9 }

10 void thatFunc ( bool cariable ) {11 [= ] ( ) {12 std : : cout << variable << std : : endl ;13 } ( ) ;14 }15 } ;16 i n t main ( ) {17 UselessClass uselessInstance ;18 uselessInstance . thisFunc ( ) ;19 uselessInstance . thatFunc ( f a l s e ) ;20 re turn 0 ;21 }

2. As you have probably already worked out, one of the (many) values oflambdas is that they do not need to be declared and named like ‘normal’functions. The simple code below uses the very useful ‘for_each’1

function to print a tab-separated list of all the elements in a vector.However, this code can be re-written much more concisely and effi-ciently using a lambda function. In fact, lines 6, 7, 8 and 15 can allbe combined into a single line of code! Give it a go!

1 #inc lude <iostream>2 // f o r std : : for_each3 #inc lude <algorithm>4 #inc lude <vector>5 // Def in ing a func t i on to p r i n t tab−separated l i s t s6 void tabSepPrint ( i n t i ) {7 std : : cout << i << ' \ t ' ;8 }9 i n t main ( ) {

10 // d e c l a r i n g an a rb i t r a r y vec to r to p r i n t

1The for each function is an easy way to apply a function to multiple elements of agiven container. It takes three arguments: the first and last elements to which we want toapply the function, and the function we want to apply. Each of the elements between thechosen start- and end-point are then passed as the argument of the function provided.

CHAPTER 1. PRACTICAL SESSION 1 31

11 std : : vector <int> v = {1 ,2 , 3 , 4 , 5} ;12 // us ing the for_each func t i on to pass a l l e lements13 // o f v ( i . e . s t a r t i n g at v . begin ( ) and ending14 // at v . end ( ) ) in turn to the " tabSepPrint " func t i on15 for_each (v . begin ( ) ,v . end ( ) , tabSepPrint ) ;16 re turn 0 ;17 }

3. Some practice with ‘this’: In this exercise, we are going to use the‘this’ keyword to create the template for a ‘Top Trumps’-like game.The game should be able to compare the attributes of different objectsof the same class and decide which one ‘wins’. Some example code isgiven below to get you started, but you do not have to follow the samestructure; this example uses cars, but you can try with anything youwant, and add as many features to the game as you like!

1 #inc lude <iostream>2 #inc lude <s t r i ng>3 c l a s s Car {4 pub l i c :5 // d e f i n i n g some va r i a b l e s to r ep r e s en t c h a r a c t e r i s t i c s6 // that may be important in a car !7 double topSpeed ;8 double bhp ;9 double zeroToSixtyTime ;

10 // Just some idea s −11 //you could add as many more as you l i k e !12 //The name f o r each in s t ance − i . e . your model o f car !13 std : : string model ;14 // c r e a t i n g a con s t ruc to r which a l l ows us to15 // e a s i l y and qu i ck ly ente r the d e t a i l s o f our ca r s !16 Car ( double speed , double acc , std : : string name ) {17 topSpeed = speed ;18 zeroToSixtyTime = acceleration ;19 model = name ;20 }21 //This func t i on should determine which car has22 // the h igher top speed and de c l a r e an appropr ia te23 // "winner " .24 void isFaster ( Car car ) {25 // [YOUR CODE HERE! ]26 }27 // . . .28 // . . .29 } ;30

31 i n t main ( ) {32 //Creat ing some "Car"−type ob j e c t s .33 Car porsche ( 3 5 1 . 0 , 2 . 2 , "Porsche 918" ) ;34 Car bugatti ( 4 0 8 . 8 4 , 2 . 5 , "Bugatt i Veyron" ) ;35 // c a l l i n g the " i sFa s t e r " func t i on

CHAPTER 1. PRACTICAL SESSION 1 32

36 bugatti . isFaster ( porsche ) ;37 // i f your func t i on i s de f ined co r r e c t l y ,38 //both combinat ions should39 // g ive the same r e s u l t !40 porsche . isFaster ( bugatti ) ;41 re turn 0 ;42 }

Practical Session 16

Exercise 1: Computing prime numbers

Background

A prime number is defined as ‘a positive integer p > 1 that has no positiveinteger divisors other than 1 and p itself.’

The brute force, but simple, method to decide if p is prime is to test if(n mod q 6= 0) for all numbers 1 < q < p.

A quicker way to find primes is to only perform the division test for primenumbers less than p.

For example, to test the number 11 you only need to check if (11 mod2), (11 mod 3), (11 mod 5) and (11 mod 7) are zero.

Questions

1. Write a C++ program to compute the first N prime numbers, whereN is given by the user. Use dynamic arrays to store the primes anduse this information in the mod test.

2. Write to the screen a list of the first 10000 primes in the format below;where p(n) is the nth prime number. Report only the last five lines.Comment on the behaviour of the ratio n ∗ ln(p(n))/p(n) as n getslarge.

n : p(n) : n*ln( p(n) )/p(n)1 : 2 : 0.346573590279972 : 3 : 0.732408192445413 : 5 : 0.96566274746046

3. Based on question ??, give an estimate of the 106-th prime number.

4. Instead of writing to the screen, write to a file (on disk) a list containingjust the prime numbers. Print eight numbers per line, such that allnumbers have the same space, i.e., the file should start like:

2 3 5 7 11 ...

33

CHAPTER 1. PRACTICAL SESSION 1 34

*5. Time your code for N = 103, 104, 105 and 106. Make a log-log plot ofrun-time against N for both codes. What can we say from the log-log plot? Do this analysis for brute force and suggested speed up andcomment on the results.

**6. More efficient ways of computing prime numbers exist. Find and imple-ment one and report the analysis of part 5 for this algorithm. Commenton the results; think of computing very large prime numbers.

Exercise 2: Reverse Polish Notation

Background

During the 1950’s and 1960’s, computer scientists were looking for waysto program early electronic computers in an easier language than machinecode (C and C++ were not yet developed). In the process, the ReversePolish Notation (RPN) was invented, and reinvented, because it is bothrelatively easy to implement and convenient to work with. We normallyuse infixnotation for writing down calculations: the operator is positionedbetween the two operands, as in

10 + 2

Reverse Polish Notation uses the postfix-notation, writing the same equationas

10 2 +

The advantage of this system is that there is no need for an order to bedefined for operations; while the equation

(10 + 3) * 7

needs brackets in the infix-notation, the same equation reduces to

10 3 + 7 *

in RPN.

Questions

1. Read a string input from the terminal (which is assumed to be in RPN).Interpret the string correctly and output the result to the screen.Your Reverse Polish Notation calculator should be able to do add,subtract, multiply and divide integers.

CHAPTER 1. PRACTICAL SESSION 1 35

2. Extend your code such that it reads the input line-by-line from a file.Each newline marks the end of each calculation. Write out the resultof each line of the calculation and your program should abort when itdetects an ‘end of file’condition.

*3. Add in error checking to confirm the entered string can be interpretedas RPN string.

*4. Add in support for the power operator using the symbol ^.

**5. Extend your code so that it can read input strings in normal bracketsnotation. It should understand the BODMAS rules2.

Exercise 3: TomTom

Background

As the name suggests the aim of this problem is given a set of roads con-necting points (cities in our example for simplicity) find the shortest routebetween any given two cities. Hence the TomTom problem.

Questions

Assume a network of L roads connection N cities; each road connects twoof these cities. You are given a text file distances.txt that contains adouble array of the length of roads connecting the two cities. The ith rowjth column gives the travel time from the ith to the jth city. If there is nodirect connection between two cities the array contains a ridiculously largenumber, 123456789; on the diagonal the number 0 is placed. For example ifwe have the following matrix

0 123456789 100123456789 0 400

100 400 0

This implies the first city has no connection to the second but is a distanceof 100 from the third. Whereas the third city is connection to the secondand is a distance of 400 away.

You are given several different sized sets of cities for each:

1. For each set of cities compute the shortest distance between every setof cities and write this information to disk with the route as a list of

2BODMAS stands for Brackets, Order, Divide, Multiply, Add, Subtract and remindsyou in what sequence to carry out the operations of arithmetic. As you can see there arethree levels to consider.

CHAPTER 1. PRACTICAL SESSION 1 36

cities. Use the format cities, route, distance i.e. for our example abovethe answer would be

1− 2 1− 3− 2 5001− 3 1− 3 1002− 3 2− 3 400

Use any algorithm you see fit.

CHAPTER 1. PRACTICAL SESSION 1 37

*2. A famous Dutch mathematician and computer scientist (Edsger Di-jkstra) discovered an efficient algorithm for finding the shortest routebetween two points. Even though it was first published in 1959, itremains the fastest algorithm to actually give the shortest route.

Dijkstra’s algorithmFirst, to initialise:

(a) Set visited for all cities to false

(b) Set distance for all cities to infinite

(c) Set distance for the first city to 0

Next, to find the shortest route:

(a) Find the city with the lowest distance which has not been visitedyet.

(b) Mark the city as ’visited’

(c) If the city is the endpoint, stop.

(d) Update the connected cities with the distance found

Construct the actual route

(a) Start at the last city

(b) Look which connected cities has the lowest distance

(c) Add that one to the route

(d) Consider the city just added to be the last one

(e) Is the last city the begin city? Done!

Implement Dijkstra’s algorithm.

Hint: Write a class ‘City’, which stores the best distance so far, theposition, the name and the other cities which it connects to.

**3. The real TomTom problem. The real Dutch road network has 825000road junctions just counting the motorway and the provincial roads:

(a) Use some means to estimate how long your code from both part 1and part 2 would take to compute a route between two randomlychosen junctions on the Dutch principle road network.

(b) Your TomTom has a very low powered processor and has to givea route within 15 seconds. It is no use if it take two hours tocompute the route. Think carefully about what it must do toachieve this (hint, TomTom and Garmin will not always give thesame route for the same input). Implement an algorithm that

CHAPTER 1. PRACTICAL SESSION 1 38

can deal with the bonus 1 million city file in under 30 second onyour laptop (note, only compute one example route). This is stilleasier than what TomTom must do.

(c) You are now given an easier problem. For the same set of citiesyou can pre-compute what every data your want up-to a limit of1 Megabyte. Precompute some data and use this precomputeddata to improve your algorithm from part (b).