Sunteți pe pagina 1din 140

v.

95b - 08/01/10 Introduction To Programming With MathPiper

1/140

Introduction To Programming With MathPiper And MathPiperIDE


by Ted Kosan

Copyright 2010 by Ted Kosan


This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 License. To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/3.0/

v.95b - 08/01/10 Introduction To Programming With MathPiper

2/140

Table of Contents
1 Preface.................................................................................................................9 1.1 Dedication......................................................................................................9 1.2 Acknowledgments..........................................................................................9 1.3 Website And Support Email List....................................................................9 1.4 Recommended Weekly Sequence When Teaching A Class With This Book. .9 2 Introduction........................................................................................................10 2.1 What Is A Mathematics Computing Environment?.....................................10 2.2 What Is MathPiperIDE?...............................................................................11 2.3 What Inspired The Creation Of MathPiperIDE?..........................................12 3 Downloading And Installing MathPiperIDE.......................................................13 3.1 Installing Sun's Java Implementation..........................................................13 3.1.1 Installing Java On A Windows PC.........................................................13 3.1.1.1 The 64 Bit Version Of Windows Needs The 64 Bit Version Of Java ....................................................................................................................13 3.1.2 Installing Java On A Macintosh.............................................................13 3.1.3 Installing Java On A Linux PC...............................................................13 3.2 Downloading And Extracting.......................................................................13 3.2.1 Extracting The Archive File For Windows Users..................................14 3.2.2 Extracting The Archive File For Unix Users.........................................15 3.3 MathPiperIDE's Directory Structure & Execution Instructions..................15 3.3.1 Executing MathPiperIDE On Windows Systems...................................16 3.3.2 Executing MathPiperIDE On Unix Systems..........................................16 3.3.2.1 MacOS X.........................................................................................16 4 The Graphical User Interface.............................................................................17 4.1 Buffers And Text Areas................................................................................17 4.2 The Gutter...................................................................................................17 4.3 Menus..........................................................................................................17 4.3.1 File........................................................................................................18 4.3.2 Edit........................................................................................................18 4.3.3 Search...................................................................................................18 4.3.4 Markers, Folding, and View..................................................................19 4.3.5 Utilities.................................................................................................19 4.3.6 Macros..................................................................................................19 4.3.7 Plugins..................................................................................................19 4.3.8 Help.......................................................................................................19 4.4 The Toolbar..................................................................................................19 4.4.1 Undo And Redo.....................................................................................20

v.95b - 08/01/10 Introduction To Programming With MathPiper

3/140

5 MathPiper: A Computer Algebra System For Beginners...................................21 5.1 Numeric Vs. Symbolic Computations..........................................................21 5.2 Using The MathPiper Console As A Numeric (Scientific) Calculator..........22 5.2.1 Functions..............................................................................................23 5.2.1.1 The Sqrt() Square Root Function...................................................24 5.2.1.2 The IsEven() Function....................................................................24 5.2.2 Accessing Previous Input And Results..................................................25 5.3 Saving And Restoring A Console Session....................................................25 5.3.1 Syntax Errors........................................................................................26 5.4 Using The MathPiper Console As A Symbolic Calculator...........................26 5.4.1 Variables...............................................................................................27 5.4.1.1 Calculating With Unbound Variables.............................................28 5.4.1.2 Variable And Function Names Are Case Sensitive........................29 5.4.1.3 Using More Than One Variable......................................................30 5.5 Exercises......................................................................................................31 5.5.1 Exercise 1.............................................................................................31 5.5.2 Exercise 2.............................................................................................31 5.5.3 Exercise 3.............................................................................................31 5.5.4 Exercise 4.............................................................................................31 5.5.5 Exercise 5.............................................................................................32 6 The MathPiper Documentation Plugin...............................................................33 6.1 Function List................................................................................................33 6.2 Mini Web Browser Interface........................................................................33 6.3 Exercises......................................................................................................34 6.3.1 Exercise 1.............................................................................................34 6.3.2 Exercise 2.............................................................................................34 7 Using MathPiperIDE As A Programmer's Text Editor.......................................35 7.1 Creating, Opening, Saving, And Closing Text Files.....................................35 7.2 Editing Files.................................................................................................35 7.3 File Modes...................................................................................................36 7.4 Learning How To Type Properly Is An Excellent Investment Of Your Time36 7.5 Exercises......................................................................................................36 7.5.1 Exercise 1.............................................................................................36 8 MathPiperIDE Worksheet Files..........................................................................37 8.1 Code Folds...................................................................................................37 8.1.1 The title Attribute.................................................................................38 8.2 Automatically Inserting Folds & Removing Unpreserved Folds.................38 8.3 Placing Text Outside Of A Fold....................................................................39 8.4 Exercises......................................................................................................39 8.4.1 Exercise 1.............................................................................................40 8.4.2 Exercise 2.............................................................................................40

v.95b - 08/01/10 Introduction To Programming With MathPiper

4/140

8.4.3 Exercise 3.............................................................................................40 8.4.4 Exercise 4.............................................................................................40 9 MathPiper Programming Fundamentals............................................................41 9.1 Values and Expressions...............................................................................41 9.2 Operators.....................................................................................................41 9.3 Operator Precedence...................................................................................42 9.4 Changing The Order Of Operations In An Expression................................43 9.5 Functions & Function Names......................................................................44 9.6 Functions That Produce Side Effects..........................................................45 9.6.1 Printing Related Functions: Echo(), Write(), And Newline()................45 9.6.1.1 Echo().............................................................................................45 9.6.1.2 Echo Functions Are Useful For "Debugging" Programs................47 9.6.1.3 Write()............................................................................................48 9.6.1.4 NewLine().......................................................................................48 9.7 Expressions Are Separated By Semicolons.................................................49 9.7.1 Placing More Than One Expression On A Line In A Fold.....................49 9.7.2 Placing Multiple Expressions In A Code Block.....................................50 9.7.2.1 Automatic Bracket, Parentheses, And Brace Match Indicating.....51 9.8 Strings.........................................................................................................52 9.8.1 The MathPiper Console and MathPiper Folds Can Access The Same Variables........................................................................................................52 9.8.2 Using Strings To Make Echo's Output Easier To Read.........................53 9.8.2.1 Combining Strings With The : Operator........................................53 9.8.2.2 WriteString()..................................................................................53 9.8.2.3 Nl().................................................................................................54 9.8.2.4 Space()...........................................................................................54 9.8.3 Accessing The Individual Letters In A String.......................................54 9.8.3.1 Indexing Before The Beginning Of A String Or Past The End Of A String..........................................................................................................55 9.9 Comments....................................................................................................56 9.10 How To Tell If MathPiper Has Crashed And What To Do If It Has............57 9.11 Exercises....................................................................................................57 9.11.1 Exercise 1...........................................................................................58 9.11.2 Exercise 2...........................................................................................58 9.11.3 Exercise 3...........................................................................................58 9.11.4 Exercise 4...........................................................................................58 9.11.5 Exercise 5...........................................................................................59 9.11.6 Exercise 6...........................................................................................59 9.11.7 Exercise 7...........................................................................................59 10 Rectangular Selection Mode And Text Area Splitting......................................61 10.1 Rectangular Selection Mode.....................................................................61

v.95b - 08/01/10 Introduction To Programming With MathPiper

5/140

10.2 Text area splitting......................................................................................61 10.3 Exercises....................................................................................................61 10.3.1 Exercise 1...........................................................................................62 11 Working With Random Integers.......................................................................63 11.1 Obtaining Random Integers With The RandomInteger() Function...........63 11.2 Simulating The Rolling Of Dice.................................................................64 11.3 Exercises....................................................................................................65 11.3.1 Exercise 1...........................................................................................65 12 Making Decisions.............................................................................................66 12.1 Conditional Operators...............................................................................66 12.2 Predicate Expressions...............................................................................69 12.3 Exercises....................................................................................................69 12.3.1 Exercise 1...........................................................................................69 12.3.2 Exercise 2...........................................................................................70 12.3.3 Exercise 3...........................................................................................70 12.4 Making Decisions With The If() Function & Predicate Expressions.........70 12.4.1 If() Functions Which Include An "Else" Parameter.............................72 12.5 Exercises....................................................................................................72 12.5.1 Exercise 1...........................................................................................73 12.5.2 Exercise 2...........................................................................................73 12.6 The And(), Or(), & Not() Boolean Functions & Infix Notation..................73 12.6.1 And()...................................................................................................73 12.6.2 Or()......................................................................................................75 12.6.3 Not() & Prefix Notation......................................................................76 12.7 Exercises....................................................................................................77 12.7.1 Exercise 1...........................................................................................78 12.7.2 Exercise 2...........................................................................................78 12.7.3 Exercise 3...........................................................................................78 13 The While() Looping Function & Bodied Notation...........................................80 13.1 Printing The Integers From 1 to 10...........................................................80 13.2 Printing The Integers From 1 to 100.........................................................82 13.3 Printing The Odd Integers From 1 To 99..................................................82 13.4 Printing The Integers From 1 To 100 In Reverse Order...........................83 13.5 Expressions Inside Of Code Blocks Are Indented.....................................84 13.6 Long-Running Loops, Infinite Loops, & Interrupting Execution...............84 13.7 A Program That Simulates Rolling Two Dice 50 Times.............................85 13.8 Exercises....................................................................................................87 13.8.1 Exercise 1...........................................................................................88 13.8.2 Exercise 2...........................................................................................88 13.8.3 Exercise 3...........................................................................................88 13.8.4 Exercise 4...........................................................................................88

v.95b - 08/01/10 Introduction To Programming With MathPiper

6/140

14 Predicate Functions.........................................................................................89 14.1 Finding Prime Numbers With A Loop........................................................90 14.2 Finding The Length Of A String With The Length() Function...................92 14.3 Converting Numbers To Strings With The ToString() Function...............93 14.4 Finding Prime Numbers Which End With 7 (And Multi-line Function Calls) ...........................................................................................................................93 14.5 Exercises....................................................................................................94 14.5.1 Exercise 1...........................................................................................95 14.5.2 Exercise 2...........................................................................................95 15 Lists: Values That Hold Sequences Of Expressions.........................................96 15.1 Append() & Nondestructive List Operations.............................................97 15.2 Using While Loops With Lists ...................................................................98 15.2.1 Using A While Loop And Append() To Place Values Into A List........100 15.3 Exercises..................................................................................................101 15.3.1 Exercise 1.........................................................................................101 15.3.2 Exercise 2.........................................................................................101 15.3.3 Exercise 3.........................................................................................101 15.4 The ForEach() Looping Function.............................................................102 15.5 Print All The Values In A List Using A ForEach() function......................102 15.6 Calculate The Sum Of The Numbers In A List Using ForEach().............103 15.7 The .. Range Operator.............................................................................104 15.8 Using ForEach() With The Range Operator To Print The Prime Numbers Between 1 And 100..........................................................................................105 15.8.1 Using ForEach() And The Range Operator To Place The Prime Numbers Between 1 And 50 Into A List......................................................106 15.8.2 Exercises...........................................................................................107 15.8.3 Exercise 1.........................................................................................107 15.8.4 Exercise 2.........................................................................................107 15.8.5 Exercise 3.........................................................................................107 15.8.6 Exercise 4.........................................................................................108 16 Functions & Operators Which Loop Internally..............................................109 16.1 Functions & Operators Which Loop Internally To Process Lists.............109 16.1.1 TableForm().......................................................................................109 16.1.2 Contains()..........................................................................................109 16.1.3 Find()................................................................................................110 16.1.4 Count()..............................................................................................110 16.1.5 Select()..............................................................................................111 16.1.6 The Nth() Function & The [] Operator..............................................111 16.1.7 The : Prepend/Append Operator.......................................................112 16.1.8 Concat()............................................................................................112 16.1.9 Insert(), Delete(), & Replace()..........................................................112

v.95b - 08/01/10 Introduction To Programming With MathPiper

7/140

16.1.10 Take() .............................................................................................113 16.1.11 Drop()..............................................................................................114 16.1.12 FillList()..........................................................................................114 16.1.13 RemoveDuplicates()........................................................................115 16.1.14 Reverse().........................................................................................115 16.1.15 Partition()........................................................................................115 16.1.16 Table() ............................................................................................116 16.1.17 HeapSort()......................................................................................117 16.2 Functions That Work With Integers........................................................117 16.2.1 RandomIntegerList().........................................................................117 16.2.2 Maximum() & Minimum().................................................................118 16.2.3 Quotient() & Modulo()......................................................................118 16.2.4 Gcd().................................................................................................119 16.2.5 Lcm().................................................................................................119 16.2.6 Sum().................................................................................................120 16.2.7 Product()...........................................................................................120 16.3 Exercises..................................................................................................120 16.3.1 Exercise 1.........................................................................................121 16.3.2 Exercise 2.........................................................................................121 16.3.3 Exercise 3.........................................................................................121 16.3.4 Exercise 4.........................................................................................121 16.3.5 Exercise 5.........................................................................................122 17 Nested Loops..................................................................................................123 17.1 Generate All The Combinations That Can Be Entered Into A Two Digit Wheel Lock Using A Nested Loop...................................................................123 17.2 Exercises..................................................................................................124 17.2.1 Exercise 1.........................................................................................125 18 User Defined Functions..................................................................................126 18.1 Global Variables, Local Variables, & Local()...........................................128 18.2 Exercises..................................................................................................130 18.2.1 Exercise 1.........................................................................................130 18.2.2 Exercise 2.........................................................................................130 19 Miscellaneous topics......................................................................................132 19.1 Incrementing And Decrementing Variables With The ++ And -- Operators .........................................................................................................................132 19.1.1 Incrementing Variables With The ++ Operator...............................132 19.1.2 Decrementing Variables With The -- Operator.................................133 19.1.3 The Break() Function........................................................................134 19.1.4 The Continue() Function...................................................................135 19.1.5 The Repeat() Function......................................................................135 19.1.6 The EchoTime() Function.................................................................137

v.95b - 08/01/10 Introduction To Programming With MathPiper

8/140

19.2 Exercises..................................................................................................139 19.2.1 Exercise 1.........................................................................................139 19.2.2 Exercise 2.........................................................................................139 19.2.3 Exercise 3.........................................................................................140 19.2.4 Exercise 4.........................................................................................140 19.2.5 Exercise 5.........................................................................................140

v.95b - 08/01/10 Introduction To Programming With MathPiper

9/140

1 2 3 4 5 6 7 8 9 10 11 12

1 Preface
1.1 Dedication
This book is dedicated to Steve Yegge and his blog entries "Math Every Day" (http://steve.yegge.googlepages.com/math-every-day) and "Math For Programmers" (http://steve-yegge.blogspot.com/2006/03/math-forprogrammers.html).

1.2 Acknowledgments
The following people have provided feedback on this book (if I forgot to include your name on this list, please email me at ted.kosan at gmail.com): Sherm Ostrowsky Susan Addington Matthew Moelter

13 14 15 16 17 18 19 20 21 22 23 24 25

1.3 Website And Support Email List


The website for MathPiper and MathPiperIDE is http://mathpiper.org. The support email list for this book is called mathpiperuser@googlegroups.com and you can subscribe to it at http://groups.google.com/group/mathpiper-user

1.4 Recommended Weekly Sequence When Teaching A Class With This Book
Week 1: Sections 1 - 6. Week 2: Sections 7 - 9. Week 3: Sections 10 - 13. Week 4: Sections 14 - 15. Week 5: Sections 16 - 19. Week 6: Exam

v.95b - 08/01/10 Introduction To Programming With MathPiper

10/140

26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60

2 Introduction
MathPiperIDE is an open source mathematics computing environment for performing numeric and symbolic computations (the difference between numeric and symbolic computations are discussed in a later section). Mathematics computing environments are complex and it takes a significant amount of time and effort to become proficient at using one. The amount of power that these environments make available to a user, however, is well worth the effort needed to learn one. It will take a beginner a while to become an expert at using MathPiperIDE, but fortunately one does not need to be a MathPiperIDE expert in order to begin using it to solve problems.

2.1 What Is A Mathematics Computing Environment?


A Mathematics Computing Environment is a set of computer programs that 1) automatically execute a wide range of numeric and symbolic mathematics calculation algorithms and 2) provide a user interface which enables the user to access these calculation algorithms and manipulate the mathematical objects they create (An algorithm is a step-by-step sequence of instructions for solving a problem and we will be learning about algorithms later in the book). Standard and graphing scientific calculator users interact with these devices using buttons and a small LCD display. In contrast to this, users interact with MathPiperIDE using a rich graphical user interface which is driven by a computer keyboard and mouse. Almost any personal computer can be used to run MathPiperIDE, including the latest subnotebook computers. Calculation algorithms exist for many areas of mathematics and new algorithms are constantly being developed. Software that contains these kind of algorithms is commonly referred to as "Computer Algebra Systems (CAS)". A significant number of computer algebra systems have been created since the 1960s and the following list contains some of the more popular ones: http://en.wikipedia.org/wiki/Comparison_of_computer_algebra_systems Some environments are highly specialized and some are general purpose. Some allow mathematics to be entered and displayed in traditional form (which is what is found in most math textbooks). Some are able to display traditional form mathematics but need to have it input as text and some are only able to have mathematics displayed and entered as text. As an example of the difference between traditional mathematics form and text form, here is a formula which is displayed in traditional form:

a= x 2 4hx

3 7

v.95b - 08/01/10 Introduction To Programming With MathPiper 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 and here is the same formula in text form: a = x^2 + 4*h*x + 3/7

11/140

Most computer algebra systems contain a mathematics-oriented programming language. This allows programs to be developed which have access to the mathematics algorithms which are included in the system. Some mathematicsoriented programming languages were created specifically for the system they work in while others were built on top of an existing programming language. Some mathematics computing environments are proprietary and need to be purchased while others are open source and available for free. Both kinds of systems possess similar core capabilities, but they usually differ in other areas. Proprietary systems tend to be more polished than open source systems and they often have graphical user interfaces that make inputting and manipulating mathematics in traditional form relatively easy. However, proprietary environments also have drawbacks. One drawback is that there is always a chance that the company that owns it may go out of business and this may make the environment unavailable for further use. Another drawback is that users are unable to enhance a proprietary environment because the environment's source code is not made available to users. Some open source computer algebra systems do not have graphical user interfaces, but their user interfaces are adequate for most purposes and the environment's source code will always be available to whomever wants it. This means that people can use the environment for as long as they desire and they can also enhance it.

2.2 What Is MathPiperIDE?


MathPiperIDE is an open source Mathematics Computing Environment which has been designed to help people teach themselves the STEM disciplines (Science, Technology, Engineering, and Mathematics) in an efficient and holistic way. It inputs mathematics in textual form and displays it in either textual form or traditional form. MathPiperIDE uses MathPiper as its default computer algebra system, BeanShell as its main scripting language, jEdit as its framework (hereafter referred to as the MathPiperIDE framework), and Java as it overall implementation language. One way to determine a person's MathPiperIDE expertise is by their knowledge of these components. (see Table 1)

v.95b - 08/01/10 Introduction To Programming With MathPiper Level MathPiperIDE Developer MathPiperIDE Customizer MathPiperIDE Expert MathPiperIDE Novice MathPiperIDE Newbie Programming Newbie Knowledge

12/140

Knows Java, BeanShell, and the MathPiperIDE framework at an advanced level. Is able to develop MathPiperIDE plugins. Knows Java, BeanShell, and the MathPiperIDE framework at an intermediate level. Is able to develop MathPiperIDE macros. Knows MathPiper at an advanced level and is skilled at using most aspects of the MathPiperIDE application. Knows MathPiper at an intermediate level, but has only used MathPiperIDE for a short while. Does not know MathPiper but has been exposed to at least one programming language. Does not know how a computer works and has never programmed before but knows how to use a word processor.

Table 1: MathPiperIDE user experience levels.


95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 This book is for MathPiperIDE and Programming Newbies. This book will teach you enough programming to begin solving problems with MathPiperIDE and the language that is used is MathPiper. It will help you to become a MathPiperIDE Novice, but you will need to learn MathPiper from books that are dedicated to it before you can become a MathPiperIDE Expert. The MathPiperIDE project website (http://MathPiperIDE.org) contains more information about MathPiperIDE along with other MathPiperIDE resources.

2.3 What Inspired The Creation Of MathPiperIDE?


Two of MathPiperIDE's main inspirations are Scott McNeally's concept of "No child held back": http://weblogs.java.net/blog/turbogeek/archive/2004/09/no_child_held_b_1.html and Steve Yegge's thoughts on learning mathematics: 1) Math is a lot easier to pick up after you know how to program. In fact, if you're a halfway decent programmer, you'll find it's almost a snap. 2) The right way to learn math is breadth-first, not depth-first. You need to survey the space, learn the names of things, figure out what's what. http://steve-yegge.blogspot.com/2006/03/math-for-programmers.html

v.95b - 08/01/10 Introduction To Programming With MathPiper

13/140

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140

3 Downloading And Installing MathPiperIDE


3.1 Installing Sun's Java Implementation
MathPiperIDE is a Java-based application and therefore a current version of Sun's Java (at least Java 6) must be installed on your computer before MathPiperIDE can be run.

3.1.1 Installing Java On A Windows PC


Many Windows PCs will already have a current version of Java installed. You can test to see if you have a current version of Java installed by visiting the following web site: http://java.com/ This web page contains a link called "Do I have Java?" which will check your Java version and tell you how to update it if necessary.
3.1.1.1 The 64 Bit Version Of Windows Needs The 64 Bit Version Of Java

If you are using the 64 bit version of Windows, then you will need the 64 bit version of Java. The 64 bit version of Java can be obtained here: https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_DeveloperSite/en_US/-/USD/ViewProductDetail-Start?ProductRef=jre-6u16-oth-JPR@CDSCDS_Developer

3.1.2 Installing Java On A Macintosh


Macintosh computers have Java pre-installed but you may need to upgrade to a current version of Java (at least Java 6) before running MathPiperIDE. If you need to update your version of Java, visit the following website: http://developer.apple.com/java.

3.1.3 Installing Java On A Linux PC


Locate the Java documentation for your Linux distribution and carefully follow the instructions provided for installing a Java 6 compatible version of Java on your system.

3.2 Downloading And Extracting


One of the many benefits of learning MathPiperIDE is the programming-related

v.95b - 08/01/10 Introduction To Programming With MathPiper 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179

14/140

knowledge one gains about how open source software is developed on the Internet. An important enabler of open source software development are websites, such as sourceforge.net (http://sourceforge.net) and java.net (http://java.net) which make software development tools available for free to open source developers. MathPiperIDE is hosted at Google and the URL for the project website is: http://code.google.com/p/mathpiper MathPiperIDE can be obtained by selecting the downloads tab and choosing the correct download file for your computer. Place the download file on your hard drive where you want MathPiperIDE to be located. For Windows users, it is recommended that MathPiperIDE be placed somewhere on c: drive. The MathPiperIDE download consists of a main directory (or folder) called mathpiperide which contains a number of directories and files. In order to make downloading quicker and sharing easier, the mathpiperide directory (and all of its contents) have been placed into a single compressed file called an archive. For Windows systems, the archive has a .zip extension and the archives for Unix-based systems have a .tar.bz2 extension. After an archive has been downloaded onto your computer, the directories and files it contains must be extracted from it. The process of extraction uncompresses copies of the directories and files that are in the archive and places them on the hard drive, usually in the same directory as the archive file. After the extraction process is complete, the archive file will still be present on your drive along with the extracted MathPiperIDE directory and its contents. The archive file can be easily copied to a CD or USB drive if you would like to install MathPiperIDE on another computer or give it to a friend. However, don't try to run MathPiperIDE from a USB drive because it will not work correctly. (Note: If you already have a version of MathPiperIDE installed and you want to install a new version in the same directory that holds the old version, you must delete the old version first or move it to a separate directory.)

3.2.1 Extracting The Archive File For Windows Users


Usually the easiest way for Windows users to extract the MathPiperIDE archive file is to navigate to the folder which contains the archive file (using the Windows GUI), right click on the archive file (it should appear as a folder with a vertical zipper on it), and select Extract All... from the pop up menu. After the extraction process is complete, a new folder called MathPiperIDE should be present in the same folder that contains the archive file. (Note: be careful not to double click on the archive file by mistake when you are

v.95b - 08/01/10 Introduction To Programming With MathPiper 180 181 182 183 184 185 186 187 188 189 190 191 192 193

15/140

trying to open the MathPiperIDE folder. The Windows operating system will open the archive just like it opens folders and this can fool you into thinking you are opening the MathPiperIDE folder when you are not. You may want to move the archive file to another place on your hard drive after it has been extracted to avoid this potential confusion.)

3.2.2 Extracting The Archive File For Unix Users


One way Unix users can extract the download file is to open a shell, change to the directory that contains the archive file, and extract it using the following command: tar -xvjf <name of archive file> If your desktop environment has GUI-based archive extraction tools, you can use these as an alternative.

3.3 MathPiperIDE's Directory Structure & Execution Instructions


The top level of MathPiperIDE's directory structure is shown in Illustration 1: mathrider doc examples jars macros modes settings startup jedit.jar unix_run.sh win_run.bat

Illustration 1: MathPiperIDE's Directory Structure


194 195 196 197 198 199 200 201 202 203 204 205 The following is a brief description this top level directory structure: doc - Contains MathPiperIDE's documentation files. examples - Contains various example programs, some of which are pre-opened when MathPiperIDE is first executed. jars - Holds plugins, code libraries, and support scripts. macros - Contains various scripts that can be executed by the user. modes - Contains files which tell MathPiperIDE how to do syntax highlighting for various file types. settings - Contains the application's main settings files. startup - Contains startup scripts that are executed each time MathPiperIDE launches. jedit.jar - Holds the core jEdit application which MathPiperIDE builds upon.

v.95b - 08/01/10 Introduction To Programming With MathPiper 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 unix_run.sh - The script used to execute MathPiperIDE on Unix systems. win_run.bat - The batch file used to execute MathPiperIDE on Windows systems.

16/140

3.3.1 Executing MathPiperIDE On Windows Systems


Open the MathPiperIDE folder (not the archive file!) and double click on the win_run file.

3.3.2 Executing MathPiperIDE On Unix Systems


Open a shell, change to the MathPiperIDE folder, and execute the unix_run.sh script by typing the following: sh unix_run.sh
3.3.2.1 MacOS X

Make a note of where you put the MathPiperIDE application (for example /Applications/MathPiperIDE). Run Terminal (which is in /Applications/Utilities). Change to that directory (folder) by typing: cd /Applications/MathPiperIDE Run MathPiperIDE by typing: sh unix_run.sh

v.95b - 08/01/10 Introduction To Programming With MathPiper

17/140

223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258

4 The Graphical User Interface


MathPiperIDE is built on top of jEdit (http://jedit.org) so it has the "heart" of a programmer's text editor. Programmer's text editors are similar to standard text editors (like NotePad and WordPad) and word processors (like MS Word and OpenOffice) in a number of ways so getting started with MathPiperIDE should be relatively easy for anyone who has used a text editor or a word processor. However, programmer's text editors are more challenging to use than a standard text editor or a word processor because programmer's text editors have capabilities that are far more advanced than these two types of applications. Most software is developed with a programmer's text editor (or environments which contain one) and so learning how to use a programmer's text editor is one of the many skills that MathPiperIDE provides which can be used in other areas. The MathPiperIDE series of books are designed so that these capabilities are revealed to the reader over time. In the following sections, the main parts of MathPiperIDE's graphical user interface are briefly covered. Some of these parts are covered in more depth later in the book and some are covered in other books. As you read through the following sections, I encourage you to explore each part of MathPiperIDE that is being discussed using your own copy of MathPiperIDE.

4.1 Buffers And Text Areas


In MathPiperIDE, open files are called buffers and they are viewed through one or more text areas. Each text area has a tab at its upper-left corner which displays the name of the buffer it is working on along with an indicator which shows whether the buffer has been saved or not. The user is able to select a text area by clicking its tab and double clicking on the tab will close the text area. Tabs can also be rearranged by dragging them to a new position with the mouse.

4.2 The Gutter


The gutter is the vertical gray area that is on the left side of the main window. It can contain line numbers, buffer manipulation controls, and context-dependent information about the text in the buffer.

4.3 Menus
The main menu bar is at the top of the application and it provides access to a significant portion of MathPiperIDE's capabilities. The commands (or actions) in these menus all exist separately from the menus themselves and they can be executed in alternate ways (such as keyboard shortcuts). The menu items (and

v.95b - 08/01/10 Introduction To Programming With MathPiper 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295

18/140

even the menus themselves) can all be customized, but the following sections describe the default configuration.

4.3.1 File
The File menu contains actions which are typically found in normal text editors and word processors. The actions to create new files, save files, and open existing files are all present along with variations on these actions. Actions for opening recent files, configuring the page setup, and printing are also present.

4.3.2 Edit
The Edit menu also contains actions which are typically found in normal text editors and word processors (such as Undo, Redo, Cut, Copy, and Paste). However, there are also a number of more sophisticated actions available which are of use to programmers. For beginners, though, the typical actions will be sufficient for most editing needs.

4.3.3 Search
The actions in the Search menu are used heavily, even by beginners. A good way to get your mind around the search actions is to open the Search dialog window by selecting the Find... action (which is the first actions in the Search menu). A Search And Replace dialog window will then appear which contains access to most of the search actions. At the top of this dialog window is a text area labeled Search for which allows the user to enter text they would like to find. Immediately below it is a text area labeled Replace with which is for entering optional text that can be used to replace text which is found during a search. The column of radio buttons labeled Search in allows the user to search in a Selection of text (which is text which has been highlighted), the Current Buffer (which is the one that is currently active), All buffers (which means all opened files), or a whole Directory of files. The default is for a search to be conducted in the current buffer and this is the mode that is used most often. The column of check boxes labeled Settings allows the user to either Keep or hide the Search dialog window after a search is performed, Ignore the case of searched text, use an advanced search technique called a Regular expression search (which is covered in another book), and to perform a HyperSearch (which collects multiple search results in a text area). The Find button performs a normal find operation. Replace & Find will replace the previously found text with the contents of the Replace with text area and perform another find operation. Replace All will find all occurrences of the

v.95b - 08/01/10 Introduction To Programming With MathPiper 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327

19/140

contents of the Search for text area and replace them with the contents of the Replace with text area.

4.3.4 Markers, Folding, and View


These are advanced menus and they are described in later sections.

4.3.5 Utilities
The utilities menu contains a significant number of actions, some that are useful to beginners and others that are meant for experts. The two actions that are most useful to beginners are the Buffer Options actions and the Global Options actions. The Buffer Options actions allows the currently selected buffer to be customized and the Global Options actions brings up a rich dialog window that allows numerous aspects of the MathPiperIDE application to be configured. Feel free to explore these two actions in order to learn more about what they do.

4.3.6 Macros
This is an advanced menu and it is described in a later sections.

4.3.7 Plugins
Plugins are component-like pieces of software that are designed to provide an application with extended capabilities and they are similar in concept to physical world components. The tabs on the right side of the application which are labeled "GeoGebra", "Jung', "MathPiper", "MathPiperDocs", etc. are all plugins and they can be opened and closed by clicking on their tabs. Feel free to close any of these plugins which may be opened if you are not currently using them. MathPiperIDE pPlugins are covered in more depth in a later section.

4.3.8 Help
The most important action in the Help menu is the MathPiperIDE Help action. This action brings up a dialog window with contains documentation for the core MathPiperIDE application along with documentation for each installed plugin.

4.4 The Toolbar


The Toolbar is located just beneath the menus near the top of the main window and it contains a number of icon-based buttons. These buttons allow the user to access the same actions which are accessible through the menus just by clicking on them. There is not room on the toolbar for all the actions in the menus to be

v.95b - 08/01/10 Introduction To Programming With MathPiper 328 329 330 331 332 333 334 335 336

20/140

displayed, but the most common actions are present. The user also has the option of customizing the toolbar by using the Utilities->Global Options->Tool Bar dialog.

4.4.1 Undo And Redo


The Undo button on the toolbar is able to undo any text was entered since the current session of MathPiperIDE was launched. This is very handy for undoing mistakes or getting back text which was deleted. The Redo button can be used if you have selected Undo too many times and you need to "undo" one ore more Undo operations.

v.95b - 08/01/10 Introduction To Programming With MathPiper

21/140

337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372

5 MathPiper: A Computer Algebra System For Beginners


Computer algebra systems are extremely powerful and very useful for solving STEM-related problems. In fact, one of the reasons for creating MathPiperIDE was to provide a vehicle for delivering a computer algebra system to as many people as possible. If you like using a scientific calculator, you should love using a computer algebra system! At this point you may be asking yourself "if computer algebra systems are so wonderful, why aren't more people using them?" One reason is that most computer algebra systems are complex and difficult to learn. Another reason is that proprietary systems are very expensive and therefore beyond the reach of most people. Luckily, there are some open source computer algebra systems that are powerful enough to keep most people engaged for years, and yet simple enough that even a beginner can start using them. MathPiper (which is based on a CAS called Yacas) is one of these simpler computer algebra systems and it is the computer algebra system which is included by default with MathPiperIDE. A significant part of this book is devoted to learning MathPiper and a good way to start is by discussing the difference between numeric and symbolic computations.

5.1 Numeric Vs. Symbolic Computations


A Computer Algebra System (CAS) is software which is capable of performing both numeric and symbolic computations. Numeric computations are performed exclusively with numerals and these are the type of computations that are performed by typical hand-held calculators. Symbolic computations (which also called algebraic computations) relate "...to the use of machines, such as computers, to manipulate mathematical equations and expressions in symbolic form, as opposed to manipulating the approximations of specific numerical quantities represented by those symbols." (http://en.wikipedia.org/wiki/Symbolic_mathematics). Since most people who read this document will probably be familiar with performing numeric calculations as done on a scientific calculator, the next section shows how to use MathPiper as a scientific calculator. The section after that then shows how to use MathPiper as a symbolic calculator. Both sections use the console interface to MathPiper. In MathPiperIDE, a console interface to any plugin or application is a text-only shell or command line interface to it. This means that you type on the keyboard to send information to the console and it prints text to send you information.

v.95b - 08/01/10 Introduction To Programming With MathPiper 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406

22/140

5.2 Using The MathPiper Console As A Numeric (Scientific) Calculator


Open the MathPiper plugin by selecting the MathPiper tab in the lower left part of the MathPiperIDE application and place it into "Code Result" mode. The MathPiper console interface is a text area which is inside this plugin. Feel free to increase or decrease the size of the console text area if you would like by dragging on the dotted lines which are at the top side and right side of the console window. When the MathPiper console is first launched, it prints a welcome message and then provides In> as an input prompt:
MathPiper version ".80?". In>

Click to the right of the prompt in order to place the cursor there then type 2+2 followed by <enter> (or <return> on a Macintosh):
In> 2+2 Result> 4 In>

When <enter> was pressed, 2+2 was read into MathPiper for evaluation and Result> was printed followed by the result 4. Another input prompt was then displayed so that further input could be entered. This input, evaluation, output process will continue as long as the console is running and it is sometimes called a Read, Eval, Print Loop or REPL. In further examples, the last In> prompt will not be shown to save space. In addition to addition, MathPiper can also do subtraction, multiplication, exponents, and division:
In> 5-2 Result> 3 In> 3*4 Result> 12 In> 2^3 Result> 8 In> 12/6 Result> 2

Notice that the multiplication symbol is an asterisk (*), the exponent symbol is a caret (^), and the division symbol is a forward slash (/). These symbols (along

v.95b - 08/01/10 Introduction To Programming With MathPiper 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439

23/140

with addtion (+) , subtraction (), and ones we will talk about later) are called operators because they tell MathPiper to perform an operation such as addition or division. MathPiper can also work with decimal numbers:
In> .5+1.2 Result> 1.7 In> 3.7-2.6 Result> 1.1 In> 2.2*3.9 Result> 8.58 In> 2.2^3 Result> 10.648 In> 1/2 Result> 1/2

In the last example, MathPiper returned the fraction unevaluated. This sometimes happens due to MathPiper's symbolic nature, but a result in numeric form can be obtained by using the N() function (which is discussed in the next section):
In> N(1/2) Result> 0.5

As can be seen here, when a result is given in numeric form, it means that it is given as a decimal number. A numeric result could also be obtained by using a decimal point either after the 1 or the 2 (or both of them):
In> 1./2 Result> 0.5 In> 1/2. Result> 0.5 In> 1./2. Result> 0.5

When one or more decimal numbers are used in a calculation, MathPiper will usually return a numeric result.

5.2.1 Functions
N() is an example of a function. A function can be thought of as a "black box"

v.95b - 08/01/10 Introduction To Programming With MathPiper 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474

24/140

which accepts input, processes the input, and returns a result. Each function has a name and in this case, the name of the function is N which stands for "numeric". To the right of a function's name there is always a set of parentheses and information that is sent to the function is placed inside of them. The purpose of the N() function is to make sure that the information that is sent to it is processed numerically instead of symbolically. Functions are used by evaluating them and this happens when <enter> is pressed. Another name for evaluating a function is calling it.
5.2.1.1 The Sqrt() Square Root Function

The following example show the N() function being used with the square root function Sqrt():
In> Sqrt(9) Result: 3 In> Sqrt(8) Result: Sqrt(8) In> N(Sqrt(8)) Result: 2.828427125

Notice that Sqrt(9) returned 3 as expected but Sqrt(8) returned Sqrt(8). We needed to use the N() function to force the square root function to return a numeric result. The reason that Sqrt(8) does not appear to have done anything is because computer algebra systems like to work with expressions that are as exact as possible. In this case the symbolic value Sqrt(8) represents the number that is the square root of 8 more accurately than any decimal number can. For example, the following four decimal numbers all represent them represent it more accurately than Sqrt(8) does: 2.828427125 2.82842712474619 2.82842712474619009760337744842 2.8284271247461900976033774484193961571393437507539 Whenever MathPiper returns a symbolic result and a numeric result is desired, simply use the N() function to obtain one. The ability to work with symbolic values are one of the things that make computer algebra systems so powerful and they are discussed in more depth in later sections.
5.2.1.2 The IsEven() Function

, but none of

Another often used function is IsEven(). The IsEven() function takes a number

v.95b - 08/01/10 Introduction To Programming With MathPiper 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 as input and returns True if the number is even and False if it is not even:
In> IsEven(4) Result> True In> IsEven(5) Result> False

25/140

MathPiper has a large number of functions some of which are described in more depth in the MathPiper Documentation section and the MathPiper Programming Fundamentals section. A complete list of MathPiper's functions is contained in the MathPiperDocs plugin and more of these functions will be discussed soon.

5.2.2 Accessing Previous Input And Results


The MathPiper console is like a mini text editor which means you can copy text from it, paste text into it, and edit existing text. You can also reevaluate previous input by simply placing the cursor on the desired In> line and pressing <enter> on it again. The console also keeps a history of all input lines that have been evaluated. If the cursor is placed on any In> line, pressing <ctrl><up arrow> will display each previous line of input that has been entered. Finally, MathPiper associates the most recent computation result with the percent (%) character. If you want to use the most recent result in a new calculation, access it with this character:
In> 5*8 Result> 40 In> % Result> 40 In> %*2 Result> 80

5.3 Saving And Restoring A Console Session


If you need to save the contents of a console session, you can copy and paste it into a MathPiperIDE buffer and then save the buffer. You can also copy a console session out of a previously saved buffer and paste it into the console for further processing. Section 7 Using MathPiperIDE As A Programmer's Text Editor discusses how to use the text editor that is built into MathPiperIDE.

v.95b - 08/01/10 Introduction To Programming With MathPiper 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538

26/140

5.3.1 Syntax Errors


An expression's syntax is related to whether it is typed correctly or not. If input is sent to MathPiper which has one or more typing errors in it, MathPiper will return an error message which is meant to be helpful for locating the error. For example, if a backwards slash (\) is entered for division instead of a forward slash (/), MathPiper returns the following error message:
In> 12 \ 6 Exception: Error encountered during initialization or parsing: Expecting ; end of statement in program block, but got \ instead.

To fix this problem, change the \ to a /, and reevaluate the expression. This section provided a short introduction to using MathPiper as a numeric calculator and the next section contains a short introduction to using MathPiper as a symbolic calculator.

5.4 Using The MathPiper Console As A Symbolic Calculator


MathPiper is good at numeric computation, but it is great at symbolic computation. If you have never used a system that can do symbolic computation, you are in for a treat! As a first example, lets try adding fractions (which are also called rational 1 1 numbers). Add in the MathPiper console: 2 3
In> 1/2 + 1/3 Result> 5/6

Instead of returning a numeric result like 0.83333333333333333333 (which is what a scientific calculator would return) MathPiper added these two rational 5 numbers symbolically and returned . If you want to work with this result 6 further, remember that it has also been stored in the % symbol:
In> % Result> 5/6

Lets say that you would like to have MathPiper determine the numerator of this result. This can be done by using (or calling) the Numerator() function:
In> Numerator(%) Result> 5

v.95b - 08/01/10 Introduction To Programming With MathPiper 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571

27/140

Unfortunately, the % symbol cannot be used to have MathPiper determine the 5 denominator of because it only holds the result of the most recent 6 5 calculation and was calculated two steps back. 6

5.4.1 Variables
What would be nice is if MathPiper provided a way to store results (which are also called values) in symbols that we choose instead of ones that it chooses. Fortunately, this is exactly what it does! Symbols that can be associated with values are called variables. Variable names must start with an upper or lower case letter and be followed by zero or more upper case letters, lower case letters, or numbers. Examples of variable names include: 'a', 'b', 'x', 'y', 'answer', 'totalAmount', and 'loop6'. The process of associating a value with a variable is called assigning or binding the value to the variable and this consists of placing the name of a variable you would like to create on the left side of an assignment operator (:=) and an expression on the right side of this operator. When the expression returns a value, the value is assigned (or bound to) to the variable. Lets recalculate 1 1 but this time we will assign the result to the variable 'a': 2 3

In> a := 1/2 + 1/3 Result> 5/6 In> a Result> 5/6 In> Numerator(a) Result> 5 In> Denominator(a) Result> 6

In this example, the assignment operator (:=) was used to assign the result (or 5 value) to the variable 'a'. When 'a' was evaluated by itself, the value it 6 5 was bound to (in this case ) was returned. This value will stay bound to 6 the variable 'a' as long as MathPiper is running unless 'a' is cleared with the Unbind() function or 'a' has another value assigned to it. This is why we were able to determine both the numerator and the denominator of the rational number assigned to 'a' using two functions in turn. (Note: there can be no spaces between the : and the =)

v.95b - 08/01/10 Introduction To Programming With MathPiper 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
5.4.1.1 Calculating With Unbound Variables

28/140

Here is an example which shows another value being assigned to 'a':


In> a := 9 Result> 9 In> a Result> 9

and the following example shows 'a' being cleared (or unbound) with the Unbind() function:
In> Unbind(a) Result> True In> a Result> a

Notice that the Unbind() function returns 'True' as a result after it is finished to indicate that the variable that was sent to it was successfully cleared (or unbound). Many functions either return 'True' or 'False' to indicate whether or not the operation they performed succeeded. Also notice that unbound variables return themselves when they are evaluated. In this case, 'a' returned 'a'. All currently bound variables can be unbound by passing the * symbol to Unbind:
In> a := 1 Result: 1 In> b := 2 Result: 2 In> a Result: 1 In> b Result: 2 In> Unbind(*) Result: True In> a Result: a In> b Result: b

v.95b - 08/01/10 Introduction To Programming With MathPiper 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641

29/140

Unbound variables may not appear to be very useful, but they provide the flexibility needed for computer algebra systems to perform symbolic calculations. In order to demonstrate this flexibility, lets first factor some numbers using the Factor() function:
In> Factor(8) Result> 2^3 In> Factor(14) Result> 2*7 In> Factor(2343) Result> 3*11*71

Now lets factor an expression that contains the unbound variable 'x':
In> x Result> x In> IsBound(x) Result> False In> Factor(x^2 + 24*x + 80) Result> (x+4)*(x+20) In> Expand(%) Result> x^2+24*x+80

Evaluating 'x' by itself shows that it does not have a value bound to it and this can also be determined by passing 'x' to the IsBound() function. IsBound() returns 'True' if a variable is bound to a value and 'False' if it is not. What is more interesting, however, are the results returned by Factor() and Expand(). Factor() is able to determine when expressions with unbound variables are sent to it and it uses the rules of algebra to manipulate them into factored form. The Expand() function was then able to take the factored expression x20 x4 and manipulate it until it was expanded. One way to remember what the functions Factor() and Expand() do is to look at the second letters of their names. The 'a' in Factor can be thought of as adding parentheses to an expression and the 'x' in Expand can be thought of xing out or removing parentheses from an expression.
5.4.1.2 Variable And Function Names Are Case Sensitive

MathPiper variables are case sensitive. This means that MathPiper takes into account the case of each letter in a variable name when it is deciding if two or more variable names are the same variable or not. For example, the variable name Box and the variable name box are not the same variable because the first variable name starts with an upper case 'B' and the second variable name starts

v.95b - 08/01/10 Introduction To Programming With MathPiper 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 with a lower case 'b':
In> Box := 1 Result> 1 In> box := 2 Result> 2 In> Box Result> 1 In> box Result> 2

30/140

5.4.1.3 Using More Than One Variable

Programs are able to have more than 1 variable and here is a more sophisticated example which uses 3 variables:
a := 2 Result> 2 b := 3 Result> 3 a + b Result> 5 answer := a + b Result> 5 answer Result> 5

The part of an expression that is on the right side of an assignment operator is always evaluated first and the result is then assigned to the variable that is on the left side of the operator. Now that you have seen how to use the MathPiper console as both a symbolic and a numeric calculator, our next step is to take a closer look at the functions which are included with MathPiper. As you will soon discover, MathPiper contains an amazing number of functions which deal with a wide range of mathematics.

v.95b - 08/01/10 Introduction To Programming With MathPiper 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690

31/140

5.5 Exercises
Use the MathPiper console which is at the bottom of the MathPiperIDE application to complete the following exercises.

5.5.1 Exercise 1
Carefully read all of section 5. Evaluate each one of the examples in section 5 in the MathPiper console and verify that the results match the ones in the book.

5.5.2 Exercise 2
Answer each one of the following questions: a) What is the purpose of the N() function? b) What is a variable? c) Are the variables 'x' and 'X' the same variable? d) What is the difference between a bound variable and an unbound variable? e) How can you tell if a variable is bound or not? f) How can a variable be bound to a value? g) How can a variable be unbound from a value? h) What does the % character do?

5.5.3 Exercise 3
Perform the following calculation:

1 3 7 4 8 16 691 692 693 694 695 696

5.5.4 Exercise 4
a) Assign the variable answer to the result of the calculation using the following line of code: In> answer := 1/5 + 7/4 + 15/16 b) Use the Numerator() function to calculate the numerator of answer. c) Use the Denominator() function to calculate the denominator of answer.

1 7 15 5 4 16

v.95b - 08/01/10 Introduction To Programming With MathPiper 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
d) Use the N() function to calculate the numeric value of answer.

32/140

e) Use the Unbind() function to unbind the variable answer and verify that answer is unbound by executing the following code and by using the IsBound() function: In> answer

5.5.5 Exercise 5
Assign

1 3 7 to variable x, to variable y, and to variable z using the 4 8 16


Then perform the following calculations:

:= operator. a) In> x b) In> y c) In> z d) In> x + y e) In> x + z f) In> x + y + z

v.95b - 08/01/10 Introduction To Programming With MathPiper

33/140

717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754

6 The MathPiper Documentation Plugin


MathPiper has a significant amount of reference documentation written for it and this documentation has been placed into a plugin called MathPiperDocs in order to make it easier to navigate. The MathPiperDocs plugin is available in a tab called "MathPiperDocs" which is near the right side of the MathPiperIDE application. Click on this tab to open the plugin and click on it again to close it. The left side of the MathPiperDocs window contains the names of all the functions that come with MathPiper and the right side of the window contains a mini-browser that can be used to navigate the documentation.

6.1 Function List


MathPiper's functions are divided into two main categories called user functions and programmer functions. In general, the user functions are used for solving problems in the MathPiper console or with short programs and the programmer functions are used for longer programs. However, users will often use some of the programmer functions and programmers will use the user functions as needed. Both the user and programmer function names have been placed into a "tree" on the left side of the MathPiperDocs window to allow for easy navigation. The branches of the function tree can be opened and closed by clicking on the small "circle with a line attached to it" symbol which is to the left of each branch. Both the user and programmer branches have the functions they contain organized into categories and the top category in each branch lists all the functions in the branch in alphabetical order for quick access. Clicking on a function will bring up documentation about it in the browser window and selecting the Collapse button at the top of the plugin will collapse the tree. Don't be intimidated by the large number of categories and functions that are in the function tree! Most MathPiperIDE beginners will not know what most of them mean, and some will not know what any of them mean. Part of the benefit MathPiperIDE provides is exposing the user to the existence of these categories and functions. The more you use MathPiperIDE, the more you will learn about these categories and functions and someday you may even get to the point where you understand all of them. This book is designed to show newbies how to begin using these functions using a gentle step-by-step approach.

6.2 Mini Web Browser Interface


MathPiper's reference documentation is in HTML (or web page) format and so the right side of the plugin contains a mini web browser that can be used to navigate through these pages. The browser's home page contains links to the

v.95b - 08/01/10 Introduction To Programming With MathPiper 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774

34/140

main parts of the MathPiper documentation. As links are selected, the Back and Forward buttons in the upper right corner of the plugin allow the user to move backward and forward through previously visited pages and the Home button navigates back to the home page. The function names in the function tree all point to sections in the HTML documentation so the user can access function information either by navigating to it with the browser or jumping directly to it with the function tree.

6.3 Exercises 6.3.1 Exercise 1


Carefully read all of section 6. Locate the N(), IsEven(), IsOdd(), Unbind(), IsBound(), Numerator(), Denominator(), and Factor() functions in the All Functions section of the MathPiperDocs plugin and read the information that is available on them. List the one line descriptions which are at the top of the documentation for each of these functions.

6.3.2 Exercise 2
Locate the N(), IsEven(), IsOdd(), Unbind(), IsBound(), Numerator(), Denominator(), and Factor() functions in the User Functions section of the MathPiperDocs plugin and list which category each function is contained in. Don't include the Alphabetical or Built In categories in your search. For example, the N() function is in the Numbers (Operations) category.

v.95b - 08/01/10 Introduction To Programming With MathPiper

35/140

775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808

7 Using MathPiperIDE As A Programmer's Text Editor


We have covered some of MathPiperIDE's mathematics capabilities and this section discusses some of its programming capabilities. As indicated in a previous section, MathPiperIDE is built on top of a programmer's text editor but what wasn't discussed was what an amazing and powerful tool a programmer's text editor is. Computer programmers are among the most intelligent and productive people in the world and most of their work is done using a programmer's text editor (or something similar to one). Programmers have designed programmer's text editors to be super-tools which can help them maximize their personal productivity and these tools have all kinds of capabilities that most people would not even suspect they contained. Even though this book only covers a small part of the editing capabilities that MathPiperIDE has, what is covered will enable the user to begin writing useful programs.

7.1 Creating, Opening, Saving, And Closing Text Files


A good way to begin learning how to use MathPiperIDE's text editing capabilities is by creating, opening, and saving text files. A text file can be created either by selecting File->New from the menu bar or by selecting the icon for this operation on the tool bar. When a new file is created, an empty text area is created for it along with a new tab named Untitled. The file can be saved by selecting File->Save from the menu bar or by selecting the Save icon in the tool bar. The first time a file is saved, MathPiperIDE will ask the user what it should be named and it will also provide a file system navigation window to determine where it should be placed. After the file has been named and saved, its name will be shown in the tab that previously displayed Untitled. A file can be closed by selecting File->Close from the menu bar and it can be opened by selecting File->Open.

7.2 Editing Files


If you know how to use a word processor, then it should be fairly easy for you to learn how to use MathPiperIDE as a text editor. Text can be selected by dragging the mouse pointer across it and it can be cut or copied by using actions in the Edit menu (or by using <Ctrl>x and <Ctrl>c). Pasting text can be done using the Edit menu actions or by pressing <Ctrl>v.

v.95b - 08/01/10 Introduction To Programming With MathPiper 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836

36/140

7.3 File Modes


Text file names are suppose to have a file extension which indicates what type of file it is. For example, test.txt is a generic text file, test.bat is a Windows batch file, and test.sh is a Unix/Linux shell script (unfortunately, Windows is usually configured to hide file extensions, but viewing a file's properties by right-clicking on it will show this information.). MathPiperIDE uses a file's extension type to set its text area into a customized mode which highlights various parts of its contents. For example, MathPiperIDE worksheet files have a .mpw extension and MathPiperIDE knows what colors to highlight the various parts of a .mpw file in.

7.4 Learning How To Type Properly Is An Excellent Investment Of Your Time


This is a good place in the document to mention that learning how to type properly is an investment that will pay back dividends throughout your whole life. Almost any work you do on a computer (including programming) will be done much faster and with less errors if you know how to type properly. Here is what Steve Yegge has to say about this subject: "If you are a programmer, or an IT professional working with computers in any capacity, you need to learn to type! I don't know how to put it any more clearly than that." A good way to learn how to type is to locate a free "learn how to type" program on the web and use it.

7.5 Exercises 7.5.1 Exercise 1


Carefully read all of section 7. Create a text file called "my_text_file.txt" and place a few sentences in it. Save the text file somewhere on your hard drive then close it. Now, open the text file again using File->Open and verify that what you typed is still in the file.

v.95b - 08/01/10 Introduction To Programming With MathPiper

37/140

837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869

8 MathPiperIDE Worksheet Files


While MathPiperIDE's ability to execute code inside a console provides a significant amount of power to the user, most of MathPiperIDE's power is derived from worksheets. MathPiperIDE worksheets are text files which have a .mpw extension and are able to execute multiple types of code in a single text area. The worksheet_demo_1.mpw file (which is preloaded in the MathPiperIDE environment when it is first launched) demonstrates how a worksheet is able to execute multiple types of code in what are called code folds.

8.1 Code Folds


Code folds are named sections inside a MathPiperIDE worksheet which contain source code that can be executed by placing the cursor inside of it and pressing <shift><Enter>. A fold always begins with a start tag, which starts with a percent symbol (%) followed by the name of the fold type (like this: %<foldtype>). The end of a fold is marked by an end tag which looks like %/<foldtype>. The only difference between a fold's start tag and its end tag is that the end tag has a slash (/) after the %. For example, here is a MathPiper fold which will print the result of 2 + 3 to the MathPiper console (Note: the semicolon ';' which is at the end of the line of code is required):
%mathpiper 2 + 3; %/mathpiper

The output generated by a fold (called the parent fold) is wrapped in a new fold (called a child fold) which is indented and placed just below the parent. This can be seen when the above fold is executed by pressing <shift><enter> inside of it:
%mathpiper 2 + 3; %/mathpiper %output,preserve="false" Result: 5 %/output

The most common type of output fold is %output and by default folds of type

v.95b - 08/01/10 Introduction To Programming With MathPiper 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900

38/140

%output have their preserve property set to false. This tells MathPiperIDE to overwrite the %output fold with a new version during the next execution of its parent. If preserve is set to true, the fold will not be overwritten and a new fold will be created instead. There are other kinds of child folds, but in the rest of this document they will all be referred to in general as "output" folds.

8.1.1 The title Attribute


Folds can also have what is called a "title attribute" placed after the start tag which describes what the fold contains. For example, the following %mathpiper fold has a title attribute which indicates that the fold adds two number together:
%mathpiper,title="Add two numbers together." 2 + 3; %/mathpiper

The title attribute is added to the start tag of a fold by placing a comma after the fold's type name and then adding the text title="<text>" after the comma. (Note: no spaces can be present before or after the comma (,) or the equals sign (=) ).

8.2 Automatically Inserting Folds & Removing Unpreserved Folds


Typing the top and bottom fold lines (for example:
%mathpiper %/mathpiper

can be tedious and MathPiperIDE has a way to automatically insert them. Place the cursor at the beginning of a blank line in a .mpw worksheet file where you would like a fold inserted and then press the right mouse button. A popup menu will be displayed and at the top of this menu are items which read "Insert MathPiper Fold", "Insert Group Fold", etc. If you select one of these menu items, an empty code fold of the proper type will automatically be inserted into the .mpw file at the position of the cursor. This popup menu also has a menu item called "Remove Unpreserved Folds". If this menu item is selected, all folds which have a "preserve="false"" property will be removed.

v.95b - 08/01/10 Introduction To Programming With MathPiper 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920

39/140

8.3 Placing Text Outside Of A Fold


Text can also be placed outside of a fold like the following example shows:
Text can be placed above folds like this. text text text text text text text text %mathpiper,title="Fold 1" 2 + 3; %/mathpiper Text can be placed between folds like this. text text text text text text text text %mathpiper,title="Fold 2" 3 + 4; %/mathpiper Text can be placed between folds like this. text text text text text text text text

Placing text outside a fold is useful for describing what is being done in certain folds and it is also good for saving work that has been done in the MathPiper console.

921 922 923 924 925 926 927 928 929

8.4 Exercises
A MathPiperIDE worksheet file called "newbies_book_examples_1.mpw" is included in the mathpiperide/examples directory and it is opened by default when the software is first launched after it is downloaded. It contains a number of %mathpiper folds which contain code examples from the previous sections of this book. Notice that all of the lines of code have a semicolon (;) placed after them. The reason this is needed is explained in a later section. Download this worksheet file to your computer from the section on this website that contains the highest revision number and then open it in MathPiperIDE.

v.95b - 08/01/10 Introduction To Programming With MathPiper 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 Then, use the worksheet to do the following exercises.

40/140

8.4.1 Exercise 1
Carefully read all of section 8. Execute folds 1-8 in the top section of the worksheet by placing the cursor inside of the fold and then pressing <shift><enter> on the keyboard.

8.4.2 Exercise 2
The code in folds 9 and 10 have errors in them. execute the folds again. Fix the errors and then

8.4.3 Exercise 3
Use the empty fold 11 to calculate the expression 100 - 23;

8.4.4 Exercise 4
Perform the following calculations by creating new folds at the bottom of the worksheet (using the right-click popup menu) and placing each calculation into its own fold: a) 2*7 + 3 b) 18/3 c) 234238342 + 2038408203 d) 324802984 * 2308098234 e) Factor the result which was calculated in d).

v.95b - 08/01/10 Introduction To Programming With MathPiper

41/140

949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980

9 MathPiper Programming Fundamentals


The MathPiper language consists of expressions and an expression consists of one or more symbols which represent values, operators, variables, and functions. In this section expressions are explained along with the values, operators, variables, and functions they consist of.

9.1 Values and Expressions


A value is a single symbol or a group of symbols which represent an idea. For example, the value: 3 represents the number three, the value: 0.5 represents the number one half, and the value: "Mathematics is powerful!" represents an English sentence. Expressions can be created by using values and operators as building blocks. The following are examples of simple expressions which have been created this way: 3 2+3 5 + 6*21/18 - 2^3 In MathPiper, expressions can be evaluated which means that they can be transformed into a result value by predefined rules. For example, when the expression 2 + 3 is evaluated, the result value that is produced is 5:
In> 2 + 3 Result> 5

9.2 Operators
In the above expressions, the characters +, , *, /, ^ are called operators and their purpose is to tell MathPiper what operations to perform on the values in an expression. For example, in the expression 2 + 3, the addition operator + tells MathPiper to add the integer 2 to the integer 3 and return the result. The subtraction operator is , the multiplication operator is *, / is the division operator, % is the remainder operator (which is also used as the

v.95b - 08/01/10 Introduction To Programming With MathPiper 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014

42/140

"result of the last calculation" symbol), and ^ is the exponent operator. MathPiper has more operators in addition to these and some of them will be covered later. The following examples show the , *, /,%, and ^ operators being used:
In> 5 - 2 Result> 3 In> 3*4 Result> 12 In> 30/3 Result> 10 In> 8%5 Result> 3 In> 2^3 Result> 8

The character can also be used to indicate a negative number:


In> -3 Result> -3

Subtracting a negative number results in a positive number (Note: there must be a space between the two negative signs):
In> - -3 Result> 3

In MathPiper, operators are symbols (or groups of symbols) which are implemented with functions. One can either call the function that an operator represents directly or use the operator to call the function indirectly. However, using operators requires less typing and they often make a program easier to read.

9.3 Operator Precedence


When expressions contain more than one operator, MathPiper uses a set of rules called operator precedence to determine the order in which the operators are applied to the values in the expression. Operator precedence is also referred to as the order of operations. Operators with higher precedence are evaluated before operators with lower precedence. The following table shows a subset of MathPiper's operator precedence rules with higher precedence operators being placed higher in the table:

v.95b - 08/01/10 Introduction To Programming With MathPiper 1015 1016 1017 1018 1019 1020 1021 1022 ^ Exponents are evaluated right to left.

43/140

*,%,/ Then multiplication, remainder, and division operations are evaluated left to right. +, Finally, addition and subtraction are evaluated left to right. Lets manually apply these precedence rules to the multi-operator expression we used earlier. Here is the expression in source code form:
5 + 6*21/18 - 2^3

And here it is in traditional form: 56 21 3 2 18

1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044

According to the precedence rules, this is the order in which MathPiper evaluates the operations in this expression: 5 + 6*21/18 - 2^3 5 + 6*21/18 - 8 5 + 126/18 - 8 5 + 7 - 8 12 - 8 4 Starting with the first expression, MathPiper evaluates the ^ operator first which results in the 8 in the expression below it. In the second expression, the * operator is executed next, and so on. The last expression shows that the final result after all of the operators have been evaluated is 4.

9.4 Changing The Order Of Operations In An Expression


The default order of operations for an expression can be changed by grouping various parts of the expression within parentheses (). Parentheses force the code that is placed inside of them to be evaluated before any other operators are evaluated. For example, the expression 2 + 4*5 evaluates to 22 using the default precedence rules:
In> 2 + 4*5 Result> 22

If parentheses are placed around 2 + 4, however, the addition operator is forced to be evaluated before the multiplication operator and the result is 30:

v.95b - 08/01/10 Introduction To Programming With MathPiper 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
In> (2 + 4)*5 Result> 30

44/140

Parentheses can also be nested and nested parentheses are evaluated from the most deeply nested parentheses outward:
In> ((2 + 4)*3)*5 Result> 90

(Note: precedence adjusting parentheses are different from the parentheses that are used to call functions.) Since parentheses are evaluated before any other operators, they are placed at the top of the precedence table: () ^ Parentheses are evaluated from the inside out. Then exponents are evaluated right to left.

*,%,/ Then multiplication, remainder, and division operations are evaluated left to right. +, Finally, addition and subtraction are evaluated left to right.

1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075

9.5 Functions & Function Names


In programming, functions are named blocks of code that can be executed one or more times by being called from other parts of the same program or called from other programs. Functions can have values passed to them from the calling code and they always return a value back to the calling code when they are finished executing. An example of a function is the IsEven() function which was discussed in an previous section. Functions are one way that MathPiper enables code to be reused. Most programming languages allow code to be reused in this way, although in other languages these named blocks of code are sometimes called subroutines, procedures, or methods. The functions that come with MathPiper have names which consist of either a single word (such as Sum()) or multiple words that have been put together to form a compound word (such as IsBound()). All letters in the names of functions which come with MathPiper are lower case except the beginning letter in each word, which are upper case.

v.95b - 08/01/10 Introduction To Programming With MathPiper 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111

45/140

9.6 Functions That Produce Side Effects


Most functions are executed to obtain the results they produce but some functions are executed in order to have them perform work that is not in the form of a result. Functions that perform work that is not in the form of a result are said to produce side effects. Side effects include many forms of work such as sending information to the user, opening files, and changing values in the computer's memory. When a function produces a side effect which sends information to the user, this information has the words Side Effects: placed before it in the output instead of the word Result:. The Echo() and Write() functions are examples of functions that produce side effects and they are covered in the next section.

9.6.1 Printing Related Functions: Echo(), Write(), And Newline()


The printing related functions send text information to the user and this is usually referred to as "printing" in this document. However, it may also be called "echoing" and "writing".
9.6.1.1 Echo()

The Echo() function takes one expression (or multiple expressions separated by commas) evaluates each expression, and then prints the results as side effect output. The following examples illustrate this:
In> Echo(1) Result> True Side Effects> 1

In this example, the number 1 was passed to the Echo() function, the number was evaluated (all numbers evaluate to themselves), and the result of the evaluation was then printed as a side effect. Notice that Echo() also returned a result. In MathPiper, all functions return a result, but functions whose main purpose is to produce a side effect usually just return a result of True if the side effect succeeded or False if it failed. In this case, Echo() returned a result of True because it was able to successfully print a 1 as its side effect. The next example shows multiple expressions being sent to Echo() (notice that the expressions are separated by commas):
In> Echo(1,1+2,2*3) Result> True Side Effects> 1 3 6

v.95b - 08/01/10 Introduction To Programming With MathPiper 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146

46/140

The expressions were each evaluated and their results were returned (separated by spaces) as side effect output. If it is desired that commas be printed between the numbers in the output, simply place three commas between the expressions that are passed to Echo():
In> Echo(1,,,1+2,,,2*3) Result> True Side Effects> 1 , 3 , 6

Each time an Echo() function is executed, it always forces the display to drop down to the next line after it is finished. This can be seen in the following program which is similar to the previous one except it uses a separate Echo() function to display each expression:
%mathpiper Echo(1); Echo(1+2); Echo(2*3); %/mathpiper %output,preserve="false" Result: True Side Effects: 1 3 6 %/output

Notice how the 1, the 3, and the 6 are each on their own line. Now that we have seen how Echo() works, lets use it to do something useful. If more than one expression is evaluated in a %mathpiper fold, only the result from the last expression that was evaluated (which is usually the bottommost expression) is displayed:
%mathpiper a := 1; b := 2; c := 3; %/mathpiper

v.95b - 08/01/10 Introduction To Programming With MathPiper 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172
%output,preserve="false" Result: 3 %/output

47/140

In MathPiper, programs are executed one line at a time, starting at the topmost line of code and working downwards from there. In this example, the line a := 1; is executed first, then the line b := 2; is executed, and so on. Notice, however, that even though we wanted to see what was in all three variables, only the content of the last variable was displayed. The following example shows how Echo() can be used to display the contents of all three variables:
%mathpiper a := 1; Echo(a); b := 2; Echo(b); c := 3; Echo(c); %/mathpiper %output,preserve="false" Result: True Side Effects: 1 2 3 %/output

1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183

9.6.1.2 Echo Functions Are Useful For "Debugging" Programs

The errors that are in a program are often called "bugs". This name came from the days when computers were the size of large rooms and were made using electromechanical parts. Periodically, bugs would crawl into the machines and interfere with its moving mechanical parts and this would cause the machine to malfunction. The bugs needed to be located and removed before the machine would run properly again. Of course, even back then most program errors were produced by programmers entering wrong programs or entering programs wrong, but they liked to say that all of the errors were caused by bugs and not by themselves! The process of fixing errors in a program became known as debugging and the names "bugs"

v.95b - 08/01/10 Introduction To Programming With MathPiper 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 and "debugging" are still used by programmers today.

48/140

One of the standard ways to locate bugs in a program is to place Echo() function calls in the code at strategic places which print the contents of variables and display messages. These Echo() functions will enable you to see what your program is doing while it is running. After you have found and fixed the bugs in your program, you can remove the debugging Echo() function calls or comment them out if you think they may be needed later.
9.6.1.3 Write()

The Write() function is similar to the Echo() function except it does not automatically drop the display down to the next line after it finishes executing:
%mathpiper Write(1,,); Write(1+2,,); Echo(2*3); %/mathpiper %output,preserve="false" Result: True Side Effects: 1,3,6 %/output

Write() and Echo() have other differences besides the one discussed here and more information about them can be found in the documentation for these functions.

1208 1209 1210 1211 1212 1213 1214 1215 1216

9.6.1.4 NewLine()

The NewLine() function simply prints a blank line in the side effects output. It is useful for placing vertical space between printed lines:
%mathpiper a := 1; Echo(a); NewLine(); b := 2; Echo(b);

v.95b - 08/01/10 Introduction To Programming With MathPiper 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
. NewLine(); c := 3; Echo(c); %/mathpiper %output,preserve="false" Result: True Side Effects: 1 2 3 %/output

49/140

1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250

9.7 Expressions Are Separated By Semicolons


As discussed earlier, all of the expressions that are inside of a %mathpiper fold must have a semicolon (;) after them. However, the expressions executed in the MathPiper console did not have a semicolon after them. MathPiper actually requires that all expressions end with a semicolon, but one does not need to add a semicolon to an expression which is typed into the MathPiper console because the console adds it automatically when the expression is executed.

9.7.1 Placing More Than One Expression On A Line In A Fold


All the previous code examples have had each of their expressions on a separate line, but multiple expressions can also be placed on a single line because the semicolons tell MathPiper where one expression ends and the next one begins:
%mathpiper a := 1; Echo(a); b := 2; Echo(b); c := 3; Echo(c); %/mathpiper %output,preserve="false" Result: True Side Effects: 1 2 3 %/output

v.95b - 08/01/10 Introduction To Programming With MathPiper 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265

50/140

The spaces that are in the code of this example are used to make the code more readable. Any spaces that are present within any expressions or between them are ignored by MathPiper and if we remove the spaces from the previous code, the output remains the same:
%mathpiper a:=1;Echo(a);b:=2;Echo(b);c:= 3;Echo(c); %/mathpiper %output,preserve="false" Result: True Side Effects: 1 2 3 %/output

1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288

9.7.2 Placing Multiple Expressions In A Code Block


A code block (which is also called a compound expression) consists of one or more expressions which are separated by semicolons and placed within an open bracket ([) and close bracket (]) pair. When a code block is evaluated, each expression in the block will be executed from left to right. The following example shows expressions being executed within of a code block inside the MathPiper console:
In> [a := 1; Echo(a); b := 2; Echo(b); c := 3; Echo(c);] Result> True Side Effects> 1 2 3

Notice that all of the expressions were executed and 1-3 was printed as a side effect. Code blocks always return the result of the last expression executed as the result of the whole block. In this case, True was returned as the result because the last Echo(c) function returned True. If we place another expression after the Echo(c) function, however, the block will execute this new expression last and its result will be the one returned by the block:
In> [a := 1; Echo(a); b := 2; Echo(b); c := 3; Echo(c); 2 + 2;] Result> 4 Side Effects> 1

v.95b - 08/01/10 Introduction To Programming With MathPiper 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
2 3

51/140

Finally, code blocks can have their contents placed on separate lines if desired:
%mathpiper [ a := 1; Echo(a); b := 2; Echo(b); c := 3; Echo(c); ]; %/mathpiper %output,preserve="false" Result: True Side Effects: 1 2 3 %/output

Code blocks are very powerful and we will be discussing them further in later sections.
9.7.2.1 Automatic Bracket, Parentheses, And Brace Match Indicating

In programming, most open brackets '[' have a close bracket ']', most open parentheses '(' have a close parentheses ')', and most open braces '{' have a close brace '}'. It is often difficult to make sure that each "open" character has a matching "close" character and if any of these characters don't have a match, then an error will be produced. Thankfully, most programming text editors have a character match indicating tool that will help locate problems. To try this tool, paste the following code into a .mpw file and following the directions that are present in its comments:
%mathpiper /*

v.95b - 08/01/10 Introduction To Programming With MathPiper 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
Copy this code into a .mpw file. Then, place the cursor to the immediate right of any {, }, [, ], (, or ) character. You should notice that the match to this character is indicated by a rectangle being drawing around it.

52/140

*/

list := {1,2,3}; [ Echo("Hello"); Echo(list); ]; %/mathpiper

9.8 Strings
A string is a value that is used to hold text-based information. The typical expression that is used to create a string consists of text which is enclosed within double quotes. Strings can be assigned to variables just like numbers can and strings can also be displayed using the Echo() function. The following program assigns a string value to the variable 'a' and then echos it to the user:
%mathpiper a := "Hello, I am a string."; Echo(a); %/mathpiper %output,preserve="false" Result: True Side Effects: Hello, I am a string. %/output

1355 1356 1357 1358 1359 1360 1361 1362

9.8.1 The MathPiper Console and MathPiper Folds Can Access The Same Variables
A useful aspect of using MathPiper inside of MathPiperIDE is that variables that are assigned inside of a %mathpiper fold are accessible inside of the MathPiper console and variables that are assigned inside of the MathPiper console are available inside of %mathpiper folds. For example, after the above fold is executed, the string that has been bound to variable 'a' can be displayed in the MathPiper console:

v.95b - 08/01/10 Introduction To Programming With MathPiper 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
In> a Result> "Hello, I am a string."

53/140

9.8.2 Using Strings To Make Echo's Output Easier To Read


When the Echo() function is used to print the values of multiple variables, it is often helpful to print some information next to each variable so that it is easier to determine which value came from which Echo() function in the code. The following program prints the name of the variable that each value came from next to it in the side effects output:
%mathpiper a := 1; Echo("Variable a: ", a); b := 2; Echo("Variable b: ", b); c := 3; Echo("Variable c: ", c); %/mathpiper %output,preserve="false" Result: True Side Effects: Variable a: 1 Variable b: 2 Variable c: 3 %/output

1387 1388 1389 1390 1391 1392 1393 1394 1395

9.8.2.1 Combining Strings With The : Operator

If you need to combine two or more strings into one string, you can use the : operator like this:
In> "A" : "B" : "C" Result: "ABC" In> "Hello " : "there!" Result: "Hello there!"

9.8.2.2 WriteString()

The WriteString() function prints a string without showing the double quotes

v.95b - 08/01/10 Introduction To Programming With MathPiper 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431

54/140

that are around it.. For example, here is the Write() function being used to print the string "Hello":
In> Write("Hello") Result: True Side Effects: "Hello"

Notice the double quotes? Here is how the WriteString() function prints "Hello":
In> WriteString("Hello") Result: True Side Effects: Hello

9.8.2.3 Nl()

The Nl() (New Line) function is used with the : function to place newline characters inside of strings:
In> WriteString("A": Nl() : "B") Result: True Side Effects: A B

9.8.2.4 Space()

The Space() function is used to add spaces to printed output:


In> WriteString("A"); Space(5); WriteString("B") Result: True Side Effects: A B In> WriteString("A"); Space(10); WriteString("B") Result: True Side Effects: A B In> WriteString("A"); Space(20); WriteString("B") Result: True Side Effects: A B

9.8.3 Accessing The Individual Letters In A String


Individual letters in a string (which are also called characters) can be accessed by placing the character's position number (also called an index) inside of

v.95b - 08/01/10 Introduction To Programming With MathPiper 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464

55/140

brackets [] after the variable it is bound to. A character's position is determined by its distance from the left side of the string starting at 1. For example, in the string "Hello", 'H' is at position 1, 'e' is at position 2, etc. The following code shows individual characters in the above string being accessed:
In> a := "Hello, I am a string." Result> "Hello, I am a string." In> a[1] Result> "H" In> a[2] Result> "e" In> a[3] Result> "l" In> a[4] Result> "l" In> a[5] Result> "o"

9.8.3.1 Indexing Before The Beginning Of A String Or Past The End Of A String

Lets see what happens if an index is used that is less than 1 or greater than the length of a given string. First, we will bind the string "Hello" to the variable 'a':
In> a := "Hello" Result: "Hello"

Then, we'll index the character at position 1 and then the character at position 0:
In> a[1] Result: "H" In> a[0] Result: Exception: In function "StringMidGet" : bad argument number 1(counting from 1) : The offending argument aindex evaluated to 0 In function: Nth,

Notice that using an index of 0 resulted in an error. Next, lets access the character at position 5 (which is the 'o'), then the character at position 6 and finally the character at position 7:

v.95b - 08/01/10 Introduction To Programming With MathPiper 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
In> a[5] Result: "o" In> a[6] Result: """ In> a[7] Result: Exception: String index out of range: 8

56/140

The 'o' at position 5 was returned correctly, but accessing position 6 returned a double quote character (") and accessing position 7 resulted in an error. What you can see in this section is that errors are usually produced if an index is not set to the position of an actual character in a string.

9.9 Comments
Source code can often be difficult to understand and therefore all programming languages provide the ability for comments to be included in the code. Comments are used to explain what the code near them is doing and they are usually meant to be read by humans instead of being processed by a computer. Therefore, comments are ignored by the computer when a program is executed. There are two ways that MathPiper allows comments to be added to source code. The first way is by placing two forward slashes // to the left of any text that is meant to serve as a comment. The text from the slashes to the end of the line the slashes are on will be treated as a comment. Here is a program that contains comments which use slashes:
%mathpiper //This is a comment. x := 2; //Set the variable x equal to 2. %/mathpiper %output,preserve="false" Result: 2 %/output

When this program is executed, any text that starts with slashes is ignored. The second way to add comments to a MathPiper program is by enclosing the comments inside of slash-asterisk/asterisk-slash symbols /* */. This option is useful when a comment is too large to fit on one line. Any text between these symbols is ignored by the computer. This program shows a longer comment which has been placed between these symbols:

v.95b - 08/01/10 Introduction To Programming With MathPiper 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511
%mathpiper /* This is a longer comment and it uses more than one line. The following code assigns the number 3 to variable x and then returns it as a result. */ x := 3; %/mathpiper %output,preserve="false" Result: 3 %/output

57/140

1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535

9.10 How To Tell If MathPiper Has Crashed And What To Do If It Has


Sometimes code will be evaluated which has one or more unusual errors in it and the errors will cause MathPiper to "crash". Unfortunately, beginners are more likely to crash MathPiper than more experienced programmers are because a beginner's program is more likely to have errors in it. When MathPiper crashes, no harm is done but it will not work correctly after that. The only way to recover from a MathPiper crash is to exit MathPiperIDE and then relaunch it. All the information in your buffers will be saved and preserved but the contents of the console will not be. Be sure to copy the contents of the console into a buffer and then save it before restarting. The main way to tell if MathPiperIDE has crashed is that it will indicate that there are errors in lines of code that are actually fine. If you are receiving an error in code that looks okay to you, simply restarting MathPiperIDE may fix the problem. If you restart MathPiperIDE and the error is still present, this usually means that there really is an error in the code.

9.11 Exercises
For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_9_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called: book_1_section_9_exercises_john_smith.mpw. After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution

v.95b - 08/01/10 Introduction To Programming With MathPiper 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 to. The folds you create should look similar to this one:
%mathpiper,title="Exercise 1" //Sample fold. %/mathpiper

58/140

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved.

9.11.1 Exercise 1
Carefully read all of section 9. Evaluate each one of the examples in section 9 in the MathPiper worksheet you created or in the MathPiper console and verify that the results match the ones in the book. Copy all of the console examples you evaluated into your worksheet so they will be saved but do not put them in a fold.

9.11.2 Exercise 2
Change the precedence of the following expression using parentheses so that it prints 20 instead of 14: 2 + 3 * 4

9.11.3 Exercise 3
Place the following calculations into a fold and then use one Echo() function per variable to print the results of the calculations. Put strings in the Echo() functions which indicate which variable each calculated value is bound to: a b c d := := := := 1+2+3+4+5; 1-2-3-4-5; 1*2*3*4*5; 1/2/3/4/5;

9.11.4 Exercise 4
Place the following calculations into a fold and then use one Echo() function to print the results of all the calculations on a single line (Remember, the Echo() function can print multiple values if they are separated by commas.): Unbind(x); a := 2*2*2*2*2; b := 2^5; c := x^2 * x^3; d := 2^2 * 2^3;

v.95b - 08/01/10 Introduction To Programming With MathPiper 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605

59/140

9.11.5 Exercise 5
The following code assigns a string which contains all of the upper case letters of the alphabet to the variable upper. Each of the three Echo() functions prints an index number and the letter that is at that position in the string. Place this code into a fold and then continue the Echo() functions so that all 26 letters and their index numbers are printed upper := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; Echo(1,upper[1]); Echo(2,upper[2]); Echo(3,upper[3]);

9.11.6 Exercise 6
Use Echo() functions to print an index number and the character at this position for the following string (this is similar to what was done in the previous exercise.): extra := ".!@#$%^&*() _+<>,?/{}[]|\-=;"; Echo(1,extra[1]); Echo(2,extra[2]); Echo(3,extra[3]);

9.11.7 Exercise 7
The following program uses strings and index numbers to print a person's name. Create a program which uses the three strings from this program to print the names of three of your favorite musical bands. %mathpiper /* This program uses strings and index numbers to print a person's name. */ upper := "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; lower := "abcdefghijklmnopqrstuvwxyz"; extra := ".!@#$%^&*() _+<>,?/{}[]|\-="; //Print "Mary Smith.". Echo(upper[13],lower[1],lower[18],lower[25],extra[12],upper[19],lower[13],l ower[9],lower[20],lower[8],extra[1]); %/mathpiper %output,preserve="false"

v.95b - 08/01/10 Introduction To Programming With MathPiper 1606 1607 1608 1609 1610
Result: True Side Effects: Mary Smith. %/output

60/140

v.95b - 08/01/10 Introduction To Programming With MathPiper

61/140

1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645

10 Rectangular Selection Mode And Text Area Splitting


10.1 Rectangular Selection Mode
One capability that MathPiperIDE has that a word processor may not have is the ability to select rectangular sections of text. To see how this works, do the following: 1) Type three or four lines of text into a text area. 2) Hold down the <Alt> key then slowly press the backslash key (\) a few times. The bottom of the MathPiperIDE window contains a text field which MathPiperIDE uses to communicate information to the user. As <Alt>\ is repeatedly pressed, messages are displayed which read Rectangular selection is on and Rectangular selection is off. 3) Turn rectangular selection on and then select some text in order to see how this is different than normal selection mode. When you are done experimenting, set rectangular selection mode to off. Most of the time normal selection mode is what you want to use but in certain situations rectangular selection mode is better.

10.2 Text area splitting


Sometimes it is useful to have two or more text areas open for a single document or multiple documents so that different parts of the documents can be edited at the same time. A situation where this would have been helpful was in the previous section where the output from an exercise in a MathPiperIDE worksheet contained a list of index numbers and letters which was useful for completing a later exercise. MathPiperIDE has this ability and it is called splitting. If you look just to the right of the toolbar there is an icon which looks like a blank window, an icon to the right of it which looks like a window which was split horizontally, and an icon to the right of the horizontal one which is split vertically. If you let your mouse hover over these icons, a short description will be displayed for each of them. Select a text area and then experiment with splitting it by pressing the horizontal and vertical splitting buttons. Move around these split text areas with their scroll bars and when you want to unsplit the document, just press the "Unsplit All" icon.

10.3 Exercises
For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_10_exercises_<your first name>_<your last name>.mpw.

v.95b - 08/01/10 Introduction To Programming With MathPiper 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655

62/140

(Note: there are no spaces in this file name). For example, John Smith's worksheet would be called: book_1_section_10_exercises_john_smith.mpw. For the following exercises, simply type your answers anywhere in the worksheet.

10.3.1 Exercise 1
Carefully read all of section 10 then answer the following questions: a) Give two examples where rectangular selection mode may be more useful than regular selection mode. b) How can windows that have been split be unsplit?

v.95b - 08/01/10 Introduction To Programming With MathPiper

63/140

1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695

11 Working With Random Integers


It is often useful to use random integers in a program. For example, a program may need to simulate the rolling of dice in a game. In this section, a function for obtaining nonnegative integers is discussed along with how to use it to simulate the rolling of dice.

11.1 Obtaining Random Integers With The RandomInteger() Function


One way that a MathPiper program can generate random integers is with the RandomInteger() function. The RandomInteger() function takes an integer as a parameter and it returns a random integer between 1 and the passed in integer. The following example shows random integers between 1 and 5 inclusive being obtained from RandomInteger(). Inclusive here means that both 1 and 5 are included in the range of random integers that may be returned. If the word exclusive was used instead, this would mean that neither 1 nor 5 would be in the range.
In> RandomInteger(5) Result> 4 In> RandomInteger(5) Result> 5 In> RandomInteger(5) Result> 4 In> RandomInteger(5) Result> 2 In> RandomInteger(5) Result> 3 In> RandomInteger(5) Result> 5 In> RandomInteger(5) Result> 2 In> RandomInteger(5) Result> 2 In> RandomInteger(5) Result> 1 In> RandomInteger(5) Result> 2

Random integers between 1 and 100 can be generated by passing 100 to RandomInteger():
In> RandomInteger(100) Result> 15 In> RandomInteger(100) Result> 14

v.95b - 08/01/10 Introduction To Programming With MathPiper 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
In> RandomInteger(100) Result> 82 In> RandomInteger(100) Result> 93 In> RandomInteger(100) Result> 32

64/140

A range of random integers that does not start with 1 can also be generated by using the two argument version of RandomInteger(). For example, random integers between 25 and 75 can be obtained by passing RandomInteger() the lowest integer in the range and the highest one:
In> RandomInteger(25, Result: 28 In> RandomInteger(25, Result: 37 In> RandomInteger(25, Result: 58 In> RandomInteger(25, Result: 50 In> RandomInteger(25, Result: 70 75) 75) 75) 75) 75)

11.2 Simulating The Rolling Of Dice


The following example shows the simulated rolling of a single six sided die using the RandomInteger() function:
In> RandomInteger(6) Result> 5 In> RandomInteger(6) Result> 6 In> RandomInteger(6) Result> 3 In> RandomInteger(6) Result> 2 In> RandomInteger(6) Result> 5

Code that simulates the rolling of two 6 sided dice can be evaluated in the MathPiper console by placing it within a code block. The following code outputs the sum of the two simulated dice:
In> [a := RandomInteger(6); b := RandomInteger(6); a + b;] Result> 6 In> [a := RandomInteger(6); b := RandomInteger(6); a + b;] Result> 12 In> [a := RandomInteger(6); b := RandomInteger(6); a + b;] Result> 6

v.95b - 08/01/10 Introduction To Programming With MathPiper 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770
In> [a := RandomInteger(6); b := RandomInteger(6); a + b;] Result> 4 In> [a := RandomInteger(6); b := RandomInteger(6); a + b;] Result> 3 In> [a := RandomInteger(6); b := RandomInteger(6); a + b;] Result> 8

65/140

Now that we have the ability to simulate the rolling of two 6 sided dice, it would be interesting to determine if some sums of these dice occur more frequently than other sums. What we would like to do is to roll these simulated dice hundreds (or even thousands) of times and then analyze the sums that were produced. We don't have the programming capability to easily do this yet, but after we finish the section on While loops, we will.

11.3 Exercises
For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_11_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called: book_1_section_11_exercises_john_smith.mpw. After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:
%mathpiper,title="Exercise 1" //Sample fold. %/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

11.3.1 Exercise 1
Carefully read all of section 11. Evaluate each one of the examples in section 11 in the MathPiper worksheet you created or in the MathPiper console and verify that the results match the ones in the book. Copy all of the console examples you evaluated into your worksheet so they will be saved but do not put them in a fold.

v.95b - 08/01/10 Introduction To Programming With MathPiper

66/140

1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786

12 Making Decisions
The simple programs that have been discussed up to this point show some of the power that software makes available to programmers. However, these programs are limited in their problem solving ability because they are unable to make decisions. This section shows how programs which have the ability to make decisions are able to solve a wider range of problems than programs that can't make decisions.

12.1 Conditional Operators


A program's decision making ability is based on a set of special operators which are called conditional operators. A conditional operator is an operator that is used to compare two values. Expressions that contain conditional operators return a boolean value and a boolean value is one that can only be True or False. In case you are curious about the strange name, boolean values come from the area of mathematics called boolean logic. This logic was created by a mathematician named George Boole and this is where the name boolean came from. Table 2 shows the conditional operators that MathPiper uses:

Operator
x=y

Description
Returns True if the two values are equal and False if they are not equal. Notice that = performs a comparison and not an assignment like := does. Returns True if the values are not equal and False if they are equal. Returns True if the left value is less than the right value and False if the left value is not less than the right value. Returns True if the left value is less than or equal to the right value and False if the left value is not less than or equal to the right value. Returns True if the left value is greater than the right value and False if the left value is not greater than the right value. Returns True if the left value is greater than or equal to the right value and False if the left value is not greater than or equal to the right value.

x != y x<y x <= y x>y x >= y

Table 2: Conditional Operators


1787 1788 1789 1790 This example shows some of these conditional operators being evaluated in the MathPiper console:
In> 1 < 2 Result> True

v.95b - 08/01/10 Introduction To Programming With MathPiper 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829
In> 4 > 5 Result> False In> 8 >= 8 Result> True In> 5 <= 10 Result> True

67/140

The following examples show each of the conditional operators in Table 2 being used to compare values that have been assigned to variables x and y:
%mathpiper // Example 1. x := 2; y := 3; Echo(x, Echo(x, Echo(x, Echo(x, Echo(x, Echo(x, "= ", y, ":", x = y); "!= ", y, ":", x != y); "< ", y, ":", x < y); "<= ", y, ":", x <= y); "> ", y, ":", x > y); ">= ", y, ":", x >= y);

%/mathpiper %output,preserve="false" Result: True Side Effects: 2 = 3 :False 2 != 3 :True 2 < 3 :True 2 <= 3 :True 2 > 3 :False 2 >= 3 :False %/output

%mathpiper // Example 2. x := 2; y := 2; Echo(x, Echo(x, Echo(x, Echo(x, Echo(x, "= ", y, ":", x = y); "!= ", y, ":", x != y); "< ", y, ":", x < y); "<= ", y, ":", x <= y); "> ", y, ":", x > y);

v.95b - 08/01/10 Introduction To Programming With MathPiper 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868
Echo(x, ">= ", y, ":", x >= y); %/mathpiper %output,preserve="false" Result: True Side Effects: 2 = 2 :True 2 != 2 :False 2 < 2 :False 2 <= 2 :True 2 > 2 :False 2 >= 2 :True %/output

68/140

%mathpiper // Example 3. x := 3; y := 2; Echo(x, Echo(x, Echo(x, Echo(x, Echo(x, Echo(x, "= ", y, ":", x = y); "!= ", y, ":", x != y); "< ", y, ":", x < y); "<= ", y, ":", x <= y); "> ", y, ":", x > y); ">= ", y, ":", x >= y);

%/mathpiper %output,preserve="false" Result: True Side Effects: 3 = 2 :False 3 != 2 :True 3 < 2 :False 3 <= 2 :False 3 > 2 :True 3 >= 2 :True %/output

Conditional operators are placed at a lower level of precedence than the other operators we have covered to this point: () ^ Parentheses are evaluated from the inside out. Then exponents are evaluated right to left.

v.95b - 08/01/10 Introduction To Programming With MathPiper 1869 1870 1871 1872

69/140

*,%,/ Then multiplication, remainder, and division operations are evaluated left to right. +, Then addition and subtraction are evaluated left to right. =,!=,<,<=,>,>= Finally, conditional operators are evaluated.

1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898

12.2 Predicate Expressions


Expressions which return either True or False are called "predicate" expressions. By themselves, predicate expressions are not very useful and they only become so when they are used with special decision making functions, like the If() function (which is discussed in the next section).

12.3 Exercises
For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_12a_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called: book_1_section_12a_exercises_john_smith.mpw. After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:
%mathpiper,title="Exercise 1" //Sample fold. %/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

12.3.1 Exercise 1
Carefully read all of section 12 up to this point. Evaluate each one of the examples in the sections you read in the MathPiper worksheet you created or in the MathPiper console and verify that the results match the ones in the book. Copy all of the console examples you evaluated into your worksheet so they will be saved but do not put them in a fold.

v.95b - 08/01/10 Introduction To Programming With MathPiper 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919

70/140

12.3.2 Exercise 2
Open a MathPiper session and evaluate the following predicate expressions:
In> 3 = 3 In> 3 = 4 In> 3 < 4 In> 3 != 4 In> -3 < 4 In> 4 >= 4 In> 1/2 < 1/4 In> 15/23 < 122/189 /*In the following two expressions, notice that 1/2 is not considered to be equal to .5 unless it is converted to a numerical value first.*/ In> 1/2 = .5

In> N(1/2) = .5

12.3.3 Exercise 3
Come up with 10 predicate expressions of your own and evaluate them in the MathPiper console.

12.4 Making Decisions With The If() Function & Predicate Expressions
All programming languages have the ability to make decisions and the most commonly used function for making decisions in MathPiper is the If() function. There are two calling formats for the If() function:
If(predicate, then) If(predicate, then, else)

1920 1921 1922 1923 1924

The way the first form of the If() function works is that it evaluates the first expression in its argument list (which is the "predicate" expression) and then looks at the value that is returned. If this value is True, the "then" expression that is listed second in the argument list is executed. If the predicate expression evaluates to False, the "then" expression is not executed. (Note: any function

v.95b - 08/01/10 Introduction To Programming With MathPiper 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959

71/140

that accepts a predicate expression as a parameter can also accept the boolean values True and False). The following program uses an If() function to determine if the value in variable number is greater than 5. If number is greater than 5, the program will echo "Greater" and then "End of program":
%mathpiper number := 6; If(number > 5, Echo(number, "is greater than 5.")); Echo("End of program."); %/mathpiper %output,preserve="false" Result: True Side Effects: 6 is greater than 5. End of program. %/output

In this program, number has been set to 6 and therefore the expression number > 5 is True. When the If() functions evaluates the predicate expression and determines it is True, it then executes the first Echo() function. The second Echo() function at the bottom of the program prints "End of program" regardless of what the If() function does. (Note: semicolons cannot be placed after expressions which are in function calls.) Here is the same program except that number has been set to 4 instead of 6:
%mathpiper number := 4; If(number > 5, Echo(number, "is greater than 5.")); Echo("End of program."); %/mathpiper %output,preserve="false" Result: True Side Effects: End of program. %/output

v.95b - 08/01/10 Introduction To Programming With MathPiper 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977

72/140

This time the expression number > 4 returns a value of False which causes the If() function to not execute the "then" expression that was passed to it.

12.4.1 If() Functions Which Include An "Else" Parameter


The second form of the If() function takes a third "else" expression which is executed only if the predicate expression is False. This program is similar to the previous one except an "else" expression has been added to it:
%mathpiper x := 4; If(x > 5,Echo(x,"is greater than 5."),Echo(x,"is NOT greater than 5.")); Echo("End of program."); %/mathpiper %output,preserve="false" Result: True Side Effects: 4 is NOT greater than 5. End of program. %/output

1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991

12.5 Exercises
For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_12b_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called: book_1_section_12b_exercises_john_smith.mpw. After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:
%mathpiper,title="Exercise 1" //Sample fold. %/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you

v.95b - 08/01/10 Introduction To Programming With MathPiper 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011

73/140

did in the console into the worksheet so it can be saved but do not put it in a fold.

12.5.1 Exercise 1
Carefully read all of section 12 starting at the end of the previous exercises and up to this point. Evaluate each one of the examples in the sections you read in the MathPiper worksheet you created or in the MathPiper console and verify that the results match the ones in the book. Copy all of the console examples you evaluated into your worksheet so they will be saved but do not put them in a fold.

12.5.2 Exercise 2
Write a program which uses the RandomInteger() function to simulate the flipping of a coin (Hint: you can use 1 to represent a head and 2 to represent a tail.). Use predicate expressions, the If() function, and the Echo() function to print the string "The coin came up heads." or the string "The coin came up tails.", depending on what the simulated coin flip came up as when the code was executed.

12.6 The And(), Or(), & Not() Boolean Functions & Infix Notation 12.6.1 And()
Sometimes a programmer needs to check if two or more expressions are all True and one way to do this is with the And() function. The And() function has two calling formats (or notations) and this is the first one:
And(expression1, expression2, expression3, ..., expressionN)

2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023

This calling format is able to accept one or more predicate expressions as input. If all of these expressions returns a value of True, the And() function will also return a True. However, if any of the expressions return a False, then the And() function will return a False. This can be seen in the following example:
In> And(True, True) Result> True In> And(True, False) Result> False In> And(False, True) Result> False In> And(True, True, True, True) Result> True

v.95b - 08/01/10 Introduction To Programming With MathPiper 2024 2025 2026 2027
In> And(True, True, False, True) Result> False

74/140

The second format (or notation) that can be used to call the And() function is called infix notation:
expression1 And expression2

2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056

With infix notation, an expression is placed on both sides of the And() function name instead of being placed inside of parentheses that are next to it:
In> True And True Result> True In> True And False Result> False In> False And True Result> False In> True And True And True And True Result: True

Infix notation can only accept two expressions at a time, but it is often more convenient to use than function calling notation. The following program also demonstrates the infix version of the And() function being used:
%mathpiper a := 7; b := 9; Echo("1: Echo("2: Echo("3: Echo("4: ", ", ", ", a a a a < > < > 5 5 5 5 And And And And b b b b < > > < 10); 10); 10); 10);

If(a > 5 And b < 10, Echo("These expressions are both true.")); %/mathpiper %output,preserve="false" Result: True Side Effects: 1: False 2: False 3: False

v.95b - 08/01/10 Introduction To Programming With MathPiper 2057 2058 2059


4: True These expressions are both true. %/output

75/140

2060 2061 2062 2063 2064 2065

12.6.2 Or()
The Or() function is similar to the And() function in that it has both a function calling format and an infix calling format and it only works with predicate expressions. However, instead of requiring that all expressions be True in order to return a True, Or() will return a True if one or more expressions are True. Here is the function calling format for Or():
Or(expression1, expression2, expression3, ..., expressionN)

2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077

and this example shows Or() being used with function calling format:
In> Or(True, False) Result> True In> Or(False, True) Result> True In> Or(False, False) Result> False In> Or(False, False, False, False) Result> False In> Or(False, True, False, False) Result> True

The infix notation format for Or() is as follows:


expression1 Or expression2

2078 2079 2080 2081 2082 2083

and this example shows infix notation being used:


In> True Or False Result> True In> False Or True Result> True In> False Or False

v.95b - 08/01/10 Introduction To Programming With MathPiper 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105
Result> False

76/140

The following program also demonstrates the infix version of the Or() function being used:
%mathpiper a := 7; b := 9; Echo("1: Echo("2: Echo("3: Echo("4: ", ", ", ", a a a a < > > < 5 5 5 5 Or Or Or Or b b b b < > < > 10); 10); 10); 10);

If(a < 5 Or b < 10,Echo("At least one of these expressions is true.")); %/mathpiper %output,preserve="false" Result: True Side Effects: 1: True 2: True 3: True 4: False At least one of these expressions is true. %/output

2106 2107 2108 2109 2110

12.6.3 Not() & Prefix Notation


The Not() function works with predicate expressions like the And() and Or() functions do, except it can only accept one expression as input. The way Not() works is that it changes a True value to a False value and a False value to a True value. Here is the Not()'s function calling format:
Not(expression)

2111 2112 2113 2114 2115

and this example shows Not() being used with function calling format:
In> Not(True) Result> False In> Not(False) Result> True

v.95b - 08/01/10 Introduction To Programming With MathPiper 2116 2117

77/140

Instead of providing an alternative infix calling format like And() and Or() do, Not()'s second calling format uses prefix notation:
Not expression

2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134

Prefix notation looks similar to function notation except no parentheses are used:
In> Not True Result> False In> Not False Result> True

Finally, here is a program that also uses the prefix version of Not():
%mathpiper Echo("3 = 3 is ", 3 = 3); Echo("Not 3 = 3 is ", Not 3 = 3); %/mathpiper %output,preserve="false" Result: True Side Effects: 3 = 3 is True Not 3 = 3 is False %/output

2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145

12.7 Exercises
For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_12c_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called: book_1_section_12c_exercises_john_smith.mpw. After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:
%mathpiper,title="Exercise 1"

v.95b - 08/01/10 Introduction To Programming With MathPiper 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
//Sample fold. %/mathpiper

78/140

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

12.7.1 Exercise 1
Carefully read all of section 12 starting at the end of the previous exercises and up to this point. Evaluate each one of the examples in the sections you read in the MathPiper worksheet you created or in the MathPiper console and verify that the results match the ones in the book. Copy all of the console examples you evaluated into your worksheet so they will be saved but do not put them in a fold.

12.7.2 Exercise 2
The following program simulates the rolling of two dice and prints a message if both of the two dice come up less than or equal to 3. Create a similar program which simulates the flipping of two coins and print the message "Both coins came up heads." if both coins come up heads. %mathpiper /* This program simulates the rolling of two dice and prints a message if both of the two dice come up less than or equal to 3. */ die1 := RandomInteger(6); die2 := RandomInteger(6); Echo("Die1: ", die1, " NewLine(); Die2: ", die2);

If( die1 <= 3 And die2 <= 3, Echo("Both dice came up <= to 3.") ); %/mathpiper

12.7.3 Exercise 3
The following program simulates the rolling of two dice and prints a message if either of the two dice come up less than or equal to 3. Create a similar program which simulates the flipping of two coins and print the message "At least one coin came up heads." if at least one coin comes up heads. %mathpiper /* This program simulates the rolling of two dice and prints a message if either of the two dice come up less than or equal to 3.

v.95b - 08/01/10 Introduction To Programming With MathPiper 2183 2184 2185 2186 2187 2188 2189
*/ die1 := RandomInteger(6); die2 := RandomInteger(6); Echo("Die1: ", die1, " NewLine(); Die2: ", die2);

79/140

If( die1 <= 3 Or die2 <= 3, Echo("At least one die came up <= 3.") ); %/mathpiper

v.95b - 08/01/10 Introduction To Programming With MathPiper

80/140

2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224

13 The While() Looping Function & Bodied Notation


Many kinds of machines, including computers, derive much of their power from the principle of repeated cycling. Repeated cycling in a MathPiper program means to execute one or more expressions over and over again and this process is called "looping". MathPiper provides a number of ways to implement loops in a program and these ways range from straight-forward to subtle. We will begin discussing looping in MathPiper by starting with the straightforward While function. The calling format for the While function is as follows:
While(predicate) [ body_expressions ];

The While function is similar to the If function except it will repeatedly execute the expressions it contains as long as its "predicate" expression is True. As soon as the predicate expression returns a False, the While() function skips the expressions it contains and execution continues with the expression that immediately follows the While() function (if there is one). The expressions which are contained in a While() function are called its "body" and all functions which have body expressions are called "bodied" functions. If a body contains more than one expression then these expressions need to be placed within a code block (code blocks were discussed in an earlier section). What a function's body is will become clearer after studying some example programs.

13.1 Printing The Integers From 1 to 10


The following program uses a While() function to print the integers from 1 to 10:
%mathpiper // This program prints the integers from 1 to 10. /*

*/ count := 1;

Initialize the variable count to 1 outside of the While "loop".

While(count <= 10) [ Echo(count);

v.95b - 08/01/10 Introduction To Programming With MathPiper 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266
count := count + 1; //Increment count by 1.

81/140

];

%/mathpiper %output,preserve="false" Result: True Side Effects: 1 2 3 4 5 6 7 8 9 10 %/output

In this program, a single variable called count is created. It is used to tell the Echo() function which integer to print and it is also used in the predicate expression that determines if the While() function should continue to loop or not. When the program is executed, 1 is placed into count and then the While() function is called. Notice that count is bound to the value 1 above the While loop. Setting a variable to an initial value is called initializing the variable and in this case, count needs to be initialized before it is used in the While() function. The predicate expression count <= 10 becomes 1 <= 10 and, since 1 is indeed less than or equal to 10, a value of True is returned by the predicate expression. The While() function sees that the predicate expression returned a True and therefore it executes all of the expressions inside of its body from top to bottom. The Echo() function prints the current contents of count (which is 1) and then the expression count := count + 1 is executed. The expression count := count + 1 is a standard expression form that is used in many programming languages. Each time an expression in this form is evaluated, it increases the variable it contains by 1. Another way to describe the effect this expression has on count is to say that it increments count by 1. In this case count contains 1 and, after the expression is evaluated, count contains 2. After the last expression inside the body of the While() function is executed, the While() function reevaluates its predicate expression to determine whether it should continue looping or not. Since count is 2 at this point, the predicate expression returns True and the code inside the body of the While() function is

v.95b - 08/01/10 Introduction To Programming With MathPiper 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301

82/140

executed again. This loop will be repeated until count is incremented to 11 and the predicate expression returns False.

13.2 Printing The Integers From 1 to 100


The previous program can be adjusted in a number of ways to achieve different results. For example, the following program prints the integers from 1 to 100 by changing the 10 in the predicate expression to 100. A Write() function is used in this program so that its output is displayed on the same line until it encounters the wrap margin in MathPiperIDE (which can be set in Utilities -> Buffer Options...).
%mathpiper // Print the integers from 1 to 100. count := 1; While(count <= 100) [ Write(count,,); ]; count := count + 1; //Increment count by 1.

%/mathpiper %output,preserve="false" Result: True Side Effects: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23, 24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43, 44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63, 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83, 84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100 %/output

(Note: In MathPiperIDE, the above numbers will all be on a single line.)

13.3 Printing The Odd Integers From 1 To 99


The following program prints the odd integers from 1 to 99 by changing the increment value in the increment expression from 1 to 2:
%mathpiper //Print the odd integers from 1 to 99.

v.95b - 08/01/10 Introduction To Programming With MathPiper 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
x := 1; While(x <= 100) [ Write(x,,); x := x + 2; ]; %/mathpiper %output,preserve="false" Result: True Side Effects: 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43, 45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83, 85,87,89,91,93,95,97,99 %/output

83/140

//Increment x by 2.

2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338

13.4 Printing The Integers From 1 To 100 In Reverse Order


Finally, the following program prints the integers from 1 to 100 in reverse order:
%mathpiper //Print the integers from 1 to 100 in reverse order. x := 100; While(x >= 1) [ Write(x,,); x := x - 1; ]; %/mathpiper %output,preserve="false" Result: True Side Effects: 100,99,98,97,96,95,94,93,92,91,90,89,88,87,86,85,84,83,82, 81,80,79,78,77,76,75,74,73,72,71,70,69,68,67,66,65,64,63, 62,61,60,59,58,57,56,55,54,53,52,51,50,49,48,47,46,45,44, 43,42,41,40,39,38,37,36,35,34,33,32,31,30,29,28,27,26,25, 24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4, 3,2,1 %/output

//Decrement x by 1.

v.95b - 08/01/10 Introduction To Programming With MathPiper 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366

84/140

In order to achieve the reverse ordering, this program had to initialize x to 100, check to see if x was greater than or equal to 1 (x >= 1), and decrement x by subtracting 1 from it instead of adding 1 to it.

13.5 Expressions Inside Of Code Blocks Are Indented


In the programs in the previous sections which use While loops, notice that the expressions which are inside of the While() function's code block are indented. These expressions do not need to be indented to execute properly, but doing so makes the program easier to read.

13.6 Long-Running Loops, Infinite Loops, & Interrupting Execution


It is easy to create a loop that will execute a large number of times, or even an infinite number of times, either on purpose or by mistake. When you execute a program that contains an infinite loop, it will run until you tell MathPiper to interrupt its execution. This is done by opening the MathPiper console and then pressing the "Halt Calculation" button which in the upper left corner of the console. Lets experiment with the Halt Calculation button by executing a program that contains an infinite loop and then stopping it:
%mathpiper //Infinite loop example program. x := 1; While(x < 10) [ x := 3; //Oops, x is not being incremented!. ]; %/mathpiper %output,preserve="false" Processing... %/output

2367 2368 2369 2370 2371 2372 2373

Since the contents of x is never changed inside the loop, the expression x < 10 always evaluates to True which causes the loop to continue looping. Notice that the %output fold contains the word "Processing..." to indicate that the program is still running the code. Execute this program now and then interrupt it using the Halt Calculation button. When the program is interrupted, the %output fold will display the message "User interrupted calculation" to indicate that the program was

v.95b - 08/01/10 Introduction To Programming With MathPiper 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412

85/140

interrupted. After a program has been interrupted, the program can be edited and then rerun.

13.7 A Program That Simulates Rolling Two Dice 50 Times


The following program is larger than the previous programs that have been discussed in this book, but it is also more interesting and more useful. It uses a While() loop to simulate the rolling of two dice 50 times and it records how many times each possible sum has been rolled so that this data can be printed. The comments in the code explain what each part of the program does. (Remember, if you copy this program to a MathPiperIDE worksheet, you can use rectangular selection mode to easily remove the line numbers).
%mathpiper /* This program simulates rolling two dice 50 times. */ /*

These variables are used to record how many times a possible sum of two dice has been rolled. They are all initialized to 0 before the simulation begins.

*/ numberOfTwosRolled := 0; numberOfThreesRolled := 0; numberOfFoursRolled := 0; numberOfFivesRolled := 0; numberOfSixesRolled := 0; numberOfSevensRolled := 0; numberOfEightsRolled := 0; numberOfNinesRolled := 0; numberOfTensRolled := 0; numberOfElevensRolled := 0; numberOfTwelvesRolled := 0; //This variable keeps track of the number of the current roll. roll := 1; Echo("These are the rolls:"); /* The simulation is performed inside of this While loop. The number of times the dice will be rolled can be changed by changing the number 50 which is in the While function's predicate expression. */ While(roll <= 50)

v.95b - 08/01/10 Introduction To Programming With MathPiper 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462
[ //Roll the dice. die1 := RandomInteger(6); die2 := RandomInteger(6); //Calculate the sum of the two dice. rollSum := die1 + die2;

86/140

/* Print the sum that was rolled. Note: if a large number of rolls is going to be performed (say > 1000), it would be best to comment out this Write() function so that it does not put too much text into the output fold. */ Write(rollSum,,); /* These If() functions determine which sum was rolled and then add 1 to the variable which is keeping track of the number of times that sum was rolled. */ If(rollSum = 2, numberOfTwosRolled := numberOfTwosRolled + 1); If(rollSum = 3, numberOfThreesRolled := numberOfThreesRolled + 1); If(rollSum = 4, numberOfFoursRolled := numberOfFoursRolled + 1); If(rollSum = 5, numberOfFivesRolled := numberOfFivesRolled + 1); If(rollSum = 6, numberOfSixesRolled := numberOfSixesRolled + 1); If(rollSum = 7, numberOfSevensRolled := numberOfSevensRolled + 1); If(rollSum = 8, numberOfEightsRolled := numberOfEightsRolled + 1); If(rollSum = 9, numberOfNinesRolled := numberOfNinesRolled + 1); If(rollSum = 10, numberOfTensRolled := numberOfTensRolled + 1); If(rollSum = 11, numberOfElevensRolled := numberOfElevensRolled+1); If(rollSum = 12, numberOfTwelvesRolled := numberOfTwelvesRolled+1); //Increment the roll variable to the next roll number. roll := roll + 1; ]; //Print the contents of the sum count variables for visual analysis. NewLine(); NewLine(); Echo("Number of Twos rolled: ", numberOfTwosRolled); Echo("Number of Threes rolled: ", numberOfThreesRolled); Echo("Number of Fours rolled: ", numberOfFoursRolled); Echo("Number of Fives rolled: ", numberOfFivesRolled); Echo("Number of Sixes rolled: ", numberOfSixesRolled); Echo("Number of Sevens rolled: ", numberOfSevensRolled); Echo("Number of Eights rolled: ", numberOfEightsRolled);

v.95b - 08/01/10 Introduction To Programming With MathPiper 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
Echo("Number Echo("Number Echo("Number Echo("Number %/mathpiper %output,preserve="false" Result: True Side effects: These are the rolls: 4,8,6,4,6,9,7,11,9,3,11,6,11,7,11,4,7,7,8,7,3,6,7,7,7,12,4, 12,7,8,12,6,8,10,10,5,9,8,4,5,3,5,7,7,4,6,7,7,5,8, Number Number Number Number Number Number Number Number Number Number Number %/output of of of of of of of of of of of Twos rolled: 0 Threes rolled: 3 Fours rolled: 6 Fives rolled: 4 Sixes rolled: 6 Sevens rolled: 13 Eights rolled: 6 Nines rolled: 3 Tens rolled: 2 Elevens rolled: 4 Twelves rolled: 3 of of of of Nines rolled: ", numberOfNinesRolled); Tens rolled: ", numberOfTensRolled); Elevens rolled: ", numberOfElevensRolled); Twelves rolled: ", numberOfTwelvesRolled);

87/140

2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500

13.8 Exercises
For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_13_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called: book_1_section_13_exercises_john_smith.mpw. After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:
%mathpiper,title="Exercise 1" //Sample fold. %/mathpiper

v.95b - 08/01/10 Introduction To Programming With MathPiper 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518

88/140

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

13.8.1 Exercise 1
Carefully read all of section 13 up to this point. Evaluate each one of the examples in the sections you read in the MathPiper worksheet you created or in the MathPiper console and verify that the results match the ones in the book. Copy all of the console examples you evaluated into your worksheet so they will be saved but do not put them in a fold.

13.8.2 Exercise 2
Create a program which uses a While loop to print the even integers from 2 to 50 inclusive.

13.8.3 Exercise 3
Create a program which prints all the multiples of 5 between 5 and 50 inclusive.

13.8.4 Exercise 4
Create a program which simulates the flipping of a single coin 500 times. Print the number of times the coin came up heads and the number of times it came up tails after the loop is finished executing.

v.95b - 08/01/10 Introduction To Programming With MathPiper

89/140

2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551

14 Predicate Functions
A predicate function is a function that either returns True or False. Most predicate functions in MathPiper have names which begin with "Is". For example, IsEven(), IsOdd(), IsInteger(), etc. The following examples show some of the predicate functions that are in MathPiper:
In> IsEven(4) Result> True In> IsEven(5) Result> False In> IsZero(0) Result> True In> IsZero(1) Result> False In> IsNegativeInteger(-1) Result> True In> IsNegativeInteger(1) Result> False In> IsPrime(7) Result> True In> IsPrime(100) Result> False

There is also an IsBound() predicate function that can be used to determine whether or not a value is bound to a given variable:
In> a Result> a In> IsBound(a) Result> False In> a := 1 Result> 1 In> IsBound(a) Result> True In> Unbind(a) Result> True

v.95b - 08/01/10 Introduction To Programming With MathPiper 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591
In> a Result> a In> IsBound(a) Result> False

90/140

The complete list of predicate functions is contained in the User Functions/Predicates node in the MathPiperDocs plugin.

14.1 Finding Prime Numbers With A Loop


Predicate functions are very powerful when they are combined with loops because they can be used to automatically make numerous checks. The following program uses a While loop to pass the integers 1 through 20 (one at a time) to the IsPrime() function in order to determine which integers are prime and which integers are not prime:
%mathpiper //Determine which numbers between 1 and 20 (inclusive) are prime. x := 1; While(x <= 20) [ primeStatus := IsPrime(x); Echo(x, "is prime: ", primeStatus); ]; x := x + 1;

%/mathpiper %output,preserve="false" Result: True Side Effects: 1 is prime: False 2 is prime: True 3 is prime: True 4 is prime: False 5 is prime: True 6 is prime: False 7 is prime: True 8 is prime: False 9 is prime: False 10 is prime: False 11 is prime: True 12 is prime: False

v.95b - 08/01/10 Introduction To Programming With MathPiper 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629
13 is prime: 14 is prime: 15 is prime: 16 is prime: 17 is prime: 18 is prime: 19 is prime: 20 is prime: %/output True False False False True False True False

91/140

This program worked fairly well, but it is limited because it prints a line for each prime number and also each non-prime number. This means that if large ranges of integers were processed, enormous amounts of output would be produced. The following program solves this problem by using an If() function to only print a number if it is prime:
%mathpiper //Print the prime numbers between 1 and 50 (inclusive). x := 1; While(x <= 50) [ primeStatus := IsPrime(x); If(primeStatus = True, Write(x,,) ); x := x + 1; ]; %/mathpiper %output,preserve="false" Result: True Side Effects: 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47, %/output

This program is able to process a much larger range of numbers than the previous one without having its output fill up the text area. However, the program itself can be shortened by moving the IsPrime() function inside of the If() function instead of using the primeStatus variable to communicate with it:
%mathpiper /*

v.95b - 08/01/10 Introduction To Programming With MathPiper 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647
]; %/mathpiper %output,preserve="false" Result: True Side Effects: 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47, %/output Print the prime numbers between 1 and 50 (inclusive). This is a shorter version which places the IsPrime() function inside of the If() function instead of using a variable. */ x := 1; While(x <= 50) [ If(IsPrime(x), Write(x,,) ); x := x + 1;

92/140

2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663

14.2 Finding The Length Of A String With The Length() Function


Strings can contain zero or more characters and the Length() function can be used to determine how many characters a string holds:
In> s := "Red" Result> "Red" In> Length(s) Result> 3

In this example, the string "Red" is assigned to the variable s and then s is passed to the Length() function. The Length() function returned a 3 which means the string contained 3 characters. The following example shows that strings can also be passed to functions directly:
In> Length("Red") Result> 3

An empty string is represented by two double quote marks with no space in between them. The length of an empty string is 0:

v.95b - 08/01/10 Introduction To Programming With MathPiper 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697
In> Length("") Result> 0

93/140

14.3

Converting Numbers To Strings With The ToString() Function

Sometimes it is useful to convert a number to a string so that the individual digits in the number can be analyzed or manipulated. The following example shows a number being converted to a string with the ToString() function so that its leftmost and rightmost digits can be placed into variables:
In> number := 523 Result> 523 In> stringNumber := ToString(number) Result> "523" In> leftmostDigit := stringNumber[1] Result> "5" In> rightmostDigit := stringNumber[ Length(stringNumber) ] Result> "3"

Notice that the Length() function is used here to determine which character in stringNumber held the rightmost digit. Also, keep in mind that when numbers are in string form, operations such as +, -, *, and / cannot be performed on them.

14.4 Finding Prime Numbers Which End With 7 (And Multi-line Function Calls)
Now that we have covered how to turn a number into a string, lets use this ability inside a loop. The following program finds all the prime numbers between 1 and 500 which have a 7 as their rightmost digit. There are three important things which are shown in this program: 1) Function calls can have their parameters placed on more than one line if the parameters are too long to fit on a single line. In this case, a long code block is being placed inside of an If() function. 2) Code blocks (which are considered to be compound expressions) cannot have a semicolon placed after them if they are in a function call. If a semicolon is placed after this code block, an error will be produced. 3) If() functions can be placed inside of other If() functions in order to make more complex decisions. This is referred to as nesting functions. When the program is executed, it finds 24 prime numbers which have 7 as their

v.95b - 08/01/10 Introduction To Programming With MathPiper 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 rightmost digit:
%mathpiper /* */ Find all the prime numbers between 1 and 500 which have a 7 as their rightmost digit.

94/140

x := 1; While(x <= 500) [ //Notice how function parameters can be put on more than one line. If(IsPrime(x), [ stringVersionOfNumber := ToString(x); stringLength := Length(stringVersionOfNumber); //Notice that If() functions can be placed inside of other // If() functions. If(stringVersionOfNumber[stringLength] = "7", Write(x,,) ); ] //Notice that semicolons cannot be placed after code blocks //which are in function calls. ); //This is the close parentheses for the outer If() function. x := x + 1; ]; %/mathpiper %output,preserve="false" Result: True Side Effects: 7,17,37,47,67,97,107,127,137,157,167,197,227,257,277,307,317, 337,347,367,397,457,467,487, %/output

It would be nice if we had the ability to store these numbers someplace so that they could be processed further and this is discussed in the next section.

14.5 Exercises
For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_14_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's

v.95b - 08/01/10 Introduction To Programming With MathPiper 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 worksheet would be called: book_1_section_14_exercises_john_smith.mpw.

95/140

After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:
%mathpiper,title="Exercise 1" //Sample fold. %/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

14.5.1 Exercise 1
Write a program which uses a While loop to determine how many prime numbers there are between 1 and 1000. You do not need to print the numbers themselves, just how many there are.

14.5.2 Exercise 2
Write a program which uses a While loop to print all of the prime numbers between 10 and 99 which contain the digit 3 in either their 1's place or their 10's place.

v.95b - 08/01/10 Introduction To Programming With MathPiper

96/140

2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791

15 Lists: Values That Hold Sequences Of Expressions


The list value type is designed to hold expressions in an ordered collection or sequence. Lists are very flexible and they are one of the most heavily used value types in MathPiper. Lists can hold expressions of any type, they can be made to grow and shrink as needed, and they can be nested. Expressions in a list can be accessed by their position in the list (similar to the way that characters in a string are accessed) and they can also be replaced by other expressions. One way to create a list is by placing zero or more expressions separated by commas inside of a pair of braces {}. In the following example, a list is created that contains various expressions and then it is assigned to the variable x:
In> exampleList := {7,42,"Hello",1/2,var} Result> {7,42,"Hello",1/2,var} In> exampleList Result> {7,42,"Hello",1/2,var}

The number of expressions in a list can be determined with the Length() function:
In> Length({7,42,"Hello",1/2,var}) Result> 5

A single expression in a list can be accessed by placing a set of brackets [] to the right of the variable that is bound to the list and then putting the expression's position number inside of the brackets (Note: the first expression in the list is at position 1 counting from the left end of the list):
In> exampleList[1] Result> 7 In> exampleList[2] Result> 42 In> exampleList[3] Result> "Hello" In> exampleList[4] Result> 1/2 In> exampleList[5] Result> var

The 1st and 2nd expressions in this list are integers, the 3rd expression is a

v.95b - 08/01/10 Introduction To Programming With MathPiper 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814

97/140

string, the 4th expression is a rational number and the 5th expression is an unbound variable. Lists can also hold other lists as shown in the following example:
In> exampleList := {20, 30, {31, 32, 33}, 40} Result> {20,30,{31,32,33},40} In> exampleList[1] Result> 20 In> exampleList[2] Result> 30 In> exampleList[3] Result> {31,32,33} In> exampleList[4] Result> 40

The expression in the 3rd position in the list is another list which contains the integers 31, 32, and 33. An expression in this second list can be accessed by two two sets of brackets:
In> exampleList[3][2] Result> 32

The 3 inside of the first set of brackets accesses the 3rd member of the first list and the 2 inside of the second set of brackets accesses the 2nd member of the second list.

15.1 Append() & Nondestructive List Operations


Append(list, expression)

2815 2816 2817 2818 2819 2820 2821 2822

The Append() function adds an expression to the end of a list:


In> testList := {21,22,23} Result> {21,22,23} In> Append(testList, 24) Result> {21,22,23,24}

However, instead of changing the original list, Append() creates a copy of the original list and appends the expression to the copy. This can be confirmed by evaluating the variable testList after the Append() function has been called:

v.95b - 08/01/10 Introduction To Programming With MathPiper 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855
In> testList Result> {21,22,23}

98/140

Notice that the list that is bound to testList was not modified by the Append() function. This is called a nondestructive list operation and most MathPiper functions that manipulate lists do so nondestructively. To have the new list bound to the variable that is being used, the following technique can be employed:
In> testList := {21,22,23} Result> {21,22,23} In> testList := Append(testList, 24) Result> {21,22,23,24} In> testList Result> {21,22,23,24}

After this code has been executed, the new list has indeed been bound to testList as desired. There are some functions, such as DestructiveAppend(), which do change the original list and most of them begin with the word "Destructive". These are called "destructive functions" and they are advanced functions which are not covered in this book.

15.2 Using While Loops With Lists


Functions that loop can be used to select each expression in a list in turn so that an operation can be performed on these expressions. The following program uses a While loop to print each of the expressions in a list:
%mathpiper //Print each number in the list. testList := {55,93,40,21,7,24,15,14,82}; index := 1; While(index <= Length(testList)) [ Echo(index, "- ", testList[index]); ]; index := index + 1;

%/mathpiper

v.95b - 08/01/10 Introduction To Programming With MathPiper 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892
%output,preserve="false" Result: True Side Effects: 1 - 55 2 - 93 3 - 40 4 - 21 5 - 7 6 - 24 7 - 15 8 - 14 9 - 82 %/output

99/140

A loop can also be used to search through a list. The following program uses a While() function and an If() function to search through a list to see if it contains the number 53. If 53 is found in the list, a message is printed:
%mathpiper //Determine if 53 is in the list. testList := {18,26,32,42,53,43,54,6,97,41}; index := 1; While(index <= Length(testList)) [ If(testList[index] = 53, Echo("53 was found in the list at position", index)); index := index + 1; ]; %/mathpiper %output,preserve="false" Result: True Side Effects: 53 was found in the list at position 5 %/output

When this program was executed, it determined that 53 was present in the list at position 5.

v.95b - 08/01/10 Introduction To Programming With MathPiper 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930

100/140

15.2.1 Using A While Loop And Append() To Place Values Into A List
In an earlier section it was mentioned that it would be nice if we could store a set of values for later processing and this can be done with a While loop and the Append() function. The following program creates an empty list and assigned it to the variable primes. The While loop and the IsPrime() function is then used to locate the prime integers between 1 and 50 and the Append() function is used to place them in the list. The last part of the program then prints some information about the numbers that were placed into the list:
%mathpiper //Place the prime numbers between 1 and 50 (inclusive) into a list. //Create an empty list. primesList := {}; index := 1; While(index <= 50) [ /* If x is prime, append it to the end of the list and then assign the new list that is created to the variable 'primes'. */ If(IsPrime(index), primesList := Append(primesList, index ) ); ]; index := index + 1;

//Print information about the primes that were found. Echo("Primes ", primesList); Echo("The number of primes in the list = ", Length(primesList) ); Echo("The first number in the list = ", primesList[1] ); %/mathpiper %output,preserve="false" Result: True Side Effects: Primes {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47} The number of primes in the list = 15 The first number in the list = 2 %/output

The ability to place values into a list with a loop is very powerful and we will be using this ability throughout the rest of the book.

v.95b - 08/01/10 Introduction To Programming With MathPiper 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963

101/140

15.3 Exercises
For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_15a_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called: book_1_section_15a_exercises_john_smith.mpw. After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:
%mathpiper,title="Exercise 1" //Sample fold. %/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

15.3.1 Exercise 1
Create a program that uses a While loop and an IsOdd() predicate function to analyze the following list and then print the number of odd numbers it contains. {73,94,80,37,56,94,40,21,7,24,15,14,82,93,32,74,22,68,65,52,85,61,46,86,25}

15.3.2 Exercise 2
Create a program that uses a While loop and an IsNegativeNumber() function to copy all of the negative numbers in the following list into a new list. Use the variable negativeNumbersList to hold the new list. Print the contents of the list after it has been created. {36,-29,-33,-6,14,7,-16,-3,-14,37,-38,-8,-45,-21,-26,6,6,38,-20,33,41,4,24,37,40,29}

15.3.3 Exercise 3
Create one program that uses a single While loop to analyze the following list and then print the following information about it: 1) The largest number in the list. 2) The smallest number in the list. 3) The sum of all the numbers in the list.

v.95b - 08/01/10 Introduction To Programming With MathPiper 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989

102/140

{73,12,80,37,56,94,40,21,7,24,15,14,82,93,32,74,22,68,65,52,85,61,46,86,25} Hint: the following program finds the largest number in a list and it can be used as a starting point for solving this exercise. %mathpiper /* The variable that keeps track of the largest number encountered so far needs to be initialized to the lowest possible value it may hold. Why? */ largest := 0; numbersList := {4,6,7,9,2,1,3}; index := 1; While(index <= Length(numbersList) ) [ Echo("Largest: ", largest); If(numbersList[index] > largest, largest := numbersList[index]); index := index + 1; ]; Echo("The largest number in the list is: ", largest); %/mathpiper

15.4 The ForEach() Looping Function


The ForEach() function uses a loop to index through a list like the While() function does, but it is more flexible and automatic. ForEach() also uses bodied notation like the While() function and here is its calling format:
ForEach(variable, list) body

2990 2991 2992 2993 2994

ForEach() selects each expression in a list in turn, assigns it to the passed-in "variable", and then executes the expressions that are inside of "body". Therefore, body is executed once for each expression in the list.

15.5 Print All The Values In A List Using A ForEach() function


This example shows how ForEach() can be used to print all of the items in a list:

v.95b - 08/01/10 Introduction To Programming With MathPiper 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016
%mathpiper //Print all values in a list. ForEach(value, {50,51,52,53,54,55,56,57,58,59}) [ Echo(value); ]; %/mathpiper %output,preserve="false" Result: True Side Effects: 50 51 52 53 54 55 56 57 58 59 %/output

103/140

3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032

15.6 Calculate The Sum Of The Numbers In A List Using ForEach()


In previous examples, counting code in the form x := x + 1 was used to count how many times a While loop was executed. The following program uses a ForEach() function and a line of code similar to this counter to calculate the sum of the numbers in a list:
%mathpiper /* This program calculates the sum of the numbers in a list. */ //This variable is used to accumulate the sum. sum := 0; ForEach(number, {1,2,3,4,5,6,7,8,9,10} ) [ /* Add the contents of x to the contents of sum

v.95b - 08/01/10 Introduction To Programming With MathPiper 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056
and place the result back into sum. */ sum := sum + number; //Print the sum as it is being accumulated. Write(sum,,);

104/140

];

NewLine(); NewLine(); Echo("The sum of the numbers in the list = ", sum); %/mathpiper %output,preserve="false" Result: True Side Effects: 1,3,6,10,15,21,28,36,45,55, . The sum of the numbers in the list = 55 %/output

In the above program, the integers 1 through 10 were manually placed into a list by typing them individually. This method is limited because only a relatively small number of integers can be placed into a list this way. The following section discusses an operator which can be used to automatically place a large number of integers into a list with very little typing.

15.7 The .. Range Operator


first .. last

3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068

A programmer often needs to create a list which contains consecutive integers and the .. "range" operator can be used to do this. The first integer in the list is placed before the .. operator and the last integer in the list is placed after it (Note: there must be a space immediately to the left of the .. operator and a space immediately to the right of it or an error will be generated.). Here are some examples:
In> 1 .. 10 Result> {1,2,3,4,5,6,7,8,9,10} In> 10 .. 1 Result> {10,9,8,7,6,5,4,3,2,1} In> 1 .. 100 Result> {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,

v.95b - 08/01/10 Introduction To Programming With MathPiper 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107
21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37, 38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54, 55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71, 72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88, 89,90,91,92,93,94,95,96,97,98,99,100} In> -10 .. 10 Result> {-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10}

105/140

As these examples show, the .. operator can generate lists of integers in ascending order and descending order. It can also generate lists that are very large and ones that contain negative integers. Remember, though, if one or both of the spaces around the .. are omitted, an error is generated:
In> 1..3 Result> Error parsing expression, near token .3.

15.8 Using ForEach() With The Range Operator To Print The Prime Numbers Between 1 And 100
The following program shows how to use a ForEach() function instead of a While() function to print the prime numbers between 1 and 100. Notice that loops that are implemented with ForEach() often require less typing than their While() based equivalents:
%mathpiper /* This program prints the prime integers between 1 and 100 using a ForEach() function instead of a While() function. Notice that the ForEach() version requires less typing than the While() version. */ ForEach(number, 1 .. 100) [ If(IsPrime(number), Write(number,,) ); ]; %/mathpiper %output,preserve="false" Result: True Side Effects: 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71, 73,79,83,89,97,

v.95b - 08/01/10 Introduction To Programming With MathPiper 3108


. %/output

106/140

3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145

15.8.1 Using ForEach() And The Range Operator To Place The Prime Numbers Between 1 And 50 Into A List
A ForEach() function can also be used to place values in a list, just the While() function can:
%mathpiper /* */ Place the prime numbers between 1 and 50 into a list using a ForEach() function.

//Create a new list. primesList := {}; ForEach(number, 1 .. 50) [ /* If number is prime, append it to the end of the list and then assign the new list that is created to the variable 'primes'. */ If(IsPrime(number), primesList := Append(primesList, number ) ); ]; //Print information about the primes that were found. Echo("Primes ", primesList); Echo("The number of primes in the list = ", Length(primesList) ); Echo("The first number in the list = ", primesList[1] ); %/mathpiper %output,preserve="false" Result: True Side Effects: Primes {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47} The number of primes in the list = 15 The first number in the list = 2 %/output

As can be seen from the above examples, the ForEach() function and the range operator can do a significant amount of work with very little typing. You will discover in the next section that MathPiper has functions which are even more powerful than these two.

v.95b - 08/01/10 Introduction To Programming With MathPiper 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178

107/140

15.8.2 Exercises
For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_15b_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called: book_1_section_15b_exercises_john_smith.mpw. After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:
%mathpiper,title="Exercise 1" //Sample fold. %/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

15.8.3 Exercise 1
Create a program that uses a ForEach() function and an IsOdd() predicate function to analyze the following list and then print the number of odd numbers it contains. {73,94,80,37,56,94,40,21,7,24,15,14,82,93,32,74,22,68,65,52,85,61,46,86,25}

15.8.4 Exercise 2
Create a program that uses a ForEach() function and an IsNegativeNumber() function to copy all of the negative numbers in the following list into a new list. Use the variable negativeNumbersList to hold the new list. Print the contents of the list after it has been created. {36,-29,-33,-6,14,7,-16,-3,-14,37,-38,-8,-45,-21,-26,6,6,38,-20,33,41,4,24,37,40,29}

15.8.5 Exercise 3
Create one program that uses a single ForEach() function to analyze the following list and then print the following information about it: 1) The largest number in the list. 2) The smallest number in the list. 3) The sum of all the numbers in the list.

v.95b - 08/01/10 Introduction To Programming With MathPiper 3179 3180 3181 3182 3183 3184

108/140

{73,94,80,37,56,94,40,21,7,24,15,14,82,93,32,74,22,68,65,52,85,61,46,86,25}

15.8.6 Exercise 4
Create one program that does the following: 1) uses a While loop to make a list that contains 1000 random integers between 1 and 100 inclusive. 2) uses a ForEach() function to determine how many integers in the list are prime and use an Echo() function to print this total.

v.95b - 08/01/10 Introduction To Programming With MathPiper

109/140

3185 3186 3187 3188 3189 3190 3191 3192

16 Functions & Operators Which Loop Internally


Looping is such a useful capability that MathPiper has many functions which loop internally. Now that you have some experience with loops, you can use this experience to help you imagine how these functions use loops to process the information that is passed to them.

16.1 Functions & Operators Which Loop Internally To Process Lists


This section discusses a number of functions that use loops to process lists.

16.1.1 TableForm()
TableForm(list)

3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214

The TableForm() function prints the contents of a list in the form of a table. Each member in the list is printed on its own line and this sometimes makes the contents of the list easier to read:
In> testList := {2,4,6,8,10,12,14,16,18,20} Result> {2,4,6,8,10,12,14,16,18,20} In> TableForm(testList) Result> True Side Effects> 2 4 6 8 10 12 14 16 18 20

16.1.2 Contains()
The Contains() function searches a list to determine if it contains a given expression. If it finds the expression, it returns True and if it doesn't find the expression, it returns False. Here is the calling format for Contains():
Contains(list, expression)

v.95b - 08/01/10 Introduction To Programming With MathPiper 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224

110/140

The following code shows Contains() being used to locate a number in a list:
In> Contains({50,51,52,53,54,55,56,57,58,59}, 53) Result> True In> Contains({50,51,52,53,54,55,56,57,58,59}, 75) Result> False

The Not() function can also be used with predicate functions like Contains() to change their results to the opposite truth value:
In> Not Contains({50,51,52,53,54,55,56,57,58,59}, 75) Result> True

16.1.3 Find()
Find(list, expression)

3225 3226 3227 3228 3229 3230 3231 3232

The Find() function searches a list for the first occurrence of a given expression. If the expression is found, the position of its first occurrence is returned and if it is not found, -1 is returned:
In> Find({23, 15, 67, 98, 64}, 15) Result> 2 In> Find({23, 15, 67, 98, 64}, 8) Result> -1

16.1.4 Count()
Count(list, expression)

3233 3234 3235 3236 3237 3238 3239 3240 3241

Count() determines the number of times a given expression occurs in a list:


In> testList := {a,b,b,c,c,c,d,d,d,d,e,e,e,e,e} Result> {a,b,b,c,c,c,d,d,d,d,e,e,e,e,e} In> Count(testList, c) Result> 3 In> Count(testList, e) Result> 5 In> Count(testList, z) Result> 0

v.95b - 08/01/10 Introduction To Programming With MathPiper 3242

111/140

16.1.5 Select()
Select(list, predicate_function)

3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259

Select() returns a list that contains all the expressions in a list which make a given predicate function return True:
In> Select({46,87,59,-27,11,86,-21,-58,-86,-52}, "IsPositiveInteger") Result> {46,87,59,11,86}

In this example, notice that the name of the predicate function is passed to Select() in double quotes. There are other ways to pass a predicate function to Select() but these are covered in a later section. Here are some further examples which use the Select() function:
In> Select({16,14,82,92,33,74,99,67,65,52}, "IsOdd") Result> {33,99,67,65} In> Select({16,14,82,92,33,74,99,67,65,52}, "IsEven") Result> {16,14,82,92,74,52} In> Select(1 .. 75, "IsPrime") Result> {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73}

Notice how the third example uses the .. operator to automatically generate a list of consecutive integers from 1 to 75 for the Select() function to analyze.

16.1.6 The Nth() Function & The [] Operator


Nth(list, index)

3260 3261 3262 3263 3264 3265 3266 3267

The Nth() function simply returns the expression which is at a given position in a list. This example shows the third expression in a list being obtained:
In> testList := {a,b,c,d,e,f,g} Result> {a,b,c,d,e,f,g} In> Nth(testList, 3) Result> c

As discussed earlier, the [] operator can also be used to obtain a single expression from a list:

v.95b - 08/01/10 Introduction To Programming With MathPiper 3268 3269 3270 3271 3272 3273 3274
In> testList[3] Result> c

112/140

The [] operator can even obtain a single expression directly from a list without needing to use a variable:
In> {a,b,c,d,e,f,g}[3] Result> c

16.1.7 The : Prepend/Append Operator


expression : list list : expression

3275 3276 3277 3278 3279 3280 3281 3282 3283

The prepend/append operator is a colon : and it can be used to add an expression to the beginning or end of a list:
In> list := {1,2,3} Result: {1,2,3} In> abc : list Result: {abc,1,2,3} In> list : xyz Result: {1,2,3,xyz}

16.1.8 Concat()
Concat(list1, list2, ...)

3284 3285 3286 3287 3288 3289

The Concat() function is short for "concatenate" which means to join together sequentially. It takes two or more lists and joins them together into a single larger list:
In> Concat({a,b,c}, {1,2,3}, {x,y,z}) Result> {a,b,c,1,2,3,x,y,z}

16.1.9 Insert(), Delete(), & Replace()


Insert(list, index, expression)

Delete(list, index)

v.95b - 08/01/10 Introduction To Programming With MathPiper

113/140

Replace(list, index, expression)

3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301

Insert() inserts an expression into a list at a given index, Delete() deletes an expression from a list at a given index, and Replace() replaces an expression in a list at a given index with another expression:
In> testList := {a,b,c,d,e,f,g} Result> {a,b,c,d,e,f,g} In> testList := Insert(testList, 4, 123) Result> {a,b,c,123,d,e,f,g} In> testList := Delete(testList, 4) Result> {a,b,c,d,e,f,g} In> testList := Replace(testList, 4, xxx) Result> {a,b,c,xxx,e,f,g}

16.1.10 Take()
Take(list, amount) Take(list, -amount) Take(list, {begin_index,end_index})

3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315

Take() obtains a sublist from the beginning of a list, the end of a list, or the middle of a list. The expressions in the list that are not taken are discarded. A positive integer passed to Take() indicates how many expressions should be taken from the beginning of a list:
In> testList := {a,b,c,d,e,f,g} Result> {a,b,c,d,e,f,g} In> Take(testList, 3) Result> {a,b,c}

A negative integer passed to Take() indicates how many expressions should be taken from the end of a list:
In> Take(testList, -3) Result> {e,f,g}

Finally, if a two member list is passed to Take() it indicates the range of expressions that should be taken from the middle of a list. The first value in the

v.95b - 08/01/10 Introduction To Programming With MathPiper 3316 3317 3318 3319 3320

114/140

passed-in list specifies the beginning index of the range and the second value specifies its end:
In> Take(testList, {3,5}) Result> {c,d,e}

16.1.11 Drop()
Drop(list, index) Drop(list, -index) Drop(list, {begin_index,end_index})

3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340

Drop() does the opposite of Take() in that it drops expressions from the beginning of a list, the end of a list, or the middle of a list and returns a list which contains the remaining expressions. A positive integer passed to Drop() indicates how many expressions should be dropped from the beginning of a list:
In> testList := {a,b,c,d,e,f,g} Result> {a,b,c,d,e,f,g} In> Drop(testList, 3) Result> {d,e,f,g}

A negative integer passed to Drop() indicates how many expressions should be dropped from the end of a list:
In> Drop(testList, -3) Result> {a,b,c,d}

Finally, if a two member list is passed to Drop() it indicates the range of expressions that should be dropped from the middle of a list. The first value in the passed-in list specifies the beginning index of the range and the second value specifies its end:
In> Drop(testList, {3,5}) Result> {a,b,f,g}

16.1.12 FillList()
FillList(expression, length)

3341

The FillList() function simply creates a list which is of size "length" and fills it

v.95b - 08/01/10 Introduction To Programming With MathPiper 3342 3343 3344 3345 3346 3347 with "length" copies of the given expression:
In> FillList(a, 5) Result> {a,a,a,a,a} In> FillList(42,8) Result> {42,42,42,42,42,42,42,42}

115/140

16.1.13 RemoveDuplicates()
RemoveDuplicates(list)

3348 3349 3350 3351 3352 3353 3354

RemoveDuplicates() removes any duplicate expressions that are contained in a list:


In> testList := {a,a,b,c,c,b,b,a,b,c,c} Result> {a,a,b,c,c,b,b,a,b,c,c} In> RemoveDuplicates(testList) Result> {a,b,c}

16.1.14 Reverse()
Reverse(list)

3355 3356 3357 3358 3359 3360

Reverse() reverses the order of the expressions in a list:


In> testList := {a,b,c,d,e,f,g,h} Result> {a,b,c,d,e,f,g,h} In> Reverse(testList) Result> {h,g,f,e,d,c,b,a}

16.1.15 Partition()
Partition(list, partition_size)

3361 3362 3363 3364 3365

The Partition() function breaks a list into sublists of size "partition_size":


In> testList := {a,b,c,d,e,f,g,h} Result> {a,b,c,d,e,f,g,h} In> Partition(testList, 2) Result> {{a,b},{c,d},{e,f},{g,h}}

v.95b - 08/01/10 Introduction To Programming With MathPiper

116/140

3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376

If the partition_size does not divide the length of the list evenly, the remaining elements are discarded:
In> Partition(testList, 3) Result> {{a,b,c},{d,e,f}}

The number of elements that Partition() will discard can be calculated by dividing the length of a list by the partition size and obtaining the remainder:
In> Length(testList) % 3 Result> 2

Remember that % is the remainder operator. It divides two integers and returns their remainder.

16.1.16 Table()
Table(expression, variable, begin_value, end_value, step_amount)

3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393

The Table() function creates a list of values by doing the following: 1) Generating a sequence of values between a "begin_value" and an "end_value" with each value being incremented by the "step_amount". 2) Placing each value in the sequence into the specified "variable", one value at a time. 3) Evaluating the defined "expression" (which contains the defined "variable") for each value, one at a time. 4) Placing the result of each "expression" evaluation into the result list. This example generates a list which contains the integers 1 through 10:
In> Table(x, x, 1, 10, 1) Result> {1,2,3,4,5,6,7,8,9,10}

Notice that the expression in this example is simply the variable 'x' itself with no other operations performed on it. The following example is similar to the previous one except that its expression multiplies 'x' by 2:
In> Table(x*2, x, 1, 10, 1) Result> {2,4,6,8,10,12,14,16,18,20}

v.95b - 08/01/10 Introduction To Programming With MathPiper

117/140

3394 3395 3396 3397 3398

Lists which contain decimal values can also be created by setting the "step_amount" to a decimal:
In> Table(x, x, 0, 1, .1) Result> {0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1}

16.1.17 HeapSort()
HeapSort(list, compare)

3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414

HeapSort() sorts the elements of list into the order indicated by compare with compare typically being the less than operator "<" or the greater than operator ">":
In> HeapSort({4,7,23,53,-2,1}, "<"); Result: {-2,1,4,7,23,53} In> HeapSort({4,7,23,53,-2,1}, ">"); Result: {53,23,7,4,1,-2} In> HeapSort({1/2,3/5,7/8,5/16,3/32}, "<") Result: {3/32,5/16,1/2,3/5,7/8} In> HeapSort({.5,3/5,.76,5/16,3/32}, "<") Result: {3/32,5/16,.5,3/5,.76}

16.2 Functions That Work With Integers


This section discusses various functions which work with integers. Some of these functions also work with non-integer values and their use with nonintegers is discussed in other sections.

16.2.1 RandomIntegerList()
RandomIntegerList(length, lowest_possible, highest_possible)

3415 3416 3417 3418 3419 3420

A vector is a list that does not contain other lists. RandomIntegerList() creates a list of size "length" that contains random integers that are no lower than "lowest_possible" and no higher than "highest possible". The following example creates 10 random integers between 1 and 99 inclusive:
In> RandomIntegerList(10, 1, 99) Result> {73,93,80,37,55,93,40,21,7,24}

v.95b - 08/01/10 Introduction To Programming With MathPiper 3421

118/140

16.2.2 Maximum() & Minimum()


Maximum(value1, value2) Maximum(list)

3422 3423 3424 3425 3426 3427 3428 3429 3430

If two values are passed to Maximum(), it determines which one is larger:


In> Maximum(10, 20) Result> 20

If a list of values are passed to Maximum(), it finds the largest value in the list:
In> testList := RandomIntegerList(10, 1, 99) Result> {73,93,80,37,55,93,40,21,7,24} In> Maximum(testList) Result> 93

The Minimum() function is the opposite of the Maximum() function.


Minimum(value1, value2) Minimum(list)

3431 3432 3433 3434 3435 3436 3437 3438 3439

If two values are passed to Minimum(), it determines which one is smaller:


In> Minimum(10, 20) Result> 10

If a list of values are passed to Minimum(), it finds the smallest value in the list:
In> testList := RandomIntegerList(10, 1, 99) Result> {73,93,80,37,55,93,40,21,7,24} In> Minimum(testList) Result> 7

16.2.3 Quotient() & Modulo()


Quotient(dividend, divisor) Modulo(dividend, divisor)

3440 3441

Quotient() determines the whole number of times a divisor goes into a dividend:
In> Quotient(7, 3)

v.95b - 08/01/10 Introduction To Programming With MathPiper 3442 3443 3444 3445 3446 3447 3448 3449 3450
Result> 2

119/140

Modulo() determines the remainder that results when a dividend is divided by a divisor:
In> Modulo(7,3) Result> 1

The remainder/modulo operator % can also be used to calculate a remainder:


In> 7 % 2 Result> 1

16.2.4 Gcd()
Gcd(value1, value2) Gcd(list)

3451 3452 3453 3454 3455 3456 3457 3458 3459 3460

GCD stands for Greatest Common Divisor and the Gcd() function determines the greatest common divisor of the values that are passed to it. If two integers are passed to Gcd(), it calculates their greatest common divisor:
In> Gcd(21, 56) Result> 7

If a list of integers are passed to Gcd(), it finds the greatest common divisor of all the integers in the list:
In> Gcd({9, 66, 123}) Result> 3

16.2.5 Lcm()
Lcm(value1, value2) Lcm(list)

3461 3462 3463 3464 3465

LCM stands for Least Common Multiple and the Lcm() function determines the least common multiple of the values that are passed to it. If two integers are passed to Lcm(), it calculates their least common multiple:
In> Lcm(14, 8) Result> 56

v.95b - 08/01/10 Introduction To Programming With MathPiper 3466 3467 3468 3469 3470

120/140

If a list of integers are passed to Lcm(), it finds the least common multiple of all the integers in the list:
In> Lcm({3,7,9,11}) Result> 693

16.2.6 Sum()
Sum(list)

3471 3472 3473 3474 3475 3476 3477 3478 3479 3480

Sum() can find the sum of a list that is passed to it: In> testList := RandomIntegerList(10,1,99)
Result> {73,93,80,37,55,93,40,21,7,24} In> Sum(testList) Result> 523 In> testList := 1 .. 10 Result> {1,2,3,4,5,6,7,8,9,10} In> Sum(testList) Result> 55

16.2.7 Product()
Product(list)

3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493

This function has two calling formats, only one of which is discussed here. Product(list) multiplies all the expressions in a list together and returns their product:
In> Product({1,2,3}) Result> 6

16.3 Exercises
For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_16_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called: book_1_section_16_exercises_john_smith.mpw. After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the

v.95b - 08/01/10 Introduction To Programming With MathPiper 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527

121/140

start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:
%mathpiper,title="Exercise 1" //Sample fold. %/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

16.3.1 Exercise 1
Create a program that uses RandomIntegerList() to create a 100 member list that contains random integers between 1 and 5 inclusive. Use one Count() call in a loop to determine how many of each digit 1-5 are in the list and then print this information. Hint: you can use the HeapSort() function to sort the generated list to make it easier to check if your program is counting correctly. Hint: You can use the following code as the starting point for your loop: ForEach(num, 1 .. 5) [ ];

16.3.2 Exercise 2
Create a program that uses RandomIntegerList() that contains random integers between 1 and 50 to determine if the number 25 is in the list. if 25 was found in the list and "25 was not in found. to create a 100 member list inclusive and use Contains() Print "25 was in the list." the list." if it wasn't

16.3.3 Exercise 3
Create a program that uses RandomIntegerList() to create a 100 member list that contains random integers between 1 and 50 inclusive and use Find() to determine if the number 10 is in the list. Print the position of 10 if it was found in the list and "10 was not in the list." if it wasn't found.

16.3.4 Exercise 4
Create a program that uses RandomIntegerList() to create a 100 member list that contains random integers between 0 and 3 inclusive. Use Select() with the IsNonZeroInteger() predicate function to obtain all of the nonzero integers in this list.

v.95b - 08/01/10 Introduction To Programming With MathPiper 3528 3529 3530

122/140

16.3.5 Exercise 5
Create a program that uses Table() to obtain a list which contains the squares of the integers between 1 and 10 inclusive.

v.95b - 08/01/10 Introduction To Programming With MathPiper

123/140

3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541

17 Nested Loops
Now that you have seen how to solve problems with single loops, it is time to discuss what can be done when a loop is placed inside of another loop. A loop that is placed inside of another loop it is called a nested loop and this nesting can be extended to numerous levels if needed. This means that loop 1 can have loop 2 placed inside of it, loop 2 can have loop 3 placed inside of it, loop 3 can have loop 4 placed inside of it, and so on. Nesting loops allows the programmer to accomplish an enormous amount of work with very little typing.

17.1 Generate All The Combinations That Can Be Entered Into A Two Digit Wheel Lock Using A Nested Loop

3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552

The following program generates all the combinations that can be entered into a two digit wheel lock. It uses a nested loop to accomplish this with the "inside" nested loop being used to generate one's place digits and the "outside" loop being used to generate ten's place digits.
%mathpiper /* */ Generate all the combinations can be entered into a two digit wheel lock.

combinationsList := {}; ForEach(digit1, 0 .. 9) //This loop is called the "outside" loop.

v.95b - 08/01/10 Introduction To Programming With MathPiper 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594
[

124/140

ForEach(digit2, 0 .. 9)//This loop is called the "inside" loop. [ combinationsList := Append(combinationsList, {digit1, digit2}); ]; ]; Echo(TableForm(combinationsList)); %/mathpiper %output,preserve="false" Result: True Side Effects: {0,0} {0,1} {0,2} {0,3} {0,4} {0,5} {0,6} . . //The middle of the list has not been shown. . {9,3} {9,4} {9,5} {9,6} {9,7} {9,8} {9,9} True %/output

The relationship between the outside loop and the inside loop is interesting because each time the outside loop cycles once, the inside loop cycles 10 times. Study this program carefully because nested loops can be used to solve a wide range of problems and therefore understanding how they work is important.

17.2 Exercises
For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_17_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called: book_1_section_17_exercises_john_smith.mpw.

v.95b - 08/01/10 Introduction To Programming With MathPiper 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607

125/140

After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:
%mathpiper,title="Exercise 1" //Sample fold. %/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

17.2.1 Exercise 1
Create a program that will generate all of the combinations that can be entered into a three digit wheel lock. (Hint: a triple nested loop can be used to accomplish this.)

v.95b - 08/01/10 Introduction To Programming With MathPiper

126/140

3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643

18 User Defined Functions


In computer programming, a function is a named section of code that can be called from other sections of code. Values can be sent to a function for processing as part of the call and a function always returns a value as its result. A function can also generate side effects when it is called and side effects have been covered in earlier sections. The values that are sent to a function when it is called are called arguments or actual parameters and a function can accept 0 or more of them. These arguments are placed within parentheses. MathPiper has many predefined functions (some of which have been discussed in previous sections) but users can create their own functions too. The following program creates a function called addNums() which takes two numbers as arguments, adds them together, and returns their sum back to the calling code as a result:
In> addNums(num1,num2) := num1 + num2 Result> True

This line of code defined a new function called addNums and specified that it will accept two values when it is called. The first value will be placed into the variable num1 and the second value will be placed into the variable num2. Variables like num1 and num2 which are used in a function to accept values from calling code are called formal parameters. Formal parameter variables are used inside a function to process the values/actual parameters/arguments that were placed into them by the calling code. The code on the right side of the assignment operator is bound to the function name "addNums" and it is executed each time addNums() is called. The following example shows the new addNums() function being called multiple times with different values being passed to it:
In> addNums(2,3) Result> 5 In> addNums(4,5) Result> 9 In> addNums(9,1) Result> 10

Notice that, unlike the functions that come with MathPiper, we chose to have this function's name start with a lower case letter. We could have had addNums() begin with an upper case letter but it is a convention in MathPiper for user

v.95b - 08/01/10 Introduction To Programming With MathPiper 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682

127/140

defined function names to begin with a lower case letter to distinguish them from the functions that come with MathPiper. The values that are returned from user defined functions can also be assigned to variables. The following example uses a %mathpiper fold to define a function called evenIntegers() and then this function is used in the MathPiper console to assign a list of even integers to the variable "a":
%mathpiper evenIntegers(endInteger) := [ resultList := {}; x := 2; While(x <= endInteger) [ resultList := Append(resultList, x); ]; x := x + 2;

/* The result of the last expression which is executed in a function is the result that the function returns to the caller. In this case, resultList is purposely being executed last so that its contents are returned to the caller. */ resultList; ]; %/mathpiper %output,preserve="false" Result: True %/output

In> a := evenIntegers(10) Result> {2,4,6,8,10} In> Length(a) Result> 5

The function evenIntegers() returns a list which contains all the even integers from 2 up through the value that was passed into it. The fold was first executed in order to define the evenIntegers() function and make it ready for use. The evenIntegers() function was then called from the MathPiper console and 10 was passed to it.

v.95b - 08/01/10 Introduction To Programming With MathPiper 3683 3684 3685

128/140

After the function was finished executing, it returned a list of even integers as a result and this result was assigned to the variable 'a'. We then passed the list that was assigned to 'a' to the Length() function in order to determine its size.

3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716

18.1 Global Variables, Local Variables, & Local()


The new evenIntegers() function seems to work well, but there is a problem. The variables 'x' and resultList were defined inside the function as global variables which means they are accessible from anywhere, including from within other functions, within other folds (as shown here):
%mathpiper Echo(x, ",", resultList); %/mathpiper %output,preserve="false" Result: True Side Effects: 12 ,{2,4,6,8,10} %/output

and from within the MathPiper console:


In> x Result> 12 In> resultList Result> {2,4,6,8,10}

Using global variables inside of functions is usually not a good idea because code in other functions and folds might already be using (or will use) the same variable names. Global variables which have the same name are the same variable. When one section of code changes the value of a given global variable, the value is changed everywhere that variable is used and this will eventually cause problems. In order to prevent errors being caused by global variables having the same name, a function named Local() can be called inside of a function to define what are called local variables. A local variable is only accessible inside the function it has been defined in, even if it has the same name as a global variable. The following example shows a second version of the evenIntegers() function which uses Local() to make 'x' and resultList local variables:

v.95b - 08/01/10 Introduction To Programming With MathPiper 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755
%mathpiper /* This version of evenIntegers() uses Local() to make x and resultList local variables */ evenIntegers(endInteger) := [ Local(x,resultList); resultList := {}; x := 2; While(x <= endInteger) [ resultList := Append(resultList, x); x := x + 2; ];

129/140

];

/* The result of the last expression which is executed in a function is the result that the function returns to the caller. In this case, resultList is purposely being executed last so that its contents are returned to the caller. */ resultList;

%/mathpiper %output,preserve="false" Result: True %/output

We can verify that 'x' and resultList are now local variables by first clearing them, calling evenIntegers(), and then seeing what 'x' and resultList contain:
In> Unbind(x, resultList) Result> True In> evenIntegers(10) Result> {2,4,6,8,10} In> x Result> x In> resultList

v.95b - 08/01/10 Introduction To Programming With MathPiper 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787
Result> resultList

130/140

18.2 Exercises
For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_18_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called: book_1_section_18_exercises_john_smith.mpw. After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:
%mathpiper,title="Exercise 1" //Sample fold. %/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

18.2.1 Exercise 1
Create a function called tenOddIntegers() which returns a list which contains 10 random odd integers between 1 and 99 inclusive. Hint: You may want to use the RandomIntegerList(), Select(), IsOdd(), and Take() functions.

18.2.2 Exercise 2
Create a function called convertStringToList(string) which takes a string as a parameter and returns a list which contains all of the characters in the string. Here is an example of how the function should work: In> convertStringToList("Hello friend!") Result> {"H","e","l","l","o"," ","f","r","i","e","n","d","!"} In> convertStringToList("Computer Algebra System") Result> {"C","o","m","p","u","t","e","r"," ","A","l","g","e","b","r","a"," ","S","y","s","t","e","m"}

Hint: Remember, a string can be broken down into individual characters by using an index value inside of brackets [] like this:

v.95b - 08/01/10 Introduction To Programming With MathPiper 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801
In> string := "Hello" Result: "Hello" In> string[1] Result: "H" In> string[2] Result: "e" In> string[3] Result: "l" In> string[4] Result: "l" In> string[5] Result: "o"

131/140

Your function should use this indexing technique inside of a loop to append each of these characters to a list.

v.95b - 08/01/10 Introduction To Programming With MathPiper

132/140

3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834

19 Miscellaneous topics
19.1 Incrementing And Decrementing Variables With The ++ And -Operators
Up until this point we have been adding 1 to a variable with code in the form of x := x + 1 and subtracting 1 from a variable with code in the form of x := x - 1. Another name for adding 1 to a variable is incrementing it and decrementing a variable means to subtract 1 from it. Now that you have had some experience with these longer forms, it is time to show you shorter versions of them.

19.1.1 Incrementing Variables With The ++ Operator


The number 1 can be added to a variable by simply placing the ++ operator after it like this:
In> x := 1 Result: 1 In> x++; Result: True In> x Result: 2

Here is a program that uses the ++ operator to increment a loop index variable:
%mathpiper index := 1; While(index <= 10) [ Echo(index); index++; //The ++ operator increments the index variable. ]; %/mathpiper %output,preserve="false" Result: True Side Effects: 1 2

v.95b - 08/01/10 Introduction To Programming With MathPiper 3835 3836 3837 3838 3839 3840 3841 3842 3843
3 4 5 6 7 8 9 10 %/output

133/140

3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872

19.1.2 Decrementing Variables With The -- Operator


The number 1 can be subtracted from a variable by simply placing the -operator after it like this:
In> x := 1 Result: 1 In> x--; Result: True In> x Result: 0

Here is a program that uses the -- operator to decrement a loop index variable:
%mathpiper index := 10; While(index >= 1) [ Echo(index); ]; index--; //The -- operator decrements the index variable.

%/mathpiper %output,preserve="false" Result: True Side Effects: 10 9 8 7 6 5

v.95b - 08/01/10 Introduction To Programming With MathPiper 3873 3874 3875 3876 3877
4 3 2 1 %/output

134/140

3878 3879

19.1.3 The Break() Function


The Break() function is used to end a loop early and here is its calling format:
Break()

3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908

The following program has a While loop which is configured to loop 10 times. However, when the loop counter variable index reaches 5, the Break() function is called and this causes the loop to end early:
%mathpiper index := 1; While(index <= 10) [ Echo(index); If(index = 5, Break()); ]; index++;

%/mathpiper %output,preserve="false" Result: True Side Effects: 1 2 3 4 5 %/output

When a Break() function is used to end a loop, it is called "breaking out" of the loop. Notice that only the numbers 1-5 are printed in this program.

v.95b - 08/01/10 Introduction To Programming With MathPiper 3909 3910 3911 3912

135/140

19.1.4 The Continue() Function


The Continue() function is similar to the Break() function, except that instead of ending the loop, it simply causes it to skip the remainder of the loop for the current loop iteration. Here is the Continue() function's calling format:
Continue()

3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944

The following program uses a While loop which is configured to print the integers from 0 to 8. However, the Continue() function is used to skip the execution of the Echo() function when the loop indexing variable index is equal to 5:
%mathpiper index := 0; While(index < 8) [ index++; If(index = 5, Continue()); Echo(index); ]; %/mathpiper %output,preserve="false" Result: True Side Effects: 1 2 3 4 6 7 8 %/output

Notice that the number 5 is not printed when this program is executed.

19.1.5 The Repeat() Function


The Repeat() function is a looping function which is similar to While() and

v.95b - 08/01/10 Introduction To Programming With MathPiper 3945 3946

136/140

ForEach(), but it is simpler than these two. Here are the two calling formats for Repeat():
Repeat(count) body Repeat() body

3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981

The first version of Repeat() simply takes an integer argument which indicates how many times it should loop. The following program shows how to use Repeat() to print 4 copies of the word "Hello":
%mathpiper Repeat(4) [ Echo("Hello"); ]; %/mathpiper %output,preserve="false" Result: 4 Side Effects: Hello Hello Hello Hello %/output

The second version of Repeat() does not take any arguments and it is designed to run as an infinite loop. The Break() function is then used to make the Repeat() function stop looping. The following program would print the loop indexing variable index forever, but the Break() function is used to stop the loop after 3 iterations:
%mathpiper index := 1; loopCount := Repeat() [ Echo(index); If(index = 3, Break());

v.95b - 08/01/10 Introduction To Programming With MathPiper 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005
index := index + 1; ]; Echo("Loop count: ", loopCount); %/mathpiper %output,preserve="false" Result: True Side Effects: 1 2 3 Loop count: 2 %/output

137/140

Notice that Repeat() returns the number of times it actually looped as a result and that this information is assigned to the variable loopCount.

19.1.6 The EchoTime() Function


Computers are extremely fast, but they still take time to execute programs. Sometimes it is important to determine how long it takes to evaluate a given expression in order to do things like determine if a section of code need to run quicker than it currently is or determine if one piece of code is slower than another. The EchoTime() function is a bodied function which is used to time how long a section of code takes to run and here is its calling format:
EchoTime()expression

4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016

The following examples use EchoTime() to determine how long it takes to add the numbers 2 and 3 together and how long it takes to factor 1234567:
In> EchoTime() 2 + 3 Result: 5 Side Effects: 0.000080946 seconds taken. In> EchoTime() Factor(1234567) Result: 127*9721 Side Effects: 0.395028773 seconds taken.

In the following program, a ForEach loop is used to have the Factor() function

v.95b - 08/01/10 Introduction To Programming With MathPiper 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059

138/140

factor all the numbers in a list. The EchoTime() function is used to determine how long it takes to do all the factoring:
%mathpiper EchoTime() ForEach(number, {100,54,65,67,344,98,454}) [ Echo(number, " - ", Factor(number)); ]; %/mathpiper %output,preserve="false" Result: True Side Effects: 100 - 2^2*5^2 54 - 2*3^3 65 - 5*13 67 - 67 344 - 2^3*43 98 - 2*7^2 454 - 2*227 0.262678978 seconds taken. %/output

Finally, the following program show how to time a code block which prints the numbers from 1 to 100:
%mathpiper EchoTime() [ index := 1; While(index <= 100) [ Write(index,,); If(index % 10 = 0, NewLine()); ]; ]; %/mathpiper index++;

NewLine();

v.95b - 08/01/10 Introduction To Programming With MathPiper 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076
%output,preserve="false" Result: True Side Effects: 1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17,18,19,20, 21,22,23,24,25,26,27,28,29,30, 31,32,33,34,35,36,37,38,39,40, 41,42,43,44,45,46,47,48,49,50, 51,52,53,54,55,56,57,58,59,60, 61,62,63,64,65,66,67,68,69,70, 71,72,73,74,75,76,77,78,79,80, 81,82,83,84,85,86,87,88,89,90, 91,92,93,94,95,96,97,98,99,100, . 0.055418423 seconds taken. %/output

139/140

4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096

19.2 Exercises
For the following exercises, create a new MathPiperIDE worksheet file called book_1_section_19_exercises_<your first name>_<your last name>.mpw. (Note: there are no spaces in this file name). For example, John Smith's worksheet would be called: book_1_section_19_exercises_john_smith.mpw. After this worksheet has been created, place your answer for each exercise that requires a fold into its own fold in this worksheet. Place a title attribute in the start tag of each fold which indicates the exercise the fold contains the solution to. The folds you create should look similar to this one:
%mathpiper,title="Exercise 1" //Sample fold. %/mathpiper

If an exercise uses the MathPiper console instead of a fold, copy the work you did in the console into the worksheet so it can be saved but do not put it in a fold.

19.2.1 Exercise 1
Create a program which uses a While loop to display the numbers from 1 to 50. Use the ++ operator to increment the loop index variable.

19.2.2 Exercise 2
Create a program which uses a While loop to display the numbers from 1 to

v.95b - 08/01/10 Introduction To Programming With MathPiper 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120
50 in reverse order. variable.

140/140

Use the -- operator to decrement the loop index

19.2.3 Exercise 3
Create a program which uses a Continue() function to cause a While loop which is configured to print the numbers from 1 to 100 to skip printing the number 72.

19.2.4 Exercise 4
Create a program which uses the version of the Repeat() function which takes an integer as an argument and the : string concatenation operator to print the following: Hello HelloHello HelloHelloHello HelloHelloHelloHello HelloHelloHelloHelloHello Hint: In> string := "Hi" Result: "Hi" In> string := string : "Hi" Result: "HiHi"

19.2.5 Exercise 5
In the last example in the EchoTime() section, what operator is being used to format the output into lines of 10 numbers and how is this operator doing this?

S-ar putea să vă placă și