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.
Read more: Programming articles | Small Basic articles
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
TextWindow.WriteLine("Stop")
ElseIf trafficLights = "yellow" Then
TextWindow.WriteLine("Get ready")
Else
TextWindow.WriteLine("Go!")
EndIf
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)
EndFor
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[1] = "Sunday"
day[2] = "Monday"
day[3] = "Tuesday"
day[4] = "Wednesday"
day[5] = "Thursday"
day[6] = "Friday"
day[7] = "Saturday"
For i = 1 To 7
TextWindow.WriteLine(day[i])
EndFor
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.
Article tags
Related articles
Content Recommendation
Q.Why is Windows Backup skipping files?
Q.Why do my scanned documents display gibberish?
Q.How can I convert MTS files to edit in Windows Movie...
Updating your subscription status