Workbook-CS 2202 Foundations of Computer Science Wk 1-6

65
1 CS 2202/7202 Foundations of Computer Science Programming Concepts Workbook weeks 1-6 Programming Computers How do computers represent information internally? What are: 1. Machine Code 2. Assembly Code 3. High Level Languages Why are there so many different High Level Languages? What characterizes imperative programming languages?

description

foundatiins of computer science

Transcript of Workbook-CS 2202 Foundations of Computer Science Wk 1-6

Page 1: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  1  

   

CS 2202/7202 Foundations of Computer Science

Programming Concepts Workbook weeks 1-6

Programming Computers How do computers represent information internally? What are:

1. Machine Code

2. Assembly Code

3. High Level Languages

Why are there so many different High Level Languages? What characterizes imperative programming languages?

Page 2: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  2  

Identify what each of the following imperative programming constructs is used for and give an example:

1. Literal:

2. Constant:

3. Variable:

4. Expression:

5. Selection/Conditionals

6. Iteration/Loops

7. Functions

Page 3: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  3  

Class Example 1: Using the imperative programming building blocks, write an algorithm (set of steps) that will allow you to get a set of numbers from a partner, calculate the average (mean) of that set of numbers and tell your partner the answer. Keep in mind the following:

1. you must ask your partner for the numbers 2. you may not remember anything unless you write it down 3. you may not give any answer that is not written down 4. anything you write down must be given a name that describes what it is 5. if you change the value of something you have written down, write

down how and when you change it - for example if I want to keep track of the number of 2's my partner gives me then I may

1. choose to remember a count called count_2 which starts at 0. 2. ask for a number, 3. if number equals 2 then I add 1 to count_2.

Algorithm:

Page 4: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  4  

Workshop 1 – small group exercise

Using the fundamental constructs of imperative programs, write algorithms to do the following tasks: 1) calculate the area of a circle 2) convert Celsius to Fahrenheit 3) determine a person's age based on their year of birth. Compare your group’s algorithm with another group.

Page 5: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  5  

Lab 1 - notes (Unix & Emacs commands) Working with Linux (Unix)

If the computer is currently running Windows, reboot the computer. When the computer starts to reboot you will have the option to select Linux. Use the arrow keys to select Linux and press enter. The computer will then boot into Linux. All of the computing science suites are "dual boot". You can boot them into either Windows or Linux.

Once the Linux screen appears, log in using your student ID and password.

Starting a Terminal

Select the terminal application from the Applications - Accessories pull down menu. This starts the terminal application (you will do a lot of work using the terminal).

After a short while, a terminal window will appear on screen. A small amount of text appears ending with a line that finishes with a % character. This last line is called the prompt. When the prompt appears you can type commands.

Setting up a working directory

While your mouse is over the terminal window, type in the following commands (note that you need to press the return key on your keyboard after each command).

ls

A small list of filenames will appear on screen. These are the names of files and directories. Files are places where you store information. Directories are places that are used to store files and other directories. You will need to create some new files in this workshop. It is sensible to create a new directory to put these files in. First you need to make a directory to put all of your programming work into:

mkdir FCS

Type in ls again. You should see the name FCS appear in the list. FCS is a new directory where you can put files and other directories. Now type:

cd FCS

This command changes your working directory to FCS. Your working directory is the place where you are right now. If you type ls now you will see no names listed. This is because we have not yet put any files or directories into the cs1a directory. Create another directory, just for this workshop, called workshop1:

mkdir Lab1

Type ls to confirm your handiwork and then type:

Page 6: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  6  

cd Lab1

to change your working directory to Lab1. This directory is where you will put all of your files for this Lab.

Find out if Linux is 'case sensitive'. ie can you instead type lab1 instead of Lab1 to mean the same directory?

There are two special aliases you can use when working with directories: '..' is the parent directory and '.' is the current directory.

Type:

cd ..

Now type ls to see what directory you are now in. Change back to the Lab1 directory. What directory will you be in if you now type cd ../..

Verify your expectation by typing the command and using ls to check. When you have finished, change back to the Lab1 directory.

Find a 'Unix Cheat Sheet' online. What are the commands to remove a file or directory, move a file or directory, copy a file or directory, find out which directory you are currently in. Write down your key unix commands in your course workbook.

Editing a New File To define a program you need to create a source file. A source file is just a file containing the text of a program written in a particular programming language. We will create source files using a text editor called Emacs.  

Start Emacs. You can find it in the Applications directory. You can also start it from the terminal by typing:

emacs

A window will appear on screen and the menu bar at the top of the screen will now have the word Emacs in the left-hand corner. To edit a new file hold down the control-key while typing ’x’ and then ’f’. Now look at the bottom of the emacs window and type the following: introprog/Lab1/Image.html

Emacs may try to help you as you type in this name (which is OK). This file does not yet exist so the emacs window will be blank.

Before going further, find a 'cheat sheet' for emacs online.

emacs is a general editor as well as a source code editor. Try out the commands on your 'cheat sheet' to get familiar with emacs. Write down some key emacs commands in your course workbook.

Logging out

You must log out at the end of your practical. Otherwise, someone else can use your account and pretend to be you. Never leave your terminal without first properly logging out.

Page 7: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  7  

Notes

Page 8: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  8  

Lab 2 – SVN tutorial

Using Subversion for practicals You will need to keep your practical files in SVN. If you aren't familiar with SVN, the following instructions (from the PT web page) will help you get started

In the instructions below, you should replace a1111111 with your own student id.

Step 0: Getting to know Subversion

Subversion, also known as svn, is a powerful version control system to help maintain a coherent copy of a project that can be worked on from multiple locations. You can work on the code from home and the lab and subversion will help you keep you different copies up to date.

We will use Subversion as the handin mechanism throughout this course. If you are not familiar with SVN you should read over the <a href="http:>svn documentation</a href="http:>

Step 1: Creating the assignment directory in your svn repository

To copy all of the files for the practical from a directory into your repository. Open a terminal window on your machine, and type the following command:

svn import -m "practical name" directory https://version-control.adelaide.edu.au/svn/a1111111/handin-key

replacing practical name with a name for your practical, directory with the directory where your initial files have been saved and handin-key with the svn directory specified for the practical (found on the practical sheet).

If you do not have any starting files for the practical you can create an empty svn directory with the command:

svn mkdir -m "practical name" https://version-control.adelaide.edu.au/svn/a1111111/handin-key

These will create a directory with the name of the handin key in an svn repository that we have set up for you. Your svn repository is called https://version-control.adelaide.edu.au/svn/a1111111/ where a1111111 is your student id.

Exercise 1 - make a directory 2014/s1/FCS/Test in your svn repository. You will either have to make the directories one at a time (2014, then 2014/t1, then 2014/t1/FCSA...), or there is an option you can give to tell svn to make all of the directories if they don't already exist.

Type svn help mkdir and see if you can find the option to make all of the directories.

Step 2: Checking out a working version of your assignment.

In  your  home  account,  change  to  a  directory  above  the  one  where  you  want  to  place  your  working  files  for  this  assignment.  Then  type:    

Page 9: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  9  

svn checkout https://version-control.adelaide.edu.au/svn/a1111111/handin-key new-directory

A new directory called new-directory will now be created in your current working directory. The contents of this now become a working-copy of the files for this assignment. Note that this working copy will look the same as your original copy but, the directory contains hidden sub-directories needed by svn to operate correctly. You can and should (to avoid confusion) delete your original copy.

Note that you can have more than one working copy of a project. For example you could have one working copy at home and one at university and you can, very conveniently, use svn to help keep them in sync. See the <a href="http://www.cs.adelaide.edu.au/docs/svn-instr.pdf">svn documentation for details on how this can be done. However, for now, we will assume you have just the one working copy. </a >

<a href="http://www.cs.adelaide.edu.au/docs/svn-instr.pdf">Exercise 2: checkout your </a >2014/s1/FCS/Test svn directory

Step 3: Adding files and Committing changes

When you want to add your a new file to your repository, use the commands

svn add Myfile.cpp svn add AnotherFile.cpp svn commit -m "initial commit"

These commands tell Subversion to keep track of these file in your working copy (Subversion only keeps track of the files you tell it to) and then commits (copies) these files to your repository. You should get a few messages describing what the add and commit commands are doing. By the end of these commands a copy of MyFile.cpp and AnotherFile.cpp will now be part of your svn repository. Any files in the directory when you do svn import (as in step 1) will already be added to your repository.

As you work on your assignment, you should commit your changes early and often. That is, you should regularly copy new versions of your files to your repository. To commit your files to the repository you change to the directory containing the working copy of your files and type:

svn commit -m "meaningful message about what I just changed."

note, that the message after the -m in the line above can be anything. However, it should be relevant to the state of the project at this moment. Also note that running commit is the only way your repository will get to know about the latest versions of your files. When we mark your submission we will look at what has been committed to your repository and, also, how often and what times you commited to your repository.

Exercise 3: create a new file using emacs called test.txt Write 'testing' in the file and save.

Look at your svn repository in the web browser (see step 1 for the http address of your svn repository). Is the test.txt file there?

Add the test.txt file to your repository. Again look at your svn repository (reload the http address). Is the test.txt file there?

Commit the changes to your repository. Check your repository again. Is the test.txt file there now?

Step 4: Automated Checking

Page 10: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  10  

Note: The submission and automarking system is a web-submission system (ensure that you use the web-submission system and not the older command line automark tool - only web-submitted assignments will receive marks and avoid an IF).

The next step is to submit your assignment. Note that some assignments might not include automated marking (you may just be submitting) but some do.

By now you have written your assignment and committed your changed files to the repository along the way. Now you can submit and automatically mark your assignment by following <a href="https:> this link to the web-submission system. Select your year, semester/term, course and assignment. For this exercise, choose the SVN-test assignment. Choose the make a new submission for this assignment link and follow the prompts. The output from automatic marking (if any) should appear in a panel at the bottom of the page. Click on the relevant links to refresh this panel. </a href="https:>

Notes

Page 11: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  11  

C ++ fundamentals (C++ language tutorial – structure of a program) The basic C++ program – main function (write the main function here and note what each line does note how we get user input and write user output from the console in C++)

Page 12: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  12  

Class Example 2 - editing, compiling and adding our code to our svn repository clang and gcc are the compilers available on the lab computers to build our programs. The basic command to compile C++ programs using these compilers are: clang <MyProgramName.cpp> -o <NameForTheExecutable> g++ <MyProgramName.cpp> -o <NameForTheExecutable> Imperative constructs in C++ (C++ language tutorial: Basics of C++: variables and types, constants, operators, basic input/output Program structure: Statements and flow control) Give an example of each of the following in C++

1. Literal (give an example of each of the following C++ types): char: int: long: unsigned int: float: double: bool: string (note must include string library - #include<string>):

Page 13: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  13  

2. Constant:

3. Variable:

4. Expression: (note down the precedence of operators)

5. Selection/Conditionals (Note down DeMorgan’s Laws)

6. Iteration/Loops

7. Functions (we’ll look at these after the above)

Workshop 2 – small group exercise

1)  Identify  the  fundamental  constructs  and  types  needed  to  code  class  example  1.                

Page 14: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  14  

           2)  while(x  !=  "some  value"  ||  y  !=  "some  value"  ||  z  !=  "some  value")          {                code          };    The  aim  of  this  loop  is  to  execute  the  code  until  the  string  x,  y  or  z  does  not  equal  "some  value".  Does  this  code  do  what  is  expected?  What  will  happen  when  this  loop  is  entered?    Rewrite  the  code  to  behave  as  expected.                  3)  Using  De  Morgan's  Law  determine  if  the  expressions  below  are  equivalent    !(  x=="someValue"  ||  y=="someValue"  ||  z=="someValue")      x!="someValue"  &&  y!="someValue"  &&  z!="someValue"      4)  Evaluate  each  of  the  following  expressions:        a)  result  =  5  +  6  *  4/2;        b)  result  =  5  +  (6  *  4)/2;        c)  result  =  (5  +  6)  *  4/2;        d)  result  =  TRUE  ||  FALSE  &&  TRUE;        e)  result  =  TRUE  &&  FALSE  ||  TRUE;        f)  result  =  TRUE  &&  (FALSE  ||  TRUE);        g)  result  =  5  <=  3  &&  6  >  4;        h)  result  =  !5  <=  3  &&  6  >  4  

Page 15: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  15  

     i)  result  =  5;              result++;        5)  Write  C++  expressions  for  the  following.  Use  parenthesis  where  appropriate  to  clearly  indicate  the  order  of  evaluation.        a)  test  if  x  is  less  than  5  or  y  equals  7          b)  increment  x  and  test  if  greater  than  max          c)  test  if  x  is  not  divisible  by  2  (hint  consider  how  you  might  use  the  modulo  operator  for  this)    

Page 16: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  16  

Class Example 3 - converting Class Example 1 to C++ code

Notes

 Workshop  2  (con’t)    6)  Translate  your  algorithms  from  workshop  1  into  C++,  put  them  in  your  svn  repository  in  the  directory  2014/s1/FCS/Workshop2/    compile  and  run  your  programs.

Page 17: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  17  

3

Code blocks and scope (C++ language tutorial – Program structure: Name visibility) How does C++ represent a block of code (ie what code is part of a loop, what code is part of a function, etc)? Can we access variables/constants declared in a sub block (ie a block of code that appears inside this block of code)? Show an example. Can we access variables/constants declared in a super block (ie a block of code that contains this block of code)? Show an example. Functions (C++ language tutorial – Program structure: Functions) Write down the format of a function and function call here: Lab - Rewrite your algorithms from workshop 2 part 6 as functions and call each of them from the main function and put them in your SVN repository. Show your work to your instructor when you have completed it.

Page 18: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  18  

Binary representation (Tutorials – Numerical Bases) In base 10 (our usual base for counting with 10 possible digits 0-9) each digit is multiplied by it’s place value and added together. For example 1462 is: 1 x 10^3 = 1000 4 x 10^2 = 400 6 x 10^1 = 60 2 x 10^0 = 2 1462 binary works the same way but is base 2 with two possible digits 0-1. So the number 1011 is: 1x2^3 = 8 0x2^2 = 0 1x2^1 = 2 1x2^0 = 1 ---------------- 1011 (base 2) equals 11 (base 10) Binary is the way modern computers represent all information (even your programs). Look up ASCII characters. What is the binary representation of the character ‘S’? How many bits are in a C++ integer (you can check this in the C++ tutorial under types)? What is the largest and smallest integer that can be represented? What is the largest and smallest unsigned integer that can be represented? Question for discussion: How does the computer know whether the 0’s and 1’s are a string, character, integer, etc. You wouldn’t want to accidentally subtract a character and the number 3.21. C++ is a strongly typed language and will not allow you to mix non-compatible types. How does C++ prevent this? Do all programming languages do this? Complete Review Quiz 1 – ask questions for anything that isn’t clear. Once you have completed all of the above, you can work on Practical 1 and review questions.

Page 19: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  19  

Notes

Page 20: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  20  

Notes

Page 21: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  21  

Notes

Page 22: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  22  

Arrays (c++ language tutorial arrays): What are arrays used for? Write down an example of how to do the following in C++ Declare an array: Initialize an array: Access the nth element in an array: Use an array as an parameter in a function: Return an array from a function:

Page 23: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  23  

Lab – Prac 2

Before you begin you may need to review the section in your text or online reference about arrays.

Remember that all of your practical work needs to be in your SVN repository. This practical should be in your repository in the directory 2014/s1/FCS/prac2/ Part 1 - single dimension arrays Create a file called array1.cpp for your program Write a function called reverse that takes an array of 10 integers and reverses the elements of the array. Write a main function that asks for 10 integers to be input, calls reverse and then prints out the reversed array of integers. So if the user inputs the numbers 1 2 3 4 5 6 7 8 9 10 our program should print out 10 9 8 7 6 5 4 3 2 1 Part 2 - Design challenge (a little tricky) If we wanted to allow the user to enter between 1 and 20 numbers and reverse them, how might we do that still only using fixed size arrays? Hint, what additional information would the reverse function need to be given? Implement and test your idea. Store your answer in the file array2.cpp Multi-Dimensional Arrays (c++ language tutorial arrays): What are multi-dimensional arrays used for? Write down an example of how to do the following in C++ Declare a multi-dimensional array: Initialize a multi-dimensional array: Access the nth element in a multi-dimensional array: Use a multi-dimensional array as n parameter in a function:

Page 24: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  24  

Lab – Prac 2 Part 3 - multi-dimensional arrays and redirection Read the section Arguments passed by reference and by value in the Functions section of the online tutorial. This section discusses two ways we can pass arguments to functions: by reference and by value. In the following exercise you will need to consider whether the arguments to the functions should be passed by reference or by value. All of these exercises must be done using static arrays (ie fixed size arrays) and should be written in the file array3.cpp We have 15 students enrolled in our course and we want to create a small database with the names, age and score on this practical. How could we use a multi-dimensional array to store this information? Write a function called populateDatabase that reads in the student information from the command line and stores it into the database. You can declare the database as a global variable. Write a function called printDatabase that prints out the values in the database in a readable format. Write a function called getScore that takes a string (student name), and the database as arguments and returns the score of the student. Write a main function that calls populateDatabase, then prints out your own score (you are one of the students in the database) and then calls print database3.

Page 25: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  25  

Vectors (C++ reference – Containers – vector – look at the functions: vector::at, vector::size, vector::insert, vector::push_back, vector::pop_back, vector::operator[]):

What are vectors used for?

Write down an example of how to do the following in C++ Declare a vector: Initialize a vector: Access the nth element in a vector: Use a vector as a parameter in a function: Return a vector from a function: Get the size of a vector: Other data types (C++ tutorial – other data types)

Write down an example of each of the following and when they would be used:

typedef:

Page 26: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  26  

union:

struct:

enum:

Lab – Prac 3

Part  1  -­‐  Modify  Prac  2  part3  (student  database)  to  use  a  struct  to  represent  the  student  record  ie  name,  score,  age.    Part  2  -­‐  modify  your  program  to  use  a  vector  instead  of  an  array  to  store  the  student  records.  

   

Page 27: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  27  

Software engineering

How do each of the following contribute to correct and maintainable code?: program structure: use of space: indentation: structure of multi-line statements: documenting functions and programs with comments /** * @filename * * author name */ /** * A function that takes a temperature and a character indicating fahrenheit or celsius scale and converts to the other scale. * @param temperature the temperature to be converted * @param scale: F or f for Fahrenheit, C or c for Celsius * @return converted temperature * @precondition (we’d list them here if we had a precondition) * / worked example: specification of max Calculating the maximum Input: two numbers pre-condition: numbers must be > 0 Output: a number Calculates the maximum value for the two input numbers and returns this as the result

Page 28: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  28  

Prac 4 – Group exercise - part 1 Specify a function, numberOfTwos, which takes three arguments each representing a dice roll, and returns the number of twos that appear in the dice rolls. Your specification should include test cases that include the inputs to the function and the expected result. Compare your specification with your neighbour. Group lab - part 2 Implement the function numberOfTwos (add the implementation to the file dicepoker.js). Your implementation must include the specification from the previous question.

Add code to the driver program to call the function numberOfTwos with your test cases and check if the output is correct.

Group lab - part 3 Specify and implement a generalised version of the previous function called numberOfXs, which takes a fourth argument, x and determines the number of dice rolls that equal the argument x. Extend the driver program so that it calls the function numberOfXs to print out the number of 1s, 2s, .., 6s. Group lab - part 4 Specify and implement a function called totalOfXs, which takes a fourth argument, x and determines the total (sum) of the dice rolls that are equal to the argument x. Extend the driver program so that it calls the function totalOfXs to print out the total for each of the possible dice rolls (1s, 2s, .., 6s).

Page 29: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  29  

Testing and debugging What is the purpose of each of the following types of tests? Give an example of each: white box testing: black box testing: boundary cases: equivalence classes: Explain and give an example of each of the following testing and development techniques: stubs: test driver (driver that runs tests):

Page 30: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  30  

Class Example 4 Specify, design and determine tests for the function, isTwoOfAKind, which determines whether or not the three dice rolls include a two of a kind. Identify boundary cases and equivalence classes in your tests and whether they are white or black box tests. Prac 4 (con’t) Group exercise/lab - part 5 Design and implement test cases for the functions written in Prac 4 - part 3 and part 4. Identify boundary cases and equivalence classes in your tests and whether they are white or black box tests. Pointers (C++ tutorial – pointers. NOT including pointer arithmetics, pointers and string literals, void pointers, and pointers to functions)

Dynamic Memory (C++ language tutorial – dynamic memory)

Program memory Program variables are stored in two different memory segments: Stack and Heap So far, all variables we have declared have been stored on the stack. Stack memory is freed automatically when block of code is exited (relate to why scope is only inside of the block where defined). However, Stack memory is only used when we know the size of the data. What if we didn't know how big an array should be in advance? For example, what if we want the program user to determine how many values to store in the array? Heap memory is available to allocate dynamically at run time (ie when the program is running). Unlike Stack memory which is freed automatically when it goes out of scope, Heap memory must be managed (ie allocated and freed) by the programmer in C++. "

Page 31: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  31  

Class Exercises - Before running the code below, try to predict what will happen. stackNHeap.cpp #include <iostream> using namespace std; /** * Create and return an array on the Stack */ int * stackArray(){ int a[] = {1, 2, 3}; return a; } /** * Create and return an array on the Heap */ int * heapArray(int size){ int * a = new int[size]; //Create in the heap with new for (int i = 0; i < 3; i++ ) a[i] = i + 1; return a; } /** * Multiply first 3 array values by 2 */ void updateArray(int * arr){ for(int i = 0; i < 3; i++) arr[i] = arr[i] * 2; } int main(){ int size = 3; int b[] = {10, 20, 30}; updateArray(b); //Ok as the array in the stack. cout << "calling updateArray on {10, 20, 30} on stack" << endl; for (int i = 0 ; i < size; i++ ) { cout <<"\t" << b[i]; } cout << endl; int * a = stackArray(); // Stack memory for the array is freed cout << "Printing array returned by stackArray()" << endl; for (int i = 0 ; i < size; i++ ) { cout <<"\t" << a[i]; // Will not work! } cout << endl; int * a2 = heapArray(size); cout << "Printing array returned by heapArray()" << endl;

Page 32: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  32  

for (int i = 0 ; i < size; i++ ) { cout <<"\t" << a2[i]; } cout << endl; delete [] a2; // free heap memory when no longer needed! return 0; } output: ************************************************************************** address.cpp #include <iostream> using namespace std; /** * Demonstrates the values of and dereferening of pointers * and arrays */ int main(){ int x = 10; int * b = &x; // value of the pointer b (a memory address) cout << "int * b is: " << b << endl; // value of a dereferenced pointer cout << "*b is: " << *b << endl; // arrays are also pointers, a is a memory address int a[] = {1, 2, 3}; cout << "int array a is: " << a << endl; cout << "int array a+1 is: " << a + 1 << endl; cout << "int array a +2 is: " << a + 2 << endl; //Values in the array: dereferencing the pointer a cout << "a[0] is : " << a[0] << endl; cout << "*a is: " << *a << endl; cout <<" *(a + 1) is: " << *(a+1) << endl; cout << " *(a + 4) is: " << *(a+4) << endl; // undefined behaviour! return 0; } output:

Page 33: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  33  

************************************************************************* danglingPointer.cpp /** * Demonstrate memory managment of heap memory and dangling * pointers. */ #include <iostream> using namespace std; /** * Create and return an int array on the heap */ int * createHeapIntArray(){ int * x = new int[2]; x[0] = 1000; x[1] = 2000; return x; } /** * Create an int on the heap and return its heap address */ int * createHeapInt(){ int * y = new int; *y = 999; return y; } /** * Deleting heap memory returned from a function example */ void managingHeapMemory(){ int * x = createHeapIntArray(); int * y = createHeapInt(); cout << " x[0] is: " << x[0] << " and x[1] is: "<< x[1] << endl; cout << " y is: " << y << " and *y is: " << *y << endl; delete y; // we won't be using y anymore delete[] x; // we won't be using x anymore return; } int main(){ foo1(); int * i = new int; // allocate an int on the heap int *j = i; // j also points to the int on the heap cout << "i is: " << i << endl; cout << "j is: " << j << endl; *i = 100; /* i and j are both pointers to the heap memory where we have stored the value 100 */ cout <<"*i is: " << *i << endl; cout <<"*j is: " << *j << endl;

Page 34: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  34  

delete i; // we are finished with i, free the heap memory i = new int[5]; // i now points to space on the heap for an array cout << " *i is: " << *i << endl; cout << " *j is: " << *j << endl; // Ooops! We deleted this memory! /* the behaviour using *j is *UNDEFINED* this can be tricky to debug as the heap may still have the value or it might not. The program may or may not still have access to the memory. */ return 0; } output: What can happen when j is dereferenced (*j) ? 1) 2) 3) Practical 5 – Using pointers

debugging

example - using print statements to debug Lab - debugging lab

Aims – 1) To provide a basic introduction using a debugger (cgdb)

2) Review/Intro to binary numbers

This lab we are going to be looking at debuggers. Debuggers are programs (and hence, have bugs) that permit you to run and test other programs. The debugger allows you to stop your program at certain points and then step through it, examine variables and even change them.

Goal 1 – Learning to use the debugger

All debuggers work in basically the same way, but different debuggers offer small changes in the way you interact with them. For this workshop you will be using a

Page 35: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  35  

debugger called cgdb. cgdb is built on top of gdb, the GNU debugger(which is also installed on the lab machines).

To run a program under the control of the debugger, you first need to prepare the program. This is done by telling the compiler to retain something called the symbol table in the runnable program file. The symbol table is nothing more than a list of the names of program variables, and the memory addresses they occupy. When you ask the debugger to display the value of a program variable called foo, it simply goes to the address specified in the symbol table and displays what is there.

To compile a program with debug information included, you must use the –g flag to the compiler on our systems. For example to compile myProgram.cpp with debugging information using g++ we would type:

g++ -g myProgram.cpp

Task 1 – (markoff Q1)

Download the source code for this workshop from the forums and compile example1.cpp with the debug flag (call the output program example1). Run the resultant program like so:

cgdb example1

cgdb splits the view of the terminal into two. At the top you will see your code and at the bottom you will see the debugger terminal. The cursor will start

within the debugger terminal. If you press escape key then the cursor will focus on the code display at the top. Inside this view you can navigate around the code. If you press ‘i’ then you will return back to the debugger terminal. For this workshop you should only need to use the debugger terminal.

In order to use the debugger you will need to make use of the following commands in the debugger terminal.

Command Description run This will run your program inside the debugger

break line_number This will set a breakpoint on the provided line, causing your program to pause when it reaches that line number.

break function_name This will set a breakpoint to pause the program when you enter the provided function.

watch variable_name This will pause the program’s execution when the variable provided changes value

delete breakpoint_number This will delete the provided breakpoint

delete watchpoint_number This will delete the provided watchpoint

delete This will delete all breakpoints and watchpoints

Page 36: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  36  

info break This will display all the breakpoints and watchpoints

continue This will continue the execution of the program step This will step the program to the next line print variable_name This will print the value of the provided variable set variable variable_name = value This will set the value of the provided variable

quit Will quit cgdb

Try experimenting with these commands. For this task you will need to show the supervisor that you can:

• Run the program through the debugger • Set a breakpoint on main and then step through the program • Set a breakpoint on line 12 and then print out the variables a, b and c

in the debugger

• Set a breakpoint on line 8. Run the program then on reaching

breakpoint 8, delete it and continue the execution of your program. Task 2 – (markoff Q2)

Now compile example2.cpp and run it through the debugger. This program does not produce output, so you can only see what happens via the debugger.

Try printing the value of b through the debugger. You should see both an integer and a character. The integer is the ASCII representation of the

character. Look up “ASCII Table” online. How many different ASCII values are there?

Change the value of b (before updating it in the loop) to a character that has the integer value 122. What is the value of b after the loop has terminated? Can you explain this behavior? (hint – how many bytes are in a char? What is the largest value that can be represented in a char?)

Task 2 – (markoff Q2) Compile mem.cpp with the debug flags and load it into cgdb.

Set a breakpoint at main and step through the program until you reach line 11. Notice how the debugger jumps over lines 6-10.

What are the contents of each of the variables a, b, c, and idx at this point in the program?

What is the address at which each of the variables a, b, c, and idx are stored?

Page 37: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  37  

Draw a stack diagram showing where a, b, c and idx are stored in memory, how much space they take up, and what they contain at this point in the program. You may find it useful to use the sizeof operator to determine the size of the variables.

Task 3 – (markoff Q3) Step through to the next line in the program (so that the line ‘b = new int[ARRAY_SIZE]’ is executed).

Does the address of b change? Does the contents of b change? Where do you think the heap is in memory?

Task 4 – (markoff Q4) Assume you have the code below:

int a[5]; int i; for (i=0; i<10; i++) { a[i]=5-i; cout << "a[" << i << "] = " << a[i] << "\n"; }

and a stack as shown:

Var name Contents Address i 0x7fff5fbff9d4 a[4] 0x7fff5fbff9d0

a[3] 0x7fff5fbff9cc

a[2] 0x7fff5fbff9c8

a[1] 0x7fff5fbff9c4

a[0] 0x7fff5fbff9c0 What will happen in this program? Step through the program by hand (not in cgdb) updating the stack contents to work out what happens. Will this program always allocate memory in this manner and behave this way? Explain.

Page 38: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  38  

File I/O (C++ language tutorial input/output with files)

Notes:

Page 39: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  39  

Notes

Page 40: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  40  

Notes

Page 41: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  41  

Notes

Page 42: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  42  

Lab - Programming Languages and their tools Aims – 1) To practice the development of an algorithm, compare algorithms and implement. 2) To review some of the basic programming structures we expect you to be familiar with. 3) To examine what is common and different between programming languages. 4) Learn to find, interpret, understand and use documentation about software development tools and programming languages. These tasks should be with a partner. Your group needs to write down your answers to the group questions either online or on paper. Workshop supervisors will discuss your answers with you and mark you off for each section completed. You can receive assistance fromand give assistance to other students for individual tasks, but guidance on how to solve the problem rather than solutions should be given. – Reviewing algorithm development - Hunting the Snark Hunting the Snark is to be a simple guessing game. The Snark* will be hiding behind one of three trees (red, yellow or green). The player has a maximum of three guesses to guess which tree the Snark is behind. *The Snark is a fictitious creature in Lewis Carroll’s The Hunting of the Snark. Capturing the Snark causes you to disappear. http://www.gutenberg.org/ebooks/13 Task 1 Q1 Design an algorithm outlining the steps the computer must take to play the Hunt the Snark game with a human user. You can design your algorithm in English, chart form, pseudocode, or any other form you feel comfortable with. It is your job to identify any additional details you may need to know about the game’s behaviour. Your workshop tutor will give you 15 minutes to work on sketching out your algorithm. They will then announce a question and answer periodwhen you can ask for any further details you need to complete your algorithm.

Page 43: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  43  

Keep a copy of your team’s design for Task 1, you will need it later. Q2 Download the code files from the course Forum. If you aren’t prompted to unarchive the file, you can open a terminal (from the applications menu and use the archive command: tar xvf workshop1Code.tar You will now have a directory with 4 files. Compare the four implementations of the Snark program in the different languages (Python, C++ and Java). What common programming constructs do you see in the different languages? Make a list of similarities and differences you see in the languages. Explain what is meant by the following and identify where each of the three languages (Python, Java, C++) fit. Strongly Typed:

Page 44: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  44  

Weakly Typed: Static type checked: Dynamic type checked: How does the Snark.cpp program compare with your algorithm? Do both work equally well? Are there aspects that are clearer or less clear in one algorithm? Goal 2 – exploring compilers and interpreters Q3 What command compiles C++ code? Java code? Python? Look online to find this information and run each of the programs. Test whether they work. Can you cause the programs to fail? If so, how?

Page 45: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  45  

Note the difference in the way that you run C++ and Java versus running Python. Can you think or find any advantages to one or the other? Introduction to Objects (C++ tutorial Classes (I) ) Objects are like structs but contain both variables AND methods (functions) and by default they hide the information from other parts of the program – instead they control what parts of the program can access the variables and methods and how. Member variables can be public or private (or protected which we’ll look at later in inheritance). Are member variables usually public or private? Why? Member functions can be public or private (or protected which we’ll look at later in inheritance). Are member functions usually public or private? Why? Give an example where you might make a member function private? Think about what this would mean. Where could the function be called from?

Page 46: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  46  

Give an example of the following types of methods and explain their role: Constructor: Destructor: Acessor: Mutator:

Page 47: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  47  

Class Example: Create  a  student  object.    Using  the  code  from  prac  2  part  3,  create  a  database  of  student  objects.  How  would  this  change  if  we  made  the  database  of  pointers  to  student  objects?  How  would  this  change  if  we  used  a  dynamic  array  instead  of  a  vector?  

Page 48: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  48  

Notes

Page 49: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  49  

Notes      

Page 50: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  50  

 Lab – designing objects Aims – 1) To gain experience writing classes in C++ 2) To become familiar with compiling a program that contains multiple header(.h) and source files(.cpp). 3) To gain experience with Unified Modelling Language (UML) 4) To be able to develop use UML diagrams for notating a simple class In this exercise we will be looking into classes and creating them using C++. You will start this workshop by looking at a Die class that has been notated using UML. UML is a standardised modelling language used to describe object-oriented systems. From there you will need to write both the header and source file for this Die class. In finishing this workshop you will be designing a class to represent a die roll within the popular dice game Yahtzee. You will be using UML to notate your design of this class. Task 1 Group Task – (markoff Q1) When designing classes we can use UML diagrams to capture the important information about that class. These diagrams allow us to start thinking about our overall design before we write any code. The format a UML diagram of a class is shown below.

Within UML class diagrams we represent are access modifiers as follows:

!!

CS 1X02 Object Oriented Programming

Workshop Week 7 Objects, Classes and UML

Aims –

1) To gain experience writing classes in C++ 2) To become familiar with compiling a program that contains multiple

header(.h) and source files(.cpp). 3) To gain experience with Unified Modelling Language (UML) 4) To be able to develop use UML diagrams for notating a simple class

This week we will be looking into classes and creating them using C++. You will start this week’s workshop by looking at a Die class that has been notated using UML. UML is a standardised modelling language used to describe object-oriented systems. From there you will need to write both the header and source file for this Die class.

In finishing this workshop you will be designing a class to represent a die roll within the popular dice game Yahtzee. You will be using UML to notate your design of this class.

Over the next two practical sessions you will be implementing this class.

Task 1 Group Task – (markoff Q1) When designing classes we can use UML diagrams to capture the important information about that class. These diagrams allow us to start thinking about our overall design before we write any code. The format a UML diagram of a class is listed below.

Class Name

Member Variables access modifier attributeName: type

Methods access modifier attributeName: return type

Within UML class diagrams we represent are access modifiers as follows: Symbol Access Modifier Description + Public Method or member variable is accessible both

in and outside of the class implementation - Private Method or member variable is only accessible

inside the class implementation # Protected We will talk about this access modifier later Here is the UML diagram for a Die class. For this task create a header file(.h) representing the class described in the diagram. You should define your header file in the Die.h. The syntax for defining a class is as follows: #ifndef CLASSNAME_H #define CLASSNAME_H class ClassName { access-modifier: ClassName(); // Argument less constructor

ClassName(int foo); // Constructor with argument ~ClassName(); // Destructor int getSomething() const; // Accessor void doSomething(); // Mutator int m_myFoo; // Member variable }; #endif Task 2 Group Task – (markoff Q2) For this task you will need to write the implementation of the Die class in Die.cpp. An important thing to note is that this Die class represents a six-sided die so m_face should be in the range of 1 to 6 inclusive.

Die

- m_face: unsigned int

+ Die() + Die(unsigned int face) + getFace() const: unsigned int + roll(): void

Page 51: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  51  

Here is the UML diagram for a Die class. For this task create a header file(.h) representing the class described in the diagram. You should define your header file in the Die.h.

The syntax for defining a class in you Die.h file is as follows – you will need to replace “CLASSNAME_H” with you actual class name “DIE_H” and ClassName with Die. And replace “access-modifier” with the appropriate modifier (public or private). Die.h file #ifndef DIE_H #define DIE_H class Die { public: Die(); // Argument less constructor Die(unsigned int face); // Constructor with argument ~ClassName(); // Destructor int getFace() const; // Accessor void roll(); // Mutator private: unsigned int m_face; // Member variable – current Die value }; #endif Task 2 Group Task – (markoff Q2) For this task you will need to write the implementation of the Die class in Die.cpp. An important thing to note is that this Die class represents a six-sided die so m_face should be in the range of 1 to 6 inclusive. The syntax for defining the implementation class for the Die.h definition is as follows:

Within UML class diagrams we represent are access modifiers as follows: Symbol Access Modifier Description + Public Method or member variable is accessible both

in and outside of the class implementation - Private Method or member variable is only accessible

inside the class implementation # Protected We will talk about this access modifier later Here is the UML diagram for a Die class. For this task create a header file(.h) representing the class described in the diagram. You should define your header file in the Die.h. The syntax for defining a class is as follows: #ifndef CLASSNAME_H #define CLASSNAME_H class ClassName { access-modifier: ClassName(); // Argument less constructor

ClassName(int foo); // Constructor with argument ~ClassName(); // Destructor int getSomething() const; // Accessor void doSomething(); // Mutator int m_myFoo; // Member variable }; #endif Task 2 Group Task – (markoff Q2) For this task you will need to write the implementation of the Die class in Die.cpp. An important thing to note is that this Die class represents a six-sided die so m_face should be in the range of 1 to 6 inclusive.

Die

- m_face: unsigned int

+ Die() + Die(unsigned int face) + getFace() const: unsigned int + roll(): void

Page 52: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  52  

Die.cpp file #include “Die.h” // Argument-less Constructor Implementation Die::Die() { // Set member variables here – default will be 1 m_face = 1; } // Constructor with Arguments Implementation using initializer list Die::Die(unsigned int face):m_face(face) { } // Destructor Die::~Die() { } // Accessor Implementation unsigned int Die::getFace() const { return m_face; } // Mutator Implementation void Die::roll() { m_face = 1337; } Once you have written your implementation file then download the source code for this workshop. We have provided you with a main.cpp file that creates and makes use of your Die class. To compile all of these files use the following command: g++ -g Die.cpp main.cpp –o dieProgram (note the files must be in this order. Files to the left of the list must NOT depend on anything defined in files to its right in the list. Here the main program uses Die in its code. Die does not use anything in the main.cpp file in its code). Once you can compile and run this program, get your work marked off by a supervisor. Task 3 Group Task – (markoff Q3) For this task you will need to design a class called DiceRoll using UML notation. The DiceRoll class represents a collection of rolled die. All of the dice in this collection are six-sided die and so you can reuse your Die class within then DiceRoll class. This DiceRoll class will be used within the popular dice game Yahtzee. If you

Page 53: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  53  

are unfamiliar with Yahtzee then you can look the rules up online or ask another member of your group. You will need to make an appropriate abstraction of this class based on functionality required to play Yahtzee. In particular we will need your DiceRoll object will need to be able to: • Reroll all the dice • Obtain the number of times a face value appears in the roll • Identify if the dice roll may be scored as Three of a Kind, FourofaKind Full House Yahtzee • Return the sum of all die in the roll (Chance) • Obtain a list of the current face values Your dice roll class does not need to support scoring of a small or large straight. Prac 7 – Objects Aims – 1) To gain experience in writing objects that are composed of other objects 2) To become familiar with reading in input from a file in C++ 3) To gain more experience in identifying suitable test cases References needed – Textbook or online tutorial for C++ reference. Notes on Objects This practical session is a continuation of the work started in the Workshop. You will need to complete that workshop before starting this practical. For this practical store your code in the following directory inside of SVN. 2014/s1/FCS/diceRoll You should be committing your work to SVN as you make changes. You may find it useful to commit every time you complete one of the practical tasks. Task 1 – Write a header file based upon the DiceRoll class that your group designed in the workshop. When writing this header file ensure that: 1) You correctly use include guards (lines with hash in front of them) 2) You use const to identify which methods are accessors 3) You provide the correct access modifier to your member variables and methods

Page 54: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  54  

4) You do not have ‘using namespace std’ inside your header file. Instead everything from the standard namespace is prefixed with std:: Task 2 – Write the implementation file(.cpp) for DiceRoll. Your implementation file should contain implementations of every method you defined in the class header. Task 3 – Write a small program that uses the DiceRoll class. This program should create a DiceRoll object, then roll all the dice and then print out the face values of each of the dice. It should then print out whether the current roll can be scored as a Three of a Kind, Four of a Kind, Full House or Yahtzee. Task 4 – Update your program from Task 3 so that it now accepts the command line argument –test. So that if we type: ./diceProgram –test then the DiceRoll tests will be run. Whereas if we type: ./diceProgram the tests will not be run We can do this by using another form of the main function: int main(int argc, char * argv[]) When we use this, we can access the variables argc, which is the number of arguments given on the command line, and argv which is an array of the actual arguments (stored as arrays of characters) If we type: ./diceProgram –test then argc will be 2 (there are two arguments on the command line) and argv will be an array with “./diceProgram” and “-test”. So we can check if argc is greater than 1 and if so if any arguments, other than the first == “-test”. If so then run the tests. Your unit tests should test the methods related to: Obtaining the number of times a face value appears in the roll Identifying if the dice roll may be scored as o Three of a Kind o FourofaKind

Page 55: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  55  

o Full House o Yahtzee Return the sum of all die in the roll(Chance) You may find it useful to write a constructor for your DiceRoll class that accepts a list of face values. Task 5(Optional) – Add two additional methods to your DiceRoll class that check if it can be scored as a short or long straight. You may find it useful to overload the comparison operators for your Die class. At this point, you would have written a lot of the core logic behind the game Yahtzee. With a bit of additional effort you could easily implement the entire game. Consider what other objects you would need to fully develop this game. Feel free to post your ideas on the forums for discussion.      Complete  the  reviews  and  prac  8              

Page 56: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  56  

Static  class  members  -­‐  (C++  tutorial  Classes  (II)  Static  Members)    What  are  static  class  members  used  for?          How  do  you  make  a  static  class  member  in  C++?          Where  do  you  initialise  static  class  member  variables?    Class  Exercise    Write  a  WebPage  class  that  has  a  static  count  that  keeps  track  of  the  number  of  times  any  web  pages  have  been  visited.  For  example  if  there  are  5  web  pages  and  page  1  has  been  visited  once  and  page  4  has  been  visited  five  times,  then  the  count  should  6  (1  visit  +  5  visits).    Write  a  driver  to  show  that  the  count  is  static  -­‐  ie  that  if  a  page  is  visited,  all  pages  will  see  the  count  increased,  not  just  the  page  that  was  visited.      

Page 57: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  57  

Notes

Page 58: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  58  

C++ tutorial - Classes (II) Overloading operators, keyword this Special Members - copy constructor, copy assignment Write down an example member function to overload the operator < for a Die class:  Class Exercise – Extend your Card class to overload the operators <, >, == and = When is a copy constructor needed? What is the keyword this used for? When is it needed?

Page 59: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  59  

Prac 9 – operator overloading, copy constructors Objective:  Familiarise  and  practice  the  four  important  member  methods  of  a  C++  class,  namely,    

1. Constructor  2. Copy  constructor  3. Destructor  4. Copy  assignment  and  operator  overloading  

e.g.,   class Matrix { public: Matrix(); // constructor Matrix(const Matrix &f); // copy constructor ~Matrix(); // destructor Matrix & operator = (const Matrix& rhs); // assignment operator };  Task:  Design  and  implement  a  Matrix  class.  A  matrix  is  a  dynamically  allocated  1-­‐dimension  array  (do  not  use  2-­‐dimension  array;  do  not  use  std:vector  ).  A  pointer  float * data is  needed  to  hold  the  2-­‐dimensional  matrix  data.  Let’s  assume  the  matrix  is  stored  as  row-­‐wise.  That  means,  a  2-­‐dimension  matrix  M  with  m  by  n:    M(0,0) M(0,1) …. M(0, n-1) . . . M(m-1,0) …… M(m-1, n-1) Fig. 1  is  stored  as  a  1D  array  in  the  memory:      [ M(0,0), M(0,1), M(0,2), … ….. …. M(m-1,0), …, M(m-1, n-1) ]    

Hints:  a  matrix  element  in  the  2D  matrix     M(i, j) (indexed from 0, not 1) can  be  mapped  to  the  1D  array  p(k)  using  the  calculation:   k = i * n + j The  1D  array  is  also  indexed  from  0,  instead  of  1.      

• Task  1:  

Design  and  implement  this  Matrix  class.  Your  class  should  have  the  above  four  member  methods.  

 Your  class  should  have  a  member  function  which  reads  a  ASCII  text  file  containing  the  raw  matrix  data.  You  can  suppose  you  know  the  row  and  column  number  of  the  matrix  (m  and  n  respectively).  The  raw  matrix  data  are  stored  as  in  Fig.  1.  We  assume  no  blank  lines  and  comments  in  the  data  file.  It’s  well  formatted.    

Page 60: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  60  

• Implement  a  main  function  which  declares  an  object  of  your  Matrix  class  and  read  a  data  file  and  print  a  particular  datum  in  the  matrix.  Then  delete  the  object  which  should  call  the  properly  implemented  destructor.  Also  test  the  copy  constructor  and  overloaded  assignment  operator.    

• Task  2:    

Overload  operator  "+"  for  calculating  C  =  A  +  B  (A,B,C  are  Matrix  objects).  You  can  use  input_a.txt,  and  input_b.txt  as  input  files  to  create  Matrix  A  and  B  respectively.    

• Task  3:  

Overload  operator  "*"  for  matrix  product  (multiplication).  Check  http://en.wikipedia.org/wiki/Matrix_multiplication  to  see  how  matrix  multiplication  works.  You  can  use  input_c.txt,  and  input_d.txt  as  input  files.    

Your  Matrix  class  must  be  designed  in  a  way  that  fits  for  any  type  of  matrices,  not  only  for  matrices  provided  for  testing  purpose.  All  input  files  can  be  found  from  file  inputfiles.zip.                                                Friends  (C++  tutorial  Friendship  &  Inheritance  -­‐  Friend  functions,  friend  classes)    What  does  making  a  function  or  a  class  a  friend  allow?          

Page 61: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  61  

       Note,  it  is  unlikely  you  will  need  to  use  friend  functions  for  any  of  your  work  in  this  course.    We  only  expect  you  to  know  what  they  are  and  how  they  work  in  case  you  come  across  them.          Review  &  Practice    Based  on  work  so  far,  your  lecturer  may  give  you  additional  practice  labs.      

Page 62: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  62  

Notes    

Page 63: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  63  

Notes

Page 64: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  64  

Notes      

Page 65: Workbook-CS 2202 Foundations of Computer Science Wk 1-6

  65  

Notes