19.04.2017 Views

Learn to Program with Small Basic

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Igpay Atinlay<br />

Let’s teach the computer a language game called pig latin. The rules for<br />

creating pig latin words are simple. To convert a word in<strong>to</strong> pig latin, move<br />

the first letter <strong>to</strong> the end and add the letters ay after it. So, the word talk<br />

becomes alktay, fun becomes unfay, and so on. Can you decipher the original<br />

title of this section?<br />

Figure 18-5 shows the strategy you’ll use <strong>to</strong> convert a word in<strong>to</strong> pig<br />

latin, using the word basic.<br />

Input<br />

b<br />

Output<br />

a s i c<br />

<br />

<br />

<br />

a s i c b a y<br />

<br />

<br />

<br />

Extract substring (from letter 2<br />

<strong>to</strong> the end) and assign it <strong>to</strong> the<br />

output string.<br />

Append the first letter <strong>to</strong> the<br />

output string.<br />

Append ay <strong>to</strong> the output<br />

string.<br />

Figure 18-5: Translating an English word in<strong>to</strong> pig latin<br />

You first extract the substring from the second character <strong>to</strong> the end and<br />

assign it <strong>to</strong> the output string. You then add the first letter in the input string<br />

<strong>to</strong> the output, followed by ay. Enter the code in Listing 18-7 <strong>to</strong> implement<br />

these steps.<br />

1 ' PigLatin.sb<br />

2 TextWindow.Title = "Pig Latin"<br />

3<br />

4 While ("True")<br />

5 TextWindow.Write("Enter a word: ")<br />

6 word = TextWindow.Read()<br />

7<br />

8 pigLatin = Text.GetSubTextToEnd(word, 2) ' Gets characters 2 <strong>to</strong> end<br />

9 pigLatin = pigLatin + Text.GetSubText(word, 1, 1) ' Appends first character<br />

10 pigLatin = pigLatin + "ay" ' Appends "ay"<br />

11 TextWindow.WriteLine(pigLatin) ' Displays the output<br />

12 TextWindow.WriteLine("")<br />

13 EndWhile<br />

Listing 18-7: Converting a word entered by the user in<strong>to</strong> pig latin<br />

The program runs an infinite loop <strong>to</strong> allow the user <strong>to</strong> try different<br />

words (line 4). After reading the input word from the user (line 6), we<br />

extract the substring that starts at position 2 (that is, from the second<br />

character <strong>to</strong> the end of the input word) and assign it <strong>to</strong> pigLatin. Then we<br />

extract the first letter from word and append it <strong>to</strong> pigLatin (line 9), followed<br />

by ay (line 10). We display the pig latin word (line 11), followed by an empty<br />

line (line 12) and go for another round. Ongratulationscay! Ouyay inishedfay<br />

ouryay rogrampay!<br />

276 Chapter 18

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

Saved successfully!

Ooh no, something went wrong!