14
Practical Week 5 Programming Using C# QUEEN’S UNIVERSITY BELFAST

Programming Using C#computingat.eeecs.qub.ac.uk/wp-content/uploads/2015/10/...6 | QUEEN’S UNIVERSITY BELFAST TASK 3: SUM OF AN ARRAY Often the elements of an array represent a series

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Programming Using C#computingat.eeecs.qub.ac.uk/wp-content/uploads/2015/10/...6 | QUEEN’S UNIVERSITY BELFAST TASK 3: SUM OF AN ARRAY Often the elements of an array represent a series

Practical Week 5

Programming Using C#

QUEEN’S UNIVERSITY BELFAST

Page 2: Programming Using C#computingat.eeecs.qub.ac.uk/wp-content/uploads/2015/10/...6 | QUEEN’S UNIVERSITY BELFAST TASK 3: SUM OF AN ARRAY Often the elements of an array represent a series

1 | QUEEN’S UNIVERSITY BELFAST

Table of Contents

PRACTICAL 5 ..................................................................................................................................................... 2

EXERCISE 1 ..................................................................................................................................................... 2

TASK 1: CREATING AN ARRAY ................................................................................................................. 2

TASK 2: ARRAYS AND LOOPS ................................................................................................................... 5

TASK 3: SUM OF AN ARRAY ...................................................................................................................... 6

EXERCISE 2 ..................................................................................................................................................... 7

TASK 1: STORING USER INPUT IN AN ARRAY ........................................................................................... 7

TASK 2: REVERSE PRINT ARRAY................................................................................................................. 7

TASK 3: LARGEST AND SMALLEST VALUE IN THE ARRAY ........................................................................ 7

EXERCISE 3 ........................................................................................................................................................ 9

TASK 1: MULTI-DIMENSIONAL ARRAYS .................................................................................................... 9

TASK 2: TIMES TABLES USING MULTI-DIMENSIONAL ARRAYS ............................................................... 10

EXERCISE 4 ................................................................................................................................................... 11

TASK 1: CREATING A LIST ........................................................................................................................ 11

TASK 2: CREATING A RANDOM LIST ...................................................................................................... 13

Page 3: Programming Using C#computingat.eeecs.qub.ac.uk/wp-content/uploads/2015/10/...6 | QUEEN’S UNIVERSITY BELFAST TASK 3: SUM OF AN ARRAY Often the elements of an array represent a series

2 | QUEEN’S UNIVERSITY BELFAST

PRACTICAL 5 Practical 4 introduced you to objects; this is a fundamental feature of object oriented

programming. You should consider your problems as you solve them on paper and aim to identify

what objects you will require to programme the solution efficiently. This will involve looking that

the states, i.e. instance variables, which will allow you to classify and identify each instance of that

object and the behaviours, i.e. the methods, which will allow you to apply functions to the object.

Object orientation allows code reuse, modularity and portability of your programmes. This should

make testing and debugging much easier.

This practical, practical 5, introduces arrays this is another fundamental feature of programming.

EXERCISE 1 The tasks in the first part of this practical provide step-by-step instructions on creating an object in

C#. This is followed by a number of tasks for you to complete by applying the knowledge gained

in the first few tasks.

TASK 1: CREATING AN ARRAY In this task you will create an array with a data type of double. The array will have 10 elements

and you will individually initialise each one. After you have initialised the elements, you will print

each element to the console with reference to the array.

Step 1: Open Visual Studio and navigate to the File menu, select New (or press Ctrl+Shift+N) and

click on Project. Name the new project appropriately e.g. P05E01Task01.

NOTE: In the next step we will declare an array which we must do to be able to use it – very

similar to how we would with a variable. Therefore we will have to give it a type, using the

following format

typeName[] arrayRefVar;

typeName can refer to any of the primitive data types or an object reference (which can

be user defined).

Then we will construct the array using the new operator as follows:

arrayRefVar = new typeName[length];

The above statement does two things:

It creates a new array of type typeName and of length length;

It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to

the variable can be combined in one statement, as shown below:

typeName[] arrayRefVar = new typeName[length];

int [] myArray = new int [length]

Table 1 below outlines how you can declare arrays for different data types.

Page 4: Programming Using C#computingat.eeecs.qub.ac.uk/wp-content/uploads/2015/10/...6 | QUEEN’S UNIVERSITY BELFAST TASK 3: SUM OF AN ARRAY Often the elements of an array represent a series

3 | QUEEN’S UNIVERSITY BELFAST

Table 1

Step 2: We are going to create an array of data type double with 10 elements, type the code, in

Figure 1, into the main method of your class:

Figure 1

This has declared the array and the value of each element has been initialised to zero.

Consider table 2 below which illustrates how the array would look:

index 0 1 2 3 4 5 6 7 8 9

value 0 0 0 0 0 0 0 0 0 0

Table 2

You can now start to assign your own values to the each element but remember that you

cannot have any more than 10 elements in this array.

Each item in an array is called an element and each element is accessed by its

numerical index, as shown in table 2. Also note that numbering begins at 0. Table 3

outlines what we want our array to contain.

index 0 1 2 3 4 5 6 7 8 9

value 1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9

Table 3

Therefore, to initialize an element within an array, we would use the following syntax:

arrayRefVar[index] = value;

The square brackets are used to refer to the position of each element within the array.

Don't forget arrays start at 0, the first position in an array has the index number 0.

Step 3: To assign a value to the first element, type the following line of code, Figure 2, underneath

where you declared the array:

Figure 2

Declaring Arrays

int[] numbers = new int[10]; An array called numbers of ten

integers. All elements are initialized to

zero.

int length = Convert.ToInt32(Console.Readline());

double[] data = new double[length];

The length need not be a constant. It

can be taken from an input stream.

int[] squares = {0, 1, 4, 9, 16};

An array of five integers with initial

values.

String[] friends = {“Emily”, “Bob” , “Cindy”}; An array of three strings

double[] data = new int[10]; ERROR: You cannot initialize a double[]

variable with an array of type int[]

Page 5: Programming Using C#computingat.eeecs.qub.ac.uk/wp-content/uploads/2015/10/...6 | QUEEN’S UNIVERSITY BELFAST TASK 3: SUM OF AN ARRAY Often the elements of an array represent a series

4 | QUEEN’S UNIVERSITY BELFAST

Step 4: The first element of the array, at position 0, has now been assigned the value 1.0.

Continuing from Table 3, we will now assign the second element by typing the code, in Figure 3,

under the line assigning the first element of the array:

Figure 3

Step 5: You should now individually assign the remaining elements of the array using the values

specified in Table 3. Remember to correctly reference the elements as you proceed.

Step 6: We will now print all elements of the array to the Console. Type the code in Figure 4

underneath the last assignment to position 9 in the array:

Figure 4

Step 7: Repeat the code above for each element in the array. Remember to edit the text within

the quotation marks so it is relevant to the element you are printing within that statement.

Step 8: Save your work (CTRL+Shift+S) and then choose the Start menu item (or press

Ctrl+F5). Your output will be similar to Figure 5 below:

Figure 5

You now have successfully declared and assigned values to elements in your array. What

happens if you try to assign a value to index 10? Try it and see. As there are only 10 spaces in the

array (indexed 0-9), trying to assign a value to the 11th space will cause and error. This is one of

the main errors you will obtain when working with arrays.

Page 6: Programming Using C#computingat.eeecs.qub.ac.uk/wp-content/uploads/2015/10/...6 | QUEEN’S UNIVERSITY BELFAST TASK 3: SUM OF AN ARRAY Often the elements of an array represent a series

5 | QUEEN’S UNIVERSITY BELFAST

TASK 2: ARRAYS AND LOOPS As you should note there is a lot of repeated code in Task 1 and it would be much easier to use a

loop to iterate through each element of the array rather than accessing them individually. This

tasks steps you through using loops to assign values and print them to console.

Step 1: Create new Console Application project and name it P05E01Task02.

Step 2: In the Program class, within the main method, declare an array of data type integer that

will hold 10 elements, see Figure 6.

Figure 6

Step 3: Write a for loop to populate the array by typing the code in Figure 7 beneath your array

declaration:

Figure 7

There are 10 elements in the array, which must be assigned a value. The first element of the

array is at index 0 so the initializer variable of the for loop, called i, starts at 0. In order to fill

all elements of the array we want the loop to continue until it reaches 9 (i.e. less than 10).

We will add one to i each time the loop is executed. The value that is being assigned to

each element of the array is the current value of i, see Table 4.

index 0 1 2 3 4 5 6 7 8 9

value 0 1 2 3 4 5 6 7 8 9

Table 4

Step 4: We will now create another for loop which will print out the array. Type the code in Figure

8 beneath the loop you wrote to assign values.

Figure 8

Step 5: Save your work (Ctrl+Shift+S), run the program by clicking the start button on the toolbar

or use the shortcut Ctrl+F5. A console window should open with output similar to Figure 9:

Figure 9

Page 7: Programming Using C#computingat.eeecs.qub.ac.uk/wp-content/uploads/2015/10/...6 | QUEEN’S UNIVERSITY BELFAST TASK 3: SUM OF AN ARRAY Often the elements of an array represent a series

6 | QUEEN’S UNIVERSITY BELFAST

TASK 3: SUM OF AN ARRAY Often the elements of an array represent a series of values that may be used in a calculation for

another purpose.

For example, if the array represents exam grades for a student, a tutor may wish to total the

elements of the array to calculate the average mark attained by that student. This task will step

you through coding this.

Step 1: Create new Console Application project and name it P05E01Task03.

We will use the information provided in Table 5 to create a 10 element integer array with

studentArray

index 0 1 2 3 4 5 6 7 8 9

value 87 68 94 100 83 78 85 91 76 87

Table 5

NOTE: When you know the array values you need at the point of declaration, then you can

declare, create and assign values in one statement. The syntax is as follows:

typeName[] arrayRefVar = {value1, value2, value3,…,value10};

Step 2: Type in the code in Figure 10 to declare, create and assign the values in Table 5.

Figure 10

Step 3: To add the elements together type in the following code, beneath the declaration of the

array

Figure 11

NOTE: To add all the values together we will need a variable to hold the running total i.e

total. This needs to be declared outside the for loop and initialised to zero. If declared

inside the loop then it is only accessible inside the loop but we will need the information

stored in the variable outside the loop.

Within the for loop we use studentArray.Length which is an inbuilt method of an array that

provides the length of it. It is better programming practice to use array.Length as we don’t

need to worry about knowing how many values are actually stored in the array.

Finally we use += to say total = total + studentArray[i]

Step 3: Now let us print out some values of the array, namely the total, the number of elements in

the array and the average mark. To do this type the code in Figure 12 after the for loop.

Figure 12

Step 4: Save your work (Ctrl+Shift+S), run the program by clicking the start button on the toolbar

or use the shortcut Ctrl+F5.

Page 8: Programming Using C#computingat.eeecs.qub.ac.uk/wp-content/uploads/2015/10/...6 | QUEEN’S UNIVERSITY BELFAST TASK 3: SUM OF AN ARRAY Often the elements of an array represent a series

7 | QUEEN’S UNIVERSITY BELFAST

EXERCISE 2

TASK 1: STORING USER INPUT IN AN ARRAY Our next task uses arrays to store information that is collected via user input in a survey. This is a

typical array-processing application, where we want to use Console.ReadLine() to accept

input from the keyboard and store it in an array.

Step 1: Create new Console Application project and name it P05E02Task01. Declare the array

based on the information in Table 6.

variable name studentNames

data type String

length 6

Table 6

Step 2: Now write code asking the user to enter six student names and assign each name to the

next element in the array declared in Step 1.

Step 3: Use a for loop to print all the names entered in Step 2.

Step 4: Save your work (Ctrl+Shift+S), run the program by clicking the start button on the toolbar

or use the shortcut Ctrl+F5. You should see the six student names that you entered.

TASK 2: REVERSE PRINT ARRAY An array can be printed in reverse order. This can be achieved by printing the value at the last

index and decrementing to the first.

Step 1: You should now amend the code from Exercise 2 Task 1 to add another for loop which will

run through the array from the last value to the first. Remember that the Length method provides

you with the length of the array but the last index is the length minus 1.

Step 3: Save your work (Ctrl+Shift+S), run the program by clicking the start button on the toolbar

or use the shortcut Ctrl+F5. You should see the six student names that you entered in

reverse order.

TASK 3: LARGEST AND SMALLEST VALUE IN THE ARRAY In this task you will write a program to read a sequence of values and add them to an array. You

will then find the largest and smallest values of the array, print these to screen and print the

contents of the array.

Step 1: Create new Console Application project and name it P05E02Task03. Then carry out the

following instructions to set up your program.

Create a one-dimensional array of type double and length 10

Create a currentSize variable of type int and initialise it to zero

Create two variables of type double named currentLargest and currentSmallest.

Step 2: Carry out the following set of instructions to read input from the console and print the array

Create a while loop to take input while the value in currentSize is less than the length of the

array

o Within the loop, ask the user for input, assign the input to the current element of the

array

o Within the loop, increment currentSize variable by one

Page 9: Programming Using C#computingat.eeecs.qub.ac.uk/wp-content/uploads/2015/10/...6 | QUEEN’S UNIVERSITY BELFAST TASK 3: SUM OF AN ARRAY Often the elements of an array represent a series

8 | QUEEN’S UNIVERSITY BELFAST

Step 3: Find the largest value by implementing the following instructions:

Assign to the variable currentLargest the value stored in the first position in the array

Use a for loop to iterate through the array

o In the for loop use an if statement to compare the current element of the array to

the value held in the currentLargest variable

o If the current element is greater than the currentLargest, assign its value to currentLargest

o In the for loop print out each element of the array

Step 4: Print the largest value of the array to the console

Step 5: Find the smallest value by implementing the following instructions:

Assign to the variable currentSmallest the value stored in the first position in the array

Use a for loop to iterate through the array

o In the for loop use an if statement to compare the current element of the array to

the value held in the currentSmallest variable

o If the current element is smaller than the currentSmallest, assign its value to currentSmallest

o In the for loop print out each element of the array

Step 6: Print the smallest value of the array to the console

NOTE: If you want to speed things up, you can use .Min() and .Max() on an array and it

returns the element with the smallest and largest number. However it is better to show

students how to work through an array to get these values and then introduce them to the

shortcuts provided.

Step 7: Save your work (Ctrl+Shift+S), run the program by clicking the start button on the toolbar

or use the shortcut Ctrl+F5. You should get output similar to Figure 13.

Figure 13

Page 10: Programming Using C#computingat.eeecs.qub.ac.uk/wp-content/uploads/2015/10/...6 | QUEEN’S UNIVERSITY BELFAST TASK 3: SUM OF AN ARRAY Often the elements of an array represent a series

9 | QUEEN’S UNIVERSITY BELFAST

EXERCISE 3 In this exercise we will look at multi-dimensional arrays and also start to look at other functions that

we can perform on an array.

TASK 1: MULTI-DIMENSIONAL ARRAYS

The simplest form of the multidimensional array is the 2-dimensional array. A 2-dimensional array is,

in essence, an array of arrays.

These easiest way to consider a 2-dimensional array is as a table. The table will have x number of

rows and y number of columns. Figure 14 illustrates a 2-dimensional array, which contains 3 rows

and 4 columns, it also shows how to access each of the values (or cells).

Figure 14

Thus, every element in array myArray is identified by an element name of the form

myArray[row, column]

Multidimensional arrays may be initialised by specifying bracketed values for each row. For

example the code above Table 7 is a two dimensional array with 3 rows and each row has 4

columns.

int[,] myArray = new int[3, 4] { { 1, 2, 3, 4 }, { 1, 1, 1, 1 }, { 2, 2, 2, 2 } };

Column 1 Column 2 Column 3 Column 4

Row 0 1 2 3 4

Row 1 1 1 1 1

Row 2 2 2 2 2

Table 7

An element in a 2-dimensional array is accessed by using the subscripts, i.e., row index and

column index of the array. For example:

int value = myArray[2,3];

This statement will set the variable value to the value located on the second row in the third

column.

This is how we also print out the contents of a multidimensional array.

Console.WriteLine(myArray[2,3]);

Page 11: Programming Using C#computingat.eeecs.qub.ac.uk/wp-content/uploads/2015/10/...6 | QUEEN’S UNIVERSITY BELFAST TASK 3: SUM OF AN ARRAY Often the elements of an array represent a series

10 | QUEEN’S UNIVERSITY BELFAST

Step 1: Create new Console Application project and name it P05E03Task01. Declare the array

based on the information in Table 7.

Step 2: To step through the multidimensional array we will use a nested for loop. The first loop will

step through each row and the second loop will step through each column. Type the code in

Figure 15 to print out each element of your array

Figure 15

The GetLength() method is used to get the length of a specific dimension of the array.

GetLength(0) will relate to the number of rows and GetLength(1) will return the number of

columns in this example.

Step 3: Save your work (Ctrl+Shift+S), run the program by clicking the start button on the toolbar

or use the shortcut Ctrl+F5. You should see output similar to Figure 16.

Figure 16

TASK 2: TIMES TABLES USING MULTI-DIMENSIONAL ARRAYS This aim of this task is to produce columns of the times tables, using multidimensional arrays, similar

to that shown below.

1 2 3 4

2 4 6 8

3 6 9 12

4 8 12 16

The first column is the 1 times table, the second is the 2 times table and so on. The program will

ask for user input to determine a value for the number of rows and the number of columns in the

table. Try to code this using the tab \t to separate your numbers.

Page 12: Programming Using C#computingat.eeecs.qub.ac.uk/wp-content/uploads/2015/10/...6 | QUEEN’S UNIVERSITY BELFAST TASK 3: SUM OF AN ARRAY Often the elements of an array represent a series

11 | QUEEN’S UNIVERSITY BELFAST

EXERCISE 4

TASK 1: CREATING A LIST The .NET Framework has another construct that handles many of the issues associate with arrays a

little easier. This construct is a List and this is more simply referred to as a collection. It is

considered to be an object and once created provides us with the ability to add an item, remove

an item (from any location in the List), peek at an item and also move an item from one place in

the list to another. These functions are not easily applied to an array and therefore a list provides

more flexibility depending on the data you want to “collect”. However, if the number of elements

in the List are known, or if the List is of a small fixed size, or if the efficiency in using primitive data

types is important, it is better to use arrays. Using a List will cause your program to run slower.

In this task we will create a List to hold an undetermined number of names. Consider setting up a

new class list at the start of term, you will need all names but until they arrive you are unsure how

many students there will be.

A List can be used to hold Object references and primitive data types (e.g. double).

Step 1: Create new Console Application project and name it P05E04Task01.

Declaring a List is very similar to declaring any other Object. We must tell it what Object we

are creating i.e. a List, we must provide it with a type i.e. String and we must instantiate an

instance of the Object using the keyword new.

Step 2: Let’s now declare a List of type String by typing the code in Figure 17:

Figure 17

NOTE: In this task we are going to use the Random class to generate a random integer

between 1 and 12 to determine the amount of elements we are going to store.

Step 3: To set up the random value, for the number of students in the class this year, type the code

in Figure 18:

Figure 18

Like an array the contents of a List are known as elements. However unlike an array we do

not need to know the position or index that an element is being added to. For a List data is

added to the end of it. If we want to add data at a part position in the List then we can

also achieve this. Therefore we have two different methods we can use when adding

information to a List.

The two different methods for adding data to a List are as follows:

The Add method: this adds data to the end of the List, using

myList.Add("objectToAdd");

The Insert method: this adds data to the List at a specific index. Therefore we supply

the Insert method with the index as well as the data we want to add, using

myList.Insert(2,"objectToAdd");

Page 13: Programming Using C#computingat.eeecs.qub.ac.uk/wp-content/uploads/2015/10/...6 | QUEEN’S UNIVERSITY BELFAST TASK 3: SUM OF AN ARRAY Often the elements of an array represent a series

12 | QUEEN’S UNIVERSITY BELFAST

Step 4: In this example we will use the Add method to add data to the end of the list. We will use

a for loop to add elements to the List until the counter has reached the value of the previously

declared variable randomNumber. Add the code in Figure 19:

Figure 19

Note: You now have successfully declared and initialised your List. All elements have also

been assigned a value. Your List size should have the same value as the previously

declared variable randomNumber but you can check this using the Count function.

Therefore to obtain how many elements are in an array we using Length and for a List we

use Count.

Step 5: Use a for loop to print out all of the data held in your List. Save your work (Ctrl+Shift+S), run

the program by clicking the start button on the toolbar or use the shortcut Ctrl+F5. You

should see output similar to Figure 20.

Figure 20

Page 14: Programming Using C#computingat.eeecs.qub.ac.uk/wp-content/uploads/2015/10/...6 | QUEEN’S UNIVERSITY BELFAST TASK 3: SUM OF AN ARRAY Often the elements of an array represent a series

13 | QUEEN’S UNIVERSITY BELFAST

TASK 2: CREATING A RANDOM LIST In this task we are going to explore the different ways of looping through a List and the different

results we can achieve. A List will be randomly filled with the values Triangle, Rectangle, Circle or

Square. This type of scenario can be useful for creating a bank of questions for a quiz.

Step 1: Create new Console Application project and name it P05E04Task02. Declare a String array

using the information in the variable declaration in Table 8

Name shapes

Data Type String

Size 4

Values Triangle, Rectangle, Circle, Square

Table 8

Step 2: Declare a List of type String, then generate a random number between 1 and 100. This will

be the number of items held in the List. Finally, declare an integer variable called

randomShapeSelection and assign it a random value between 0 and 4. This will be used to hold

the index of the shape that is randomly chosen from the shapeList array. Figure 21 provides you

with the code but try to work it out yourself first.

Figure 21

Step 3: Now we want to populate the List. To do this we will need a for loop which will select a

value (based on randomShapeSelection) from the array and place this String in the List. You will

then need a new random number for the randomShapeSelection variable. This loop will be

repeated for until there are a total of randomNumber elements in the List.

Step 4: Finally we will print out the values in the List however we will use a foreach statement this

time. A foreach statement is a short hand way to get access to each value of an array or list.

Type the code in Figure 22 to print out all values in the List.

Figure 22

Step 5: Save your work (Ctrl+Shift+S), run the program by clicking the start button on the toolbar

or use the shortcut Ctrl+F5. You should see output similar to Figure 23.

Figure 23