19.04.2017 Views

Learn to Program with Small Basic

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Going Interactive<br />

Let’s explore how <strong>to</strong> get the students’ scores from the user rather than<br />

hardcoding them <strong>with</strong>in the program like we did in Listing 17-3. We’ll use<br />

two loops <strong>to</strong> iterate over the students’ names and subjects, as shown in the<br />

following pseudocode (you’ll learn how <strong>to</strong> translate this pseudocode in<strong>to</strong><br />

real code in a moment):<br />

For each student in the array: [Scott, Jean, Logan]<br />

For each subject in the array: [Math, Science, Combat]<br />

score[student][subject] = read score from user<br />

EndFor<br />

EndFor<br />

You can save the names of the students in a one-dimensional array,<br />

save the names of the subjects in another one-dimensional array, and then<br />

use nested For loops <strong>with</strong> integer indices <strong>to</strong> access the individual elements<br />

of these two arrays. Then you can use the strings (student name and subject)<br />

as indices for a score matrix. Check out Listing 17-4 <strong>to</strong> see the code in<br />

action.<br />

1 ' StudentAvg2.sb<br />

2 nameList = "1=Scott;2=Jean;3=Logan;"<br />

3 subjList = "1=Math;2=Science;3=Combat;"<br />

4<br />

5 For I = 1 To 3 ' Three students<br />

6 name = nameList[I] ' Name of the Ith student<br />

7 For J = 1 To 3 ' Three subjects<br />

8 subj = subjList[J] ' Name of Jth subject<br />

9 TextWindow.Write(name + "'s " + subj + " score: ")<br />

10 score[name][subj] = TextWindow.ReadNumber()<br />

11 EndFor<br />

12 EndFor<br />

13 TextWindow.Write("Enter student name: ")<br />

14 name = TextWindow.Read()<br />

15 sum = score[name]["Math"]<br />

16 sum = sum + score[name]["Science"]<br />

17 sum = sum + score[name]["Combat"]<br />

18 avg = Math.Round(sum / 3)<br />

19 TextWindow.WriteLine(name + " average score = " + avg)<br />

Listing 17-4: Reading scores from the user<br />

The program starts by creating the name and subject arrays (lines 2–3).<br />

Then a nested loop starts <strong>to</strong> fill the score matrix. The outer loop iterates<br />

over the students, and the inner loop iterates over the subjects.<br />

The outer loop starts <strong>with</strong> I = 1. Here name gets assigned <strong>to</strong> nameList[1],<br />

which is "Scott" (line 6). Then the inner loop runs three times, the first<br />

time <strong>with</strong> J = 1, and subject gets assigned <strong>to</strong> subjList[1], which is "Math"<br />

248 Chapter 17

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!