Page 254 - Learn To Program With Scratch
P. 254

Even number
                                                                    of items.


                                                                     Find the average of
                                                                    the two middle
                                                                     numbers.

                                                                     Odd number
                                                                    of items.

                                                                    The median is the
                                                                     middle number.



                         Figure 9-25: Finding the median value of a sorted list of numbers

                             The procedure uses an if/else block to handle the two cases of even and
                         odd lists. If the number of items in the list divides by 2 with no remainder
                         (that is, the list has an even number of items) u, the median variable is cal-
                         culated as the average of the middle two numbers v. Otherwise, the list has
                         an odd number of items w, and the median variable is set equal to the num-
                         ber in the middle of the list x.
                             We’ve covered a lot of ground so far, so it’s time to apply our newfound
                         knowledge to something more challenging. The rest of this chapter walks
                         through several examples that demonstrate how to use lists in more com-
                         plex applications.


              Scratch Projects

                         In this section, you’ll explore practical Scratch projects that highlight dif-
                         ferent aspects of lists. I’ll also introduce some new ideas and techniques
                         that you can use in your own creations.

                         The Poet

                 Poet .sb2  Let’s kick off this chapter’s projects with a poem generator. Our artificial
                         poet selects words randomly from five lists (article, adjective, noun, verb, and
                         preposition) and combines them according to a fixed pattern. To give our
                         poems a central theme, all the words in these lists are somehow related to
                         love and nature. (Of course, we might still end up with some silly poetry,
                         but that’s just as fun!)









           232   Chapter 9
                                           www.it-ebooks.info
   249   250   251   252   253   254   255   256   257   258   259