Seemingly long and repetitive tasks can be very simple with the If and For commands
A good program is able to perform different tasks depending on certain conditions and this is normally the job of the If command. Another common use for programs is to perform the same task several times. This is known as looping and one of the most common commands is For.
Decisions with If
Just like Excel an If command consists of a statement followed by instructions of what to do if that statement is true. This should then be followed by the word Else and then another command to do if the first statement isn't true. Several conditions can be added by using the ElseIf command. Regardless of how many conditions there are, there should always be the EndIf command after the last condition to tell Small Basic that the If command has ended. Thus:
If trafficLights = "red" Then
ElseIf trafficLights = "yellow" Then
Looping with For
Sometimes a program needs to perform a repetitive task. Creating a loop allows you to make this a simple task. A very simple loop that creates the two times table looks like this
For i = 1 To 10
TextWindow.WriteLine(i * 2)
Looping is particularly useful when working with arrays as it offers a quick way to work with each variable stored in them. For example you can print every month name in a week array.
day = "Sunday"
day = "Monday"
day = "Tuesday"
day = "Wednesday"
day = "Thursday"
day = "Friday"
day = "Saturday"
For i = 1 To 7
This is only useful if you already know the number of variables stored in the array. This is where the section about Objects starts to become very useful. Because the Array is an object we can access information about it that is created automatically. Change the first line in the example above to
For i = 1 To Array.GetItemCount(day)
And try deleting or adding to the week list. This loop will always work no matter how many variables are stored in the array.
Updating your subscription status