Using Arrays to store month names and output this month.
The program above sets up an array called ‘MonthName’ with 12 elements. These elements have index values from 1 to 12. The program then makes use of the Clock object to find out the number of the current month. This is assigned to the variable ‘MonthNumber’. This variable is then used to extract the correct element from the array and display a statement on the screen.
Although this might seem like a lot of programming for a simple task, it is an important aspect of developing your programming skills. One variable contains 12 different values; it could just as easily contain 12000 different values, the program could still function. Later you will learn how to assign all these values more efficiently.
Using a loop to access an array
This is the same program as before but it has now been modified to use a loop to access each element of the array. The loop ‘iterates‘ through each element of the array and prints 12 simple statements on the TextWindow – Month No ‘x’ is ‘MonthName[x]’. Whenever we use an array, the chances are we will also use a loop to access it. The next tab shows this in action again…
Create the program and save it.
Code to collect the number of days in each month.
This program shows how, once the initial array has been created, a second array can be created as the program runs providing additional information about each month. In this case, the program asks the user to enter the number of days in each month.
Notice the use of prompts (using TextWindow.Write() to make sure that the cursor stays on the same line as the prompt. Also notice that I add an extra space at the end of the prompt to make sure it is clear. I also use TextWindow.ReadNumber() to make sure that I get numerical answers.
Create this program and save it.