19.04.2017 Views

Learn to Program with Small Basic

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

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

Simplifying Expressions<br />

Variables can make calculating arithmetic expressions easier. Let’s say you<br />

want <strong>to</strong> write a program that evaluates this expression:<br />

1 5<br />

+ 5 7<br />

7 8<br />

− 2 3<br />

You can write a bunch of different programs that would all give you the<br />

right answer. For example, you could write a statement that evaluates the<br />

whole expression at once:<br />

TextWindow.WriteLine((1 / 5 + 5 / 7) / (7 / 8 - 2 / 3))<br />

Or you might evaluate the numera<strong>to</strong>r and the denomina<strong>to</strong>r separately<br />

and then display the result of their division:<br />

num = (1 / 5) + (5 / 7) ' Finds the numera<strong>to</strong>r<br />

den = (7 / 8) - (2 / 3) ' Finds the denomina<strong>to</strong>r<br />

TextWindow.WriteLine(num / den) ' Does the division<br />

You could also evaluate each fraction separately and then display the<br />

result of the combined expression:<br />

a = 1 / 5<br />

b = 5 / 7<br />

c = 7 / 8<br />

d = 2 / 3<br />

answer = (a + b) / (c - d)<br />

TextWindow.WriteLine(answer)<br />

Although these three programs give you the same answer, each program<br />

uses a different style. The first program is the “chubby bunny” of programming:<br />

it crams everything in<strong>to</strong> one statement. If the original expression was<br />

more complex, the statement would be really hard <strong>to</strong> follow. The third program<br />

does the opposite: it represents every fraction in the expression <strong>with</strong> a<br />

variable, and that can also be hard <strong>to</strong> read.<br />

If you’re Goldilocks, the second solution is your “just right.” It breaks<br />

down the expression in<strong>to</strong> just enough parts <strong>to</strong> make the program easier <strong>to</strong><br />

understand. The variables num and den clearly represent the numera<strong>to</strong>r and<br />

the denomina<strong>to</strong>r.<br />

As these examples show, there’s often more than one way <strong>to</strong> solve a problem.<br />

If you ever get stuck on a problem, try breaking it in<strong>to</strong> more manageable<br />

pieces!<br />

50 Chapter 4

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

Saved successfully!

Ooh no, something went wrong!