Page 61 - Introduction to Programming with Java: A Problem Solving Approach
P. 61

                 print “Hello, world!”
Figure 2.1 Hello World algorithm that prints the message “Hello, world!”
Rectangle Algorithm
For the next example, suppose you want to display the area of a particular rectangle. First consider what you wanttheprogramtodo.InFigure2.2,lookatthearea = 40lineunderOutput.Thatshowswhatyou want the output to look like.
Figure 2.2 Rectangle algorithm that prints the area of a rectangle Apago PDF Enhancer
The top part of Figure 2.2 is the algorithm for calculating a rectangle’s area. Note that some of the words, like length and width, appear with monospace font. Monospace font is when each character’s width is uniform. We use monospace font to indicate that something is a variable. A variable is a container that holds a value. The algorithm’s first two lines assign 10 and 4 to length and width, respectively. That means that the length variable contains the value 10 and the width variable contains the value 4. The third line describes two operations: First compute the area by multiplying length times width. (The * is the multiplication “times” symbol.) Then assign the result (the product) to the variable, rectangleArea. The fourth line prints two items – the string literal “area =” and the value of the rectangleArea vari- able. When a variable appears in a print statement, the print statement prints the value stored inside the vari- able. rectangleArea contains 40, so the print statement prints the value 40. Figure 2.2’s output shows the desired display.
2.3 Variables
Now let’s consider variables in more detail. Figure 2.2’s Rectangle algorithm has three variables— length, width, and rectangleArea. In rectangleArea, notice how we run together the two words, “rectangle” and “area,” and notice how we start the second word with a capital letter. We do this to help you develop good habits for later Java coding, which does not permit any spaces in a variable name. Although it’s not necessary for pseudocode, in Java, it’s good style to begin a variable name with a lowercase letter, as in rectangleArea. If the name is a combination of several words, in Java you must remove the space(s) between multiple words in a single name, and you should begin all words after the first
2.3 Variables 27
  set length to 10
set width to 4
set rectangleArea to length * width print “area = ” rectangleArea
⎫ ⎢
⎬   algorithm ⎢
⎭
     Output:
area = 40
print statement This is what the output looks like.
        
















































































   59   60   61   62   63