Download presentation
Presentation is loading. Please wait.
1
1D Arrays Defining, Declaring & Processing
14/01/2019
2
Learning Objectives Define an array and an element.
Explain why arrays are useful and so when they should be used. State how to declare an array. State how to process an array i.e. use it (store or retrieve data). Write program code to process array data including: Searching using a linear search. Sorting using a bubble sort. 14/01/2019
3
What is an Array? A data structure that stores as many items as required using a single variable. All items must be of the same data type. e.g. An array of integers. An array of strings. … A list box is an example of an array. A storage ‘slot’ in an array is called an element e.g. 1 2 3 4 56 78 42 80 65 14/01/2019 Note that the 1st element is numbered 0.
4
Why use arrays? To store a single number you would declare one integer variable. To store 3 numbers you would need 3 variables. Clearly declaring tens, hundreds, etc… of variables is difficult and this why arrays are used. 14/01/2019
5
How to declare an array? Similar to variables. Dim …(…) As …
Array name Data Type The number of elements required. 14/01/2019
6
Processing an Array e.g. ExamMarks(3) = Mark …(…) =
Array Name A number or a variable (with a stored number) representing the required element. e.g. ExamMarks(3) = Mark Will store the contents of the Mark variable in the 4th element of the ExamMarks array. 14/01/2019 Note that the 1st element is numbered 0.
7
Initialising an array ‘Arrays may contain values from previous
‘processing. If they do then programs will use ‘this data and give incorrect results. Loop through each array element from element 1 to the last element. FOR Index = 0 TO 25 ‘LastElement e.g. 26 letters of the alphabet. Letters(Index) = 0 ‘Place a zero in all array elements NEXT Note that the 1st element is numbered 0. 14/01/2019
8
Program 5.1a Number Array Specification:
Allow the user to enter up to 5 non-zero numbers and store them in an array. Then display: The contents of the array. The sum total of the contents. The highest and lowest numbers in the array. The range of the numbers (Highest – Lowest). Then ask the user to search for a number. Either display the element it was found in or a “Number not found” message. Then ask the user if they wish to search for another number. Then ask the user if they wish to: Reset (and start again). Exit.
9
Program 5.1a Number Array Go back to Election Program
‘Declare an array for 5 numbers. Dim Numbers(5) As Integer ‘Will be used to represent each element of the array. Dim Index As Integer ‘Will be used to store each number entered. Dim Number As Integer ‘Will be used determine if the user wishes to enter numbers. Dim EnterAnotherNumber As Boolean ‘Will be used the number the user wishes to search for. Dim SearchNumber As Integer ‘Will be used determine if a number is found. Dim NumberFound As Boolean ‘Will be used determine if the user wishes to “Reset”, “Search” or “Exit”. Dim Request As String Dim Total As Integer ‘Will be used to store the total of all 5 numbers. Dim Highest As Integer ‘Will be used to store the highest number. Dim Lowest As Integer ‘Will be used to store the lowest number. Dim Range As Integer ‘Will be used to store the range (Highest – Lowest). Go back to Election Program
10
Program 5.1a Number Array Do Index = 0 NumberFound = False
Console.WriteLine(“Enter a number.”) Number = Console.ReadLine ‘Store the number entered. ‘ ‘Store the number in the next element of the array. Numbers(Index) = Number ‘Increment How Many Numbers to move to the next element of the Numbers array. Index = Index + 1 If Index > 4 Then ‘Is array full? Console.WriteLine(“The array is FULL!”) ‘Inform user array is full! Else Console.WriteLine(“Do you wish enter another number (True/False)?”) EnterAnotherNumber = Console.ReadLine End If Loop Until Index > 4 Or EnterAnotherNumber = False Go back to Election Program
11
Program 5.1a Number Array Console.WriteLine(“The contents of the array:”) For Index = 0 To 4 'Go through and display each element of the array. Console.WriteLine(Numbers(Index)) Next Index For Index = 0 To 4 'Go through each element of the array. Total = Total + Numbers(Index) ‘Running total of each number. If Index = 0 Then ‘The 1st number is both the lowest and highest. Lowest = Numbers(Index) Highest = Numbers(Index) ‘Compare each number to the lowest and highest so far and change accordingly. ElseIf Numbers(Index) < Lowest Then Lowest = Numbers(Index) ‘Set new lowest number. ElseIf Numbers(Index) > Highest Then Highest = Numbers(Index) ’Set new highest number. End If Range = Highest - Lowest Go back to Election Program
12
Program 5.1a Number Array Console.WriteLine(“The Total is: “ & Total)
Console.WriteLine(“The Highest number is: “ & Highest) Console.WriteLine(“The Lowest number is: “ & Lowest) Console.WriteLine(“The Range number is: “ & Range) 12 Go back to Election Program 12
13
Program 5.1a Number Array Do
Console.WriteLine(“Enter a number to search for.”) SearchNumber = Console.ReadLine 'Go through each element in the array to search for the number required. For Index = 0 To 4 ‘Has the number been found? If Numbers(Index) = SearchNumber Then Console.WriteLine(“The number “ & SearchNumber & “ is in element " & Index & " of the ‘Numbers’ array.“) NumberFound = True End If ‘Keep looking until all 5 elements have been searched. Next Index ‘If the number was not found display a suitable message. If NumberFound = False Then Console.WriteLine(“The number " & SearchNumber & " has not been found in the ‘Numbers’ array.”) Go back to Election Program
14
Program 5.1a Number Array Loop Until Request = “Exit” ’Exit?
Console.WriteLine(“Do you wish to ‘Search’ again, ‘Reset’ or ‘Exit’?”) Request = Console.ReadLine Loop Until Request <> “Search” ‘Search again or continue. Loop Until Request = “Exit” ’Exit? Go back to Election Program
15
Program 5.1a Number Array Run the program and test it. 14/01/2019
16
Program 5.1a Number Array Did you notice a problem? 14/01/2019
17
Program 5.1a Number Array Did you notice a problem?
What happens if you enter less than 5 numbers? 14/01/2019
18
Program 5.1a Number Array Did you notice a problem?
What happens if you enter less than 5 numbers? e.g. 14/01/2019
19
Program 5.1a Number Array Add an extra variable declaration at the beginning: Dim HowManyNumbers As Integer After the 1st Do … Loop Until which ends: Loop Until Index > 4 Or EnterAnotherNumber = False ‘Look for the rogue value 0. Do While Numbers(HowManyNumbers) <> 0 HowManyNumbers += 1 Loop Then change each For … To … Next loop to end at this variable value: e.g. For Index = 0 To HowManyNumbers - 1 There is at least one other way to deal with this but that way will not fully demonstrate the need to initialise the array – see next few slides. Also that way will leave unused values in the array which is not considered good style as it may potentially cause problems. This will hopefully become clearer after the next few slides. Go back to Election Program
20
Program 5.1a Number Array Now: What happens? What should happen?
Enter 5 numbers. Check the contents, total, highest and lowest displayed. Search for a number entered and check response. Reset. Enter 2 new numbers (different from last time). Check the contents, total, highest and lowest being displayed. Search for a number entered last time but not this time, and check response. What happens? What should happen? Why does this happen? 14/01/2019 20
21
Initialising an array Loop Until Continue = “Exit” ’Exit?
Add the following code in before the last Loop Until statement. Loop Until Request <> “Search” ‘Search again or continue. If Request = “Reset” Then ‘Reset? ‘Arrays may contain values from previous processing. If they do then programs will use this data and give incorrect results. Loop through each array element from element 1 to the last element. For Index = 0 To 4 Numbers(Index) = 0 ‘Place a zero in all array elements. Next Index HowManyNumbers = 0 ‘Reset HowManyNumbers. ‘ Other variables will also need to be reset. I will leave you to ‘consider which ones! End If Loop Until Continue = “Exit” ’Exit? Go back to Election Program 14/01/2019
22
Program 5.1a Number Array Run the program and test it. 14/01/2019
23
Animated in full screen.
Bubble Sort Animated in full screen. "Bubble-sort-example-300px" by Swfung8 - Own work. Licensed under CC BY-SA 3.0 via Wikimedia Commons - Starting from the beginning of the list, compare every adjacent pair, swap their position if they are not in the right order (the latter one is smaller than the former one). After each iteration, one less element (the last one) is needed to be compared until there are no more elements left to be compared. 14/01/2019
24
Program 5.1a Number Array Bubble Sort Extension
Animated in full screen. Extension: Before displaying the array ask the user if they wish to sort it. If so, write code to sort the array using the bubble sort method demonstrated on the previous slide. Try to do this independently but if you need hints, there are some on the next 2 slides. 14/01/2019
25
Program 5.1a Number Array Bubble Sort Extension Hints:
Swapping: Use a “temporary” variable to store one of the values to be swapped (e.g. LeftValue, RightValue, Temp, etc…), then make one element equal to the other and the other equal to the “temporary variable”. e.g. Array[Index] = Array[Index+1] Array[Index+1] = RightValue Use two nested loops: Outer loop controls the number of passes which can be either: A For To Next Step -1. Inefficiently sorting right up until the final pass of the first 2 elements even if it is not needed . A not so unordered list may become sorted before this. Steps down so that the inner loop can use its counter to drop the number of comparisons in each pass. Or A Do Loop Until: With a Boolean variable in the inner loop to note if swaps are made or not, so that the sort can stop when the array is sorted . A not so unordered list may become sorted before the absolute final pass of the first 2 elements. Inner loop should be a For To Next loop which controls the number of comparisons in each pass. Animated in full screen. 14/01/2019 Again try to code the Bubble sort with just this information but there are 2 pseudocode solutions on the next slide if you need them. 25
26
Bubble Sort Pseudocode
NoSwaps = True For Index ← StartIndex To LastIndex - 1 If List[Index] > List[Index + 1] Then Temp ← List[Index] List[Index] ← List[Index + 1] List[Index + 1] ← Temp NoSwaps = False End If End For NumberOfItems = NumberOfItems - 1 Loop Until NoSwaps = True Solution 1 (more efficient – see last slide): Animated in full screen. For End ← LastIndex - 1 To StartIndex Step - 1 For Index ← StartIndex To End If List[Index] > List[Index + 1] Then Temp ← List[Index] List[Index] ← List[Index + 1] List[Index + 1] ← Temp End If End For Solution 2:
27
Commenting on Arrays For presentations 5.1 & 5.2 I will only ask for comments to arrays. Your comments MUST explain: What does the array hold? And if it is important: How many elements and why this number? And when it is being used: What are you storing in/retrieving from the array and why? When (after and before what) are you doing this and why does it have to be done there?
28
Extension 5.1b Marks Array
Make a copy of the previous guided program “5a Number Array” and change it so that it deals with exam marks out of 100 (not just any numbers). Add in the following features: Allow automatic random marks which stops duplicate marks. Display the number of marks entered. Display the “average” of the marks entered. Hints: See next slide. 14/01/2019 28 28
29
Extension 5.1b Marks Array
Hints: The name of the array will need to be changed e.g. Marks. You will no longer be able to reset all elements of the array to 0, as 0 is a possible mark (e.g. -1 as this is not a valid mark) and you will need to move the reset loop to the beginning of the first loop. Use a boolean array (e.g. NumberGenerated) with upper bound 100. FALSE – indicates the number has not yet been generated. TRUE – indicates the number has been generated. For example, the array cell with subscript 37 indicates whether or not the number 37 has already been generated. 14/01/2019
30
Extension “Election” Program 5.1c
A town election is held to elect a new mayor. The people in the town can vote for whoever they prefer from the three candidates A, B, C. The voting is done by each voter typing A, B and C. This acts as input to a computer program. The software should assume that there are a maximum number of 1000 people who will be voting (don’t worry you will not be asked to test 1000 votes but set it up so that it would accept 1000 votes). It uses an array, Votes() to store the votes that are cast. Votes() is an array of 1000 characters: A, B or C. A second array, CandidateTotals(), contains 3 integers and is used with the array, Votes(). Write this program and when Voting is finished, the winner should be displayed. Make sure the program can deal correctly with two or three of the candidates receiving equal votes. Allow voting to be reset and initialise each element of each array. 14/01/2019 See next slides for some hints!
31
Extension “Election” Program 5.1c
Declare two arrays Votes(….) & CandidateTotals(….). See the introduction slide of this extension program for the numbers to use in (….) – in red. Compare with the Program 5a Number Array (slide 9 of this presentation). Declare an “Index” variable to loop through arrays. Add each vote to the Votes(….) array. Compare with the “entering of numbers” in Program 5a Number Array (slide 10 of this presentation).
32
Extension “Election” Program 5.1c
When Voting is finished search the Votes(….) array for each vote (A, B or C). Place totals in the CandidateTotals(….) array. CandidateTotals(1) for how many A’s, CandidateTotals(2) for how many B’s and ….. Compare with the “searching” of Program 5a Number Array (slides of this presentation). However, you are no longer searching for a number entered by the user but first for “A”, then for “B” and then for “C”. Use three separate If’s for “A”, “B” and “C”. For example if a “A” is found then increment CandidateTotals(1): CandidateTotals(1) = CandidateTotals(1) + 1 Remember you are searching the Votes(….) array and incrementing the appropriate element of the CandidatesTotals array(….) when a “A”, “B” or “C” is found.
33
Extension “Election” Program 5.1c
Compare the totals and declare the winner. CandidateTotals(1) for how many A’s, CandidateTotals(2) for how many B’s and ….. Make sure you enable a “Reset”. Compare with the “Reset” of the Program 5a Number Array (slide 16 of this presentation).
34
Extension “Letter Tally” Program 5.1d
Write a program which will keep a tally of the number of times each letter appears in a given text (can copied and pasted in). Use an array of size 26 to store the totals for each letter. Make sure you initialise each element of the array. 14/01/2019 See next slides for some hints!
35
Extension “Letter Tally” Program 5.1d
Obviously use a loop with a Mid function to extract letter by letter from the text entered. Then the long manual way would be to: If Character = “a” Then Letters (1) = Letters (1) + 1 ElseIf Character = “b” Then Letters (2) = Letters (2) + 1 and so on…. However, this is not efficient and is not the approach exams are really expecting. See the next slide. 14/01/2019 35 35
36
Extension “Letter Tally” Program 5.1d
Use the Asc function to subtract the ASCII code of “a” from the ASCII code of each letter. The difference + 1 will tell you which element of the Letters(….) array to use. CharacterIndex = ASC(Character)-ASC(“a”) + 1 Letters(CharacterIndex) = Letters(CharacterIndex) + 1 Notes: Make sure you include a reset button. This does not deal with capitals, if you have time try to see if you can get the program to do so. Continued on the next slide.
37
Extension “Letter Tally” Program 5.1d
To display, the long manual way would be to: Console.WriteLine(“Letter Tally:”) Console.WriteLine(“a: ” & Letters(1)) Console.WriteLine(“b: ” & Letters(2)) Console.WriteLine(“c: ” & Letters(3)) … However, a quicker way: For Index = 1 To 26 ’The ASCII code for a is 97, b is 98, etc… ‘ChrW will treat each number as an ASCII code and convert it to its corresponding letter, thereby avoiding manually writing a, b, c, etc… Console.WriteLine(ChrW(96 + Index) & “: ” & Letters(Index)) Next Index
38
Extension Program 4.2e – “Encryption”
A student writes some code which uses ASCII character codes. Continued on the next slide.
39
Extension Program 4.2e – “Encryption”
The student is interested in how simple encryption could be applied to a text message. One of the simplest forms of encryption is a method of ‘substitution’ where each character has a unique substitute character. The student uses this method with the following character substitutions: Continued on the next slide.
40
Extension Program 4.2e – “Encryption”
Using the identifiers above write this program to input a message string and output the encrypted string.
41
Extension Program 4.2f – “Encryption2”
Actually: Searching the Alphabet array can be avoided as the ASCII codes for the letters are in sequence. e.g. the index position for any character is; ASC(<char>)-64 Please make a copy of the previous “Encryption” program’s folder and name the new folder “Encryption2”. Then change it so that searching the Alphabet array is avoided as described above.
42
Plenary What is an array and an element? Element:
A data structure that stores as many items as required using a single variable. Element: A storage ‘slot’ in an array. Why arrays are useful and so when they should be used? Useful because they avoid the need to declare a variable for each item of data. Should be used when you want to store more than a few items of data of the same type. 14/01/2019
43
Plenary How do we declare an array? 14/01/2019
44
How to declare an array? Similar to variables. Dim …(…) As …
Array name Data Type The number of elements required. 14/01/2019
45
Plenary How do we process an array i.e. use it (store or retrieve data)? How are array elements numbered? 14/01/2019
46
Processing an Array …(…) = e.g. ExamMarks(3) = Mark
Array Name A number or a variable (with a stored number) representing the required element. e.g. ExamMarks(3) = Mark Will store the contents of the Mark variable in the 3rd element of the ExamMarks array. 14/01/2019
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.