Download presentation
Presentation is loading. Please wait.
1
GCSE Computing:: Iteration (For Loops)
2
For Loops: Why we need them
Often in programming we need to repeat (or iterate) a number of times; Mostly, arrays are used in combination with For Loops to achieve this; The following would be good reasons for using iteration: Searching for a particular item in a list/array For example search for everyone with the surname Smith in a class. Creating real time repeated processes For example creating a clock that iterates through hours, minutes and seconds; Inputting and outputting data to and from a program For example reading in the names of students in a class with results and then outputting the grade they have achieved [Poor cartographer booklet]
3
Arrays: A different type of variable
Arrays allow you to store a set of variables in one place. Imagine you wanted to create an application to store a list of your predicted GCSE grades: Dim sGrades(99) as string sGrade(0) = “A” sGrade(1) = “B” sGrade(2) = “D” sGrade(3) = “C” sGrade(4) = “F” sGrade(5) = “D” sGrade(6) = “A” sGrade(7) = “B” Notice how only one declaration has to be made. An array could be created of variable type integer, string or anything else… Arrays can be used in For Loops to reduce the amount of code that needs to be written. [Poor cartographer booklet] A B D C F D A B 1 2 3 4 5 6 7
4
Loops: In practice A B D C F D A B 1 2 3 4 5 6 7
The following code reads the array that has been created and counts the number of values that are above a “C” grade: Dim sGrades(7) as String Dim iCount as Integer sGrade(0) = “A” sGrade(1) = “B” sGrade(2) = “D” sGrade(3) = “C” sGrade(4) = “F” sGrade(5) = “D” sGrade(6) = “A” sGrade(7) = “B” For i = 0 to 7 If sGrade(i) =“A*” OR sGrade(i) =“A” OR sGrade(i) =“B” OR sGrade(i) =“C” Then iCount = iCounter + 1 End If Next Msgbox “You are on track to achieve “ & iCount & “ grades at a C or above” A B D C F D A B 1 2 3 4 5 6 7
5
Loops: In practice Dim sNames(99) as string
The following code reads in a text file and stores the data in an array. The first uses a While Loop and the second uses a For Loop Dim sNames(99) as string Dim iCounter as integer OPEN "filename.txt" FOR INPUT as #1 While NOT Eof(1) LINE INPUT #1, sNames(iCounter) iCounter = iCounter + 1 Wend Close #1
6
For Loops: In practice Dim iCounter as Integer
The following code takes searches through the array and counts the number of students with the name “Sophie” Dim iCounter as Integer For I = 1 to 10 If sName(i) = “Sophie” then iCounter = iCounter + 1 End if Next Msgbox “There are “ & iCounter & “ students with the name Sophie”
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.