Download presentation
Presentation is loading. Please wait.
Published byAugust Pierce Clark Modified over 9 years ago
1
04/11/20151 5.1 Arrays 1D Arrays Defining, Declaring & Processing
2
204/11/2015 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. Searching using a linear search. Sorting using a bubble sort. Sorting using a bubble sort.
3
304/11/2015 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. All items must be of the same data type.e.g. An array of integers. An array of integers. An array of strings. An array of strings. … A list box is an example of an array. A list box is an example of an array. A storage ‘slot’ in an array is called an element e.g. A storage ‘slot’ in an array is called an element e.g. 5678428065 12345
4
404/11/2015 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.
5
504/11/2015 How to declare an array? Similar to variables. Dim …(…) As … Array name The number of elements required. Data Type
6
604/11/2015 Processing an Array …(…) = Array Name A number or a variable (with a stored number) representing the required element. e.g. ExamMarks(3) = Mark e.g. ExamMarks(3) = Mark Will store the contents of the Mark variable in the 3 rd element of the ExamMarks array. Will store the contents of the Mark variable in the 3 rd element of the ExamMarks array.
7
704/11/2015 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 = 1 TO 26 ‘ LastElement e.g. 26 letters of the alphabet. Letters(Index) = 0 ‘Place a zero in all array elements Letters(Index) = 0 ‘Place a zero in all array elementsNEXT
8
8 Program 5.1a Number Array Specification: Allow the user to enter up to 5 numbers and store them in an array. Allow the user to enter up to 5 numbers and store them in an array. Then display: 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. 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: Then ask the user if they wish to: Reset (and start again). Exit.
9
9 Program 5.1a Number Array ‘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 Go back to Election Program
10
10 Program 5.1a Number Array Do Index = 1 Index = 1 NumberFound = False NumberFound = False Do Do 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 = 5 Then ‘Is array full? Console.WriteLine(“The array is FULL!”) ‘Inform user array is full! Console.WriteLine(“The array is FULL!”) ‘Inform user array is full!Else Console.WriteLine(“Do you wish enter another number (True/False)?”) Console.WriteLine(“Do you wish enter another number (True/False)?”) EnterAnotherNumber = Console.ReadLine EnterAnotherNumber = Console.ReadLine End If Loop Until Index = 5 Or EnterAnotherNumber = False Loop Until Index = 5 Or EnterAnotherNumber = False Go back to Election Program Go back to Election Program
11
11 Program 5.1a Number Array Console.WriteLine(“The contents of the array:”) Console.WriteLine(“The contents of the array:”) For Index = 1 To 5 'Go through and display each element of the array. For Index = 1 To 5 'Go through and display each element of the array. Console.WriteLine(Numbers(Index)) Next Index Next Index For Index = 1 To 5 'Go through each element of the array. For Index = 1 To 5 'Go through each element of the array. Total = Total + Numbers(Index) ‘Running total of each number. If Index = 1 Then ‘The 1 st number is both the lowest and highest. Lowest = Numbers(Index) Lowest = Numbers(Index) Highest = 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. Lowest = Numbers(Index) ‘Set new lowest number. ElseIf Numbers(Index) > Highest Then Highest = Numbers(Index) ’Set new highest number. Highest = Numbers(Index) ’Set new highest number. End If Next Index Next Index Range = Highest - Lowest Range = Highest - Lowest Go back to Election Program Go back to Election Program
12
12 Program 5.1a Number Array Console.WriteLine(“The Total is: “ & Total) Console.WriteLine(“The Total is: “ & Total) Console.WriteLine(“The Highest number is: “ & Highest) Console.WriteLine(“The Highest number is: “ & Highest) Console.WriteLine(“The Lowest number is: “ & Lowest) Console.WriteLine(“The Lowest number is: “ & Lowest) Console.WriteLine(“The Range number is: “ & Range) Console.WriteLine(“The Range number is: “ & Range) Go back to Election Program Go back to Election Program
13
13 Program 5.1a Number Array Do 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 = 1 To 5 ‘Has the number been found? ‘Has the number been found? If Numbers(Index) = SearchNumber Then If Numbers(Index) = SearchNumber Then Console.WriteLine(“The number “ & SearchNumber & “ is in element " & Index & " of the ‘Numbers’ array.“) NumberFound = True End If End If ‘Keep looking until all 5 elements have been searched. ‘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.”) Console.WriteLine(“The number " & SearchNumber & " has not been found in the ‘Numbers’ array.”) End If Go back to Election Program Go back to Election Program
14
14 Program 5.1a Number Array 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 <> “Search” ‘Search again or continue. Loop Until Request = “Exit” ’Exit? Go back to Election Program Go back to Election Program
15
1504/11/2015 Program 5.1a Number Array Run the program and test it.
16
1604/11/2015 Program 5.1a Number Array Now: 1.Enter 5 numbers. 2.Check the contents, total, highest and lowest displayed. 3.Search for a number entered and check response. 4.Reset. 5.Enter 2 new numbers (different from last time). 6.Check the contents, total, highest and lowest being displayed. 7.Search for a number entered last time but not this time, and check response. What happens? What should happen? Why does this happen?
17
Add the following code in before the last Loop Until statement. Loop Until Request <> “Search” ‘Search again or continue. 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. ‘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 = 1 To 5 For Index = 1 To 5 Numbers(Index) = 0 ‘Place a zero in all array elements. Next Index Next Index End If Loop Until Continue = “Exit” ’Exit? 17 04/11/2015 Initialising an array Go back to Election Program Go back to Election Program
18
1804/11/2015 Program 5.1a Number Array Run the program and test it.
19
Bubble Sort 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. 1904/11/2015 "Bubble-sort-example-300px" by Swfung8 - Own work. Licensed under CC BY-SA 3.0 via Wikimedia Commons - http://commons.wikimedia.org/wiki/File:Bubble- sort-example-300px.gif#/media/File:Bubble-sort- example-300px.gif http://commons.wikimedia.org/wiki/File:Bubble- sort-example-300px.gif#/media/File:Bubble-sort- example-300px.gif http://commons.wikimedia.org/wiki/File:Bubble- sort-example-300px.gif#/media/File:Bubble-sort- example-300px.gif Animated in full screen.
20
2004/11/2015 Program 5.1a Number Array Bubble Sort Extension Extension: Before displaying the array ask the user if they wish to sort it. 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. If so, write code to sort the array using the bubble sort method demonstrated on the previous slide. http://commons.wikimedia.org/wiki/File:Bubble-sort-example- 300px.gif#/media/File:Bubble-sort-example-300px.gif http://commons.wikimedia.org/wiki/File:Bubble-sort-example- 300px.gif#/media/File:Bubble-sort-example-300px.gif Try to do this independently but if you need hints, there are some on the next 2 slides. Try to do this independently but if you need hints, there are some on the next 2 slides.
21
04/11/2015 Program 5.1a Number Array Bubble Sort Extension Hints: http://commons.wikimedia.org/wiki/File:Bubble-sort-example-300px.gif#/media/File:Bubble-sort-example-300px.gif 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”. 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. 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: 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. 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. 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. 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. Inner loop should be a For To Next loop which controls the number of comparisons in each pass. 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.
22
22 Bubble Sort Pseudocode For End ← NumberOfItems - 1 To 1 Step - 1 For Index ← 1 To End For Index ← 1 To End If List[Index] > List[Index + 1] Then Temp ← List[Index] Temp ← List[Index] List[Index] ← List[Index + 1] List[Index] ← List[Index + 1] List[Index + 1] ← Temp List[Index + 1] ← Temp End If End For End For End For Solution 2: Do For Index ← 1 To NumberOfItems - 1 To 1 Step - 1 For Index ← 1 To NumberOfItems - 1 To 1 Step - 1 If List[Index] > List[Index + 1] Then Temp ← List[Index] Temp ← List[Index] List[Index] ← List[Index + 1] List[Index] ← List[Index + 1] List[Index + 1] ← Temp List[Index + 1] ← Temp NoSwaps = False NoSwaps = False End If End For End For Loop Until NoSwaps = True Solution 1 (more efficient – see last slide) :
23
Commenting on Arrays For presentations 5.1 & 5.2 I will only ask for comments to arrays.5.15.2 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? When in the procedure code or, if it is on its own, in which procedure (button, checkbox, textbox, etc…)?
24
2404/11/2015 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. Allow automatic random marks which stops duplicate marks. Display the number of marks entered. Display the number of marks entered. Display the “average” of the marks entered. Display the “average” of the marks entered.Hints: See next slide. See next slide.
25
2504/11/2015 Extension 5.1b Marks Array Hints: The name of the array will need to be changed e.g. Marks. The name of the array will need to be changed e.g. Marks. Use an array (e.g. NumberGenerated) with upper bound 100. Use an 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. 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. 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. You will need to write a loop to count how many marks entered e.g. declare a variable for storing how many marks (e,g, HowManyMarksEntered) and loop through the array until the rogue value (e.g. -1) is found. You will need to write a loop to count how many marks entered e.g. declare a variable for storing how many marks (e,g, HowManyMarksEntered) and loop through the array until the rogue value (e.g. -1) is found. There are actually number of ways this could be done though.
26
2604/11/2015 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. 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. See next slides for some hints!
27
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).9 Declare an “Index” variable to loop through arrays. Compare with the Program 5a Number Array (slide 9 of this presentation).9 Add each vote to the Votes(….) array. Compare with the “entering of numbers” in Program 5a Number Array (slide 10 of this presentation).10
28
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 11 - 12 of this presentation).1112 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.
29
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).16
30
3004/11/2015 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. See next slides for some hints!
31
3104/11/2015 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 If Character = “a” Then Letters (1) = Letters (1) + 1 ElseIf Character = “b” Then ElseIf Character = “b” Then Letters (2) = Letters (2) + 1 and so on…. and so on…. However, this is not efficient and is not the approach exams are really expecting. See the next slide. See the next slide.
32
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: 1. 1. Make sure you include a reset button. 2. 2. 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.
33
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: Console.WriteLine(“Letter Tally:”) For Index = 1 To 26 ’The ASCII code for a is 97, b is 98, etc… Console.WriteLine(ASC(96 + Index) & “: ” & Letters(Index)) ASCII += 1 Next Ctrl
34
Extension Program 4.2e – “Encryption” A student writes some code which uses ASCII character codes. Continued on the next slide.
35
Extension Program 4.2f – “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.
36
Extension Program 4.2f – “Encryption” Using the identifiers above write this program to input a message string and output the encrypted string.
37
Extension Program 4.2g – “Encryption 2 ” 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( )-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.
38
3804/11/2015 Plenary What is an array and an element? Array: Array: A data structure that stores as many items as required using a single variable. Element: 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. 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. Should be used when you want to store more than a few items of data of the same type.
39
3904/11/2015 Plenary How do we declare an array?
40
4004/11/2015 How to declare an array? Similar to variables. Dim …(…) As … Array name The number of elements required. Data Type
41
4104/11/2015 Plenary How do we process an array i.e. use it (store or retrieve data)? How are array elements numbered?
42
4204/11/2015 Processing an Array …(…) = Array Name A number or a variable (with a stored number) representing the required element. e.g. ExamMarks(3) = Mark e.g. ExamMarks(3) = Mark Will store the contents of the Mark variable in the 3 rd element of the ExamMarks array. Will store the contents of the Mark variable in the 3 rd element of the ExamMarks array.
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.