Студопедия

Главная страница Случайная страница

Разделы сайта

АвтомобилиАстрономияБиологияГеографияДом и садДругие языкиДругоеИнформатикаИсторияКультураЛитератураЛогикаМатематикаМедицинаМеталлургияМеханикаОбразованиеОхрана трудаПедагогикаПолитикаПравоПсихологияРелигияРиторикаСоциологияСпортСтроительствоТехнологияТуризмФизикаФилософияФинансыХимияЧерчениеЭкологияЭкономикаЭлектроника






Loops and Structured Data






" Loop" structures provide ways to methodically repeat actions, manage program flow, and automate lengthy data processing activities. Loops are often used to step through the individual items in a list of data.

8.1 While/Repeat and Do/Until

The " while" function repeatedly evaluates a block of code while the given condition is true. While loops are formatted as follows:

while (condition) block of functions to be executed while the condition is truerepeat

This example counts to 5:

x = 1 %create an initial counter value while x < = 5 print x x = x + 1repeat

In English, that code reads:

" x" initially equals 1 While x is less than or equal to 5: display the value of x then add 1 to the value of xRepeat

" Incrementing" counter values, as in the example above, is an extremely common technique in all types of programming. You'll see examples of it regularly in code, whenever you want to keep a count of items.

You can use While/Repeat to create forever repeating loops. Simply use an evaluation that is always true, and use the " wr.break" function to end the loop. Notice how the While loop and If evaluations are indented to clearly separate the logic:

print " Please wait 5 seconds...", 0, 0, 1alarmtime = clock() + 5000 while 1 = 1 % this is always true pause 1000 % wait 1 second if clock() = alarmtime print " 5 seconds have passed" % these lines are only executed if w_r.break % the clock time = the alarm time endifrepeat

Here's a more interactive version using some info provided by the user:

input " What do you want to be reminded of? ", eventname$input " Seconds to wait: ", secondsendtime = clock() * 1000 + secondstime y$, m$, d$, h$, n$, s$mytime$ = h$ + ": " + n$ + ": " + s$print " It's now " + mytime + ", and you'll be alerted in " + seconds + " seconds." while 1 = 1 pause 1000 if clock() = endtime print " It's now " + endtime + ", and " + seconds + " seconds have passed. It's time for: " + eventname$ w_r.break endifrepeat

" Do-Until" loops operate similarly to while-repeat loops, except they ensure that at least one iteration of the statements inside the loop is executed:

i = 1do print iuntil i = 1

This type of loop is often used to wait for keystrokes from the user:

do! This function gets the current keystroke: inkey$ k$! The " @" symbol is used to represent no key being pressed: if ((k$ < > " @") & (k$ < > " key 4")) then let done = 1 until done % if something other than no key, or key 4 is pressed, stopprint " You pressed the '" + k$ + " key."

Memorize the code above. You'll use it whenever you want to wait for a single keystroke from the user.

8.2 Looping Through Lists of Data: FOR

" FOR/Next" loops simply count through a range of numbers:

for i = 0 to 6 print inext

You can use conditional tests within a FOR loop, to perform different operations on each numbered item:

for i = 1 to 100 if ((mod(1, 3) = 0) and (mod(i, 5) = 0)) % mod checks the remainder print " fizzbuzz" % of a division operation elseif mod(i, 3) = 0 print " fizz" elseif mod(i, 5) = 0 print " buzz" else print i endifnext i

You can use the sequential counting ability of FOR loops to pick sequential items from an array or a list using numbered indexes:

! This creates a new list, labeled by the variable " months": list.create s, monthslist.add months, " January", " February", " March", " April", " May", " June" ~ " July", " August", " September", " October", " November", " December"! This gets the number of elements in the months list, and stores that! value in the variable " size" list.size months, size! This loop counts from 1 to the number of items in the list, and does! something with each item in the list: for i = 1 to size! This picks the numbered index item from the list, and assigns that! item to the variable " m$": list.get months, i, m$! This prints some concatenated text, using the string above: print " Month " + str$(i) + ": " + m$ next i

The " Step" option of a FOR loop allows you to skip a given number of items, each time through the loop:

for i = 0 to 12 step 3 % skip to every third number print inext i

And to count backwards:

for i = 5 to 1 step -1 % start on 5, end on 1, subtract 1 print i % each time through the loopnext iprint " Blast off! "

" Step" is especially useful because it allows you to skip items in an array or list:

list.create s, monthslist.add months, " January", " February", " March", " April", " May", " June" ~ " July", " August", " September", " October", " November", " December" list.size months, size! Count from 1 to the last item in the list, skipping by 3: for i = 1 to size step 3 list.get months, i, m$ % pick every 3rd item print " Month " + str$(i) + ": " + m$ % and print itnext i

This technique is especially useful when creating and using lists of structured data. For example, the following list contains three fields of data for each person (name, address, and phone), in consecutive order. Pay particular attention to how the FOR/Next/Step loop is used to pick out blocks of 3 consecutive pieces of data from the list:

list.create s, myuserslist.add myusers, " John Smith", " 123 Tine Ln. Forest Hills NJ", " 555-1234" ~ " Paul Thompson", " 234 Georgetown Pl. Peanut Grove AL", " 555-2345" ~ " Jim Persee", " 345 Pickles Pike Orange Grove FL", " 555-3456" ~ " George Jones", " 456 Topforge Court Mountain Creek CO", " " ~ " Tim Paulson", " ", " 555-5678" print " All users: " print " " list.size myusers, size for i = 1 to size step 3! Pick and print the item at the current index (every 3rd field, name) list.get myusers, i, n$ print " Name: " + n$! Pick and print the item at the next index (current index + 1, address) list.get myusers, i+1, a$ print " Address: " + a$! Pick and print the item 2 after the current index (index + 2, phone) list.get myusers, i+2, p$ print " Phone: " + p$ print " " next i

The code pattern above is very useful when creating data management apps. Little data lists such as the one above can hold all sorts of useful related blocks of data (phone books, recipes, etc.). You can group different fields of data sequentially, and read any selected field of information from any record using a FOR/Next/Step loop.

You can also use FOR loops to alter specific fields of data in a list. The following example checks each phone number field in the myusers list (every third item in the list, starting with the third item. If any phone field is empty, it changes that field to " 000-000-0000":

for i = 3 to size step 3 list.get myusers, i, m$ if m$ = " " list.replace myusers, i, " 000-000-0000" endifnext i

8.3 Choosing Items From Lists - The " Select" Function

RFO Basic has a built in " select" function to allow users to easily choose from items in a list. It takes 3 parameters:

1) A return parameter that holds the index number of the item selected by the user

2) The variable label that refers to the list

3) A text message to display to the user. The text message is shown on top of the select screen, and also displayed quickly in a popup box. If the text message is left blank (the empty quotes string " "), then no popup message occurs:

list.create s, monthslist.add months, " January", " February", " March", " April", " May", " June" ~ " July", " August", " September", " October", " November", " December"! Allow the user to select an item from the list: select selecteditem, months, " "! Pick out and print the selected item: list.get months, selecteditem, m$print m$

The select function can also be used to choose items from an array:

array.load months$[], " January", " February", " March", " April", " May" ~ " June", " July", " August", " September", " October", " November", " December" select selecteditem, months$[], " " print months$[selecteditem]

There is an optional fourth parameter that you can provide the select function, which determines if the user selected the item with a short click or a long hold. This option can be useful for doing different things with the selected data, depending upon how the user makes the physical selection:

array.load months$[], " January", " February", " March", " April", " May" ~ " June", " July", " August", " September", " October", " November", " December" m$ = " Click an Item to Print, Click and HOLD to DELETE" select selecteditem, months$[], m$, dprint months$[selecteditem]! The final optional parameter in the select function determines if the! user clicked short or held long on the selected item.! 0 = short, 1 = long if d = 1 then print " Item will be deleted"





© 2023 :: MyLektsii.ru :: Мои Лекции
Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав.
Копирование текстов разрешено только с указанием индексируемой ссылки на источник.