13 May 2012

Example Program of QBasic


Example Program

A QBasic program consists of lines of text, one after another, like a poem. Each line of a program (or a poem) stays by itself on one line. A line which has an instruction for the computer is called a statement. Not all lines are statements. Some lines are blank. Others are comments intended for a human reader, but not for the computer. Only a line that contains an instruction for the computer is a statement.
Usually the computer runs a program starting with the first statement and proceeding statement by statement until the end of the program is reached.
Here is a complete QBasic program as you see it when you are working with the QBasic system:
Look in Appendix B to see how to enter and run programs. You don't have to do that now to read this chapter. The picture shows many details that are not important right now. The QBasic program is just these two lines:
PRINT 10 + 5
END
The PRINT statement causes something to be printed on the screen of the computer monitor. The last statement in the program is END, which just tells the computer that the program is finished.


Two Statement Programs

Look at the program:
PRINT 10 + 5
END
If you run this program, the computer starts with the first statement:
PRINT 10 + 5
That statement says to:
  • Add the number 10 to the number 5
  • Print the result on the computer monitor (the computer screen).
This is like an electronic calculator where you enter 10, +, 5, and =.     The calculator then shows 15.
In QBasic there are many things that can be done with the sum. To see the sum on the monitor, use PRINT.

The END Statement

The statement PRINT 10 + 5 adds 10 to 5 and then prints the result 15 on the monitor. Here is what you see on your computer's screen when you run this program:
Don't get lost in the details. The part that the program printed is the number "15". All the other stuff is unimportant and depends on what computer you are using.
Here is the program again:
PRINT 10 + 5
END
The last statement, END signals the end of the program. It is obvious where this program ends, but it is harder to tell with longer programs, so the END statement is necessary for them.

QUESTION 5:

Do you suppose that the following program is correct?
END
PRINT 10 + 5
 

Comments

If you run the program again, the computer will start at the first statement again (and end immediately, as before). Here is another program:
' Program to add two numbers
PRINT 10 + 5
END
The first line of this program is called a comment. A comment starts with an apostrophe ( ' ). This is the character just left of the Enter key on the computer's keyboard. Comment lines tell humans what the program does, or what parts of the program do. When the program is run, the computer does not look at the comments at all. The comment lines have no effect on what the program does.

QUESTION 6:

What does the above program do?
 

Strings

Computers do more than arithmetic. You have probably used a computer for word processing or for viewing documents on the Web (such as this one). QBasic may be used with words, too. Here is a program that writes Hello World onto the monitor screen:
' Program to write words to the monitor
PRINT "Hello World"
END
In this program the PRINT statement has exactly what you want printed inside quotes (" "). When the program runs, the characters inside the quotes are printed. The quotes are not printed. The "Hello World" is called a string because what you want to print is a string of characters inside the quotes.
 

Sequential Execution

Characters inside of quotes are printed literally--upper and lower case are printed exactly as in the string, and punctuation (such as the period at the end of the sentence) is printed.
When the computer system performs a command given by a QBasic statement, we say that the statement is executed. Look at the program in the question (below). There are two PRINT statements. The first PRINT statement is executed first (of course), then the second PRINT statement is executed. Finally the END statement ends the program. Unless directed otherwise, a QBasic program starts with the first statement and then executes the statements in sequential order until an END is reached.

QUESTION 10:

What do you suppose this program writes to the computer monitor?
' Program to demonstrate sequential execution
PRINT "Cross patch, draw the latch,"
PRINT "Sit by the fire and spin."
END
 
 

Strings and Arithmetic in Print Statements

A PRINT statement can print more than one item. Examine the following program.
' Printing two items
PRINT "The sum of 1 plus 10 is", 1 + 10
END
The PRINT statement has two items to print:
  • A string: "The sum of 1 plus 10 is"
  • The result of an adding two numbers: 1+10
The two items are separated by a comma). When the program runs it prints the following to the monitor:
The sum of 1 plus 10 is   11
The string is printed unchanged, character for character. The next item is separated from the first with some spaces, then the result of the arithmetic is printed. It is useful to list two (or more) items in one PRINT statement.

QUESTION 11:

Here is a program that calculates 12 times 12. The program prints a sting and then prints the answer. But is the program correct?
' Compute 12 times 12
PRINT "The square of 12" is 12*12
END
 
 

Answer:

No. The PRINT statement is wrong. The words inside the quotes must include the is. The first item to print must be followed by a comma. It is very easy to overlook such small mistakes.
Here is the correct version of the program:
' Computing 12 times 12
PRINT "The square of 12 is", 12*12
END

Syntax Errors

If you tried to run the incorrect version of the program it would not work. You would see something on your screen like this:
(These notes have not explained how to run programs yet. Just pretend you tried to run the program). The gray box contains an error message that does not make much sense. To get rid of the box, hit the TAB key on your keyboard until the OK in the error message is selected, and then hit ENTER. (Unless you fix the mistake the error message will appear the next time you run the program.)
QBasic did not execute the PRINT statement because it has a Syntax Error. Syntax in programming languages means nearly the same as grammar means in human languages. It means "the rules for creating a correctly formed statement."
A statement without syntax errors is formed correctly. It might not make any sense. This is true with English also. The following is not an English sentence:
be you force may the with
It does not follow English syntax rules and is just a jumble of words. The following sentence has no syntax errors. But it does not make sense:
The distant corners softly remember grape soda.

QUESTION 12:

Is there a syntax error in the following program?
' Computing 12 times 12
PRINT The square of 12 is, 12*12
END
 
 

Bugs

The program should be:
' Computing 12 times 12
PRINT "The square of 12 is", 12*12
END
If you try to run the incorrect version you get a message window on your computer screen that lists the problem. (Often the message is hard to understand. Some syntax errors confuse the QBasic system so badly it does not know what to do.) Hopefully you can figure out the syntax error, correct it, and run the program.
Programs can have errors other than syntax errors. Just as you can say something in grammatical English that is incorrect, you can write a program in QBasic that has no syntax errors but computes an incorrect result. Such a program has one or more bugs.

QUESTION 13:

Does the following program make sense?
' Computing 12 times 12
PRINT "The square of 12 is", 12 * 0
END
 
 

Answer:

No. The PRINT statement
PRINT "The square of 12 is", 12 * 0
is correct in syntax, but it does not calculate what it should. 12 * 0 means to multiply 12 by 0, which results in a zero, which is not what is wanted. This program has a bug.

More Bugs

The buggy program:
' Computing 12 times 12
PRINT "The square of 12 is", 12 * 0
END
. . . has a comment line that says what is wanted, and even has a string in the PRINT statement that said what the result should be. But the arithmetic is wrong, and a wrong number is printed.

QUESTION 14:

Does the following program have a syntax error or a bug?
' Computing 23.8 plus 5.2
PRINT "The sum is", 23.8 * 5.2
END
 
 

A Story Problem

Here is the corrected program:
' Computing 23.8 and 5.2
PRINT "The sum is", 23.8 + 5.2
END
Often the numbers in a computer program are the values of things in real life. For example, say that one number is "the number of hours you have worked". The other number is "the number of dollars you are paid per hour". These are very interesting numbers. The two numbers multiplied together give the number of dollars you are paid (before deductions).

QUESTION 15:

Write a QBasic program that calculates how much you are paid if you work 16 hours and your rate of pay is 7.25 dollars per hour.
 
 

Answer:

' Calculate gross pay
PRINT "The pay is", 16 * 7.25
END
If you run this program it writes:
The pay is    116

Arithmetic Operators

So far we have seen the QBasic commands for adding two numbers (+) and for multiplying two numbers (*). The + and * are called arithmetic operators. Here is a list of more of them:
Arithmetic Operators
operator
meaning
example
in words
^
power
3^2
3 to the power 2
-
negation
-23
negative 23
*
multiply
1.5 * 8
1.5 times 8
/
divide
12 / 4
12 divided by 4
+
addition
4.2 + 3
4.2 plus 3
-
subtraction
9 - 2
9 minus 2
Here is a program that calculates the number of miles per gallon for a car that has burned 10 gallons of gas and gone 245.4 miles:
' Calculate miles per gallon
' 245.4 miles with 10 gallons of gas
'
PRINT "MPG is", 245.4 / 10
END
It is important to get the two numbers in the correct order. The program is correct because it divides the number of miles, 245.4, by the number of gallons, 10. The program prints its output to the monitor:
MPG is   24.54
This program has three comment lines. This is fine; comments are ignored by the computer. You can have many of them. The third comment line has nothing on it except for the apostrophe ( ' ) that makes it a comment. This is fine. You can use a blank line if you want.

QUESTION 16:

Write (on paper, in your head, or on a computer) a program to answer the following problem:
A bird watcher bought 25 pounds of bird food for an outdoor bird feeder. The birds ate all the food in 15 days. How many pounds of bird food per day did the birds eat?
 
 

Answer:

' Calculate the number of pounds of food
' birds eat in a day if they eat 25 pounds of food
' in 15 days
'
PRINT "Daily seed use is ", 25 / 15, " pounds per day"
END
Your program probably has different strings in the PRINT statement. The division is correct: 25 pounds divided by the number of days gives pounds per day. The other arrangement 15/25 is incorrect.

Three items in the PRINT statement

The PRINT statement has three items to print. This is OK, and makes the program's output more understandable. Each item is separated by a comma. The three items to print are:
  1. A string -- "Daily seed use is "
  2. An arithmetic result -- 25 / 15
  3. A string -- " pounds per day"
When printed, each item is separated from the previous item by a tab. This is like pushing the tab key on a typewriter or wordprocessor. The comma "," separating items is replaced with several spaces (not always the same number of spaces).
The above program writes the following to the computer monitor screen:
Daily seed use is    1.66666667  pounds per day

QUESTION 17:

The electricity used in a household was 1679 kilowatt hours during 41 winter days. The same household used 752 kilowatt hours during 31 summer days. Write a program which uses two PRINT statements to write out the average kilowatt hours used per day in the winter and the average kilowatt hours used per day in the summer.
 
 

Answer:

' Calculate the average KWH per day for winter and summer.
' 1679 KWH used in 41 winter days.
'  752 KWH used in 31 summer days.
'
PRINT "Average WINTER use is ", 1679/41, " KWH per day"
PRINT "Average SUMMER use is ", 752/31,  " KWH per day"
END
This program uses sequential execution. The first PRINT statement executes, then the second PRINT statement executes. Then the END statement stops the program. The program prints this to the monitor:
Average WINTER use is       40.95122     KWH/day
Average SUMMER use is       24.25806     KWH/day

Negative Numbers

Look at the table of arithmetic operators. The symbol - (minus) appears twice in the table. This is because it has two meanings:
  • The first meaning is "negative number".
  • The second meaning is "subtraction".
Arithmetic Operators
operator
meaning
example
in words
^
power
3^2
3 to the power 2
-
negation
-23
negative 23
*
multiply
1.5 * 8
1.5 times 8
/
divide
12 / 4
12 divided by 4
+
addition
4.2 + 3
4.2 plus 3
-
subtraction
9 - 2
9 minus 2
These two meanings are the same as in ordinary arithmetic. You may be so familiar with these two meanings that you may have trouble seeing them. For example, look at the following, which might be found in a math book (or in any textbook):
-25             negative 25
-5.2            negative 5.2
 
18.1 - 2.4      18.1 minus 2.4
12 - 6          12 minus 6
The "-" sign is used for two purposes in the above. QBasic uses it for the same two purposes.

QUESTION 18:

What does the "-" do in the following program?
PRINT "Usual gain in buying a lottery ticket ",  -1
END
 
 

Answer:

The "-" sign makes a negative number.

Automatic Formatting of Arithmetic

Often, both uses of "-" appear in one calculation. Examine the following:
-25 + 10        negative 25 plus 10      =  -15
-5.2 - 3.1      negative 5.2 minus 3.1   =  -8.3
18.4 - 2.4      18.4 minus 2.4           =  16.0
-12/6           minus 12 divided by 6    =  -2
The QBasic system makes this less confusing by adjusting what you type. QBasic adjusts what you type so that:
  • When "-" means "negative number" it is placed right up against the number it is for.
  • When "-" means "subtraction" it is separated from the numbers to be subtracted by one space on each side.
For example, if you type:
PRINT -  25
END
QBasic adjusts this to:
PRINT -25
END
(The adjustment is not done until after the cursor has left the line.)

QUESTION 19:

You type the following:
PRINT -  25-4
How will QBasic adjust this line?
 
 

Answer:

PRINT -25 - 4
The first minus sign means "negative number" and is moved right up against the 25. The second minus sign means "subtract" and is separated by spaces on either side.

More about Negative Numbers

The above statement subtracts 4 from a negative 25. This results in -29.

QUESTION 20:

What will the following program print on the monitor?
PRINT -16 + 4
END
 
 

Answer:

The statement PRINT -16 + 4 causes -12 to be printed on the monitor. The arithmetic -16 + 4 means "add four to negative sixteen." The - sign indicates a negative number.

Exponents

The exponentiation operator is ^ (on the same key as 6). It means "to the power of".
3^2    means three to the power two,   =   3 * 3 = 9
 
4^3    means four  to the power three, =   4 * 4 * 4 = 64
 
2.5^2  means 2.5   to the power two,   =   2.5 * 2.5 = 6.25
 
10^1.2 means ten   to the power 1.2,   =   15.8489
You may not have seen fractional powers before as in the last example. Don't worry. We won't use them. But if your need it in the future, QBasic can do it.

QUESTION 21:

What (do you suppose) that the following program writes?
' Number of square inches in a square foot
PRINT "Square inches = ", 12 ^ 2
END
 
 

Answer:

Square inches =      144

Several Operators in a Row

Sometimes you want more than one arithmetic operator in the same statement. For example, here is a program to calculate the number of fluid ounces in a gallon:
' Number of fluid oz. in a gal.
'
' There are 16 oz. per pint
' There are 2 pints per quart
' There are 4 quarts per gal.
'
PRINT "Fluid ounces = ", 16 * 2 * 4
END
When you see two or more of the same operator, start at the left and do them one at a time:
16 * 2 * 4
   
32 * 4
   
128
------




   do first




Often it makes no difference in what order you do the arithmetic when all operators are the same. In more complicated floating point arithmetic it sometimes makes a difference.

QUESTION 22:

Write a program that calculates the number of Winter days in a year.
  • There are 11 Winter days in December
  • There are 31 Winter days in January
  • There are 28 Winter days in February (usually)
  • There are 19 Winter days in March
 
 

Answer:

' Number of Winter Days
'
PRINT "Winter Days = ", 11 + 31 + 28 + 19
END
When all the operators are the same, start at the left and do the arithmetic one operator at a time. Doing this for the above:
 11 + 31 + 28 + 19    42 + 28 + 19  70 + 19   89
--------                 --------          -------
do first                 do second         do third

End of the Chapter

You have reached the end of this chapter. Only 23 more to go. You may wish to review the following:
For more exciting Story Problems, and lots more Math, be sure to look for Chapter 2, coming soon to a screen near you.
 

CHAPTER 2 — Arithmetic Expressions

This chapter is about arithmetic with QBasic. The rules for QBasic arithmetic are similar to paper-and-pencil arithmetic.

Chapter Goals

  • Arithmetic expressions.
  • Operator priority.
  • Parentheses.
  • Practice of all the above.
  • More Story Problems

QUESTION 1:

Does the following look correct?
(8 + 12) / 2


Answer:

Yes,       (8 + 12) / 2       looks right. You don't need to memorize rules to decide this.

Arithmetic Expressions

An arithmetic expression is a syntactically correct combination of numbers, operators, parenthesis, and variables.
You have not (officially) seen variables yet, so ignore that part of the definition. Here are several arithmetic expressions, similar to those you saw in the previous chapter:
 25 + 15                     32.128 - 19.6 + 3.2
 
-14 / 3                      1.243 ^ 5
 
-23.77 * -2                  10 - 5 - 8
Remember that syntax means the rules for putting together a correctly formed statement. Arithmetic expressions are parts of statements, so must follow syntax rules in order to be correct. You are already familiar with these rules: they are the same rules as for pencil-and-paper arithmetic.

QUESTION 2:

Is the following an arithmetic expression?
89.3 + / 2


Answer:

No,   89.3 + / 2 is not syntactically correct, so cannot be an arithmetic expression.
Notice that 89.3 + / 2 is made of correct components—numbers and operators—but that they are put together incorrectly.

Which Operator is done First?

When two or more arithmetic operators are used in the same arithmetic expression it is sometimes not clear what to do. For example:
      
1 + 2   *   3    =   ?
This could mean either of two things, depending on what operation is done first:
      
 
1 + 2   *   3    =   3 * 3  =  9   
-----
OR
      
1   +   2 * 3    =   1 + 6  =  7
        -----
 
It is not clear if + or if * should be done first. Which one is done first makes a difference in the result.

QUESTION 3:

What is the usual (paper-and-pencil) meaning of
1 + 2 * 3


Answer:

Usually 1 + 2 * 3 means to do the multiplication first.

Operator Priority

To clear up these problems, arithmetic operators have each been given a priority. When there is a choice, do the highest priority operation first. The priorities of operators is given in the table. The highest priority is "1" and the lowest is "4".
Priority of Arithmetic Operators
operator
meaning
priority
^
power
1
-
negation
2
*
multiply
3
/
divide
3
+
addition
4
-
subtraction
4
For example:
      
1 + 2 * 3 
    -------
    * has higher priority than +, so do first
 
   =  1  +  6
 
   =  7

QUESTION 4:

Do this:
2 * 3 + 1


Answer:

 2 * 3 + 1   =  6 + 1  =  7
 --+--
   |
higher priority 
than +, 
do first

More on Operator Priority

When there are two or more operators of different priority, do the highest priority operator first. If there are several operators of the same priority do the operators from left to right. (Except for exponentiation, ^, which is done right to left.) Examine the following:
4 + 3 * 4 + 2  
 
4 + 3 * 4 + 2     --- pick the highest priority operator
    -----
 
4 + 12 + 2        --- all operators are of same priority
------                so do them left to right
 
16 + 2 
 
18
Since * has the highest priority it is done first.
After doing * there are two + operators left. These are done left to right (although in this case it does not make a difference.)

QUESTION 5:

What is the result of the following?
10 + 3 * 3 + 5


Answer:

The highest priority operator in
 
10 + 3 * 3 + 5 
is *, so it is done first. This gives
 
10 + 9 + 5.
Now the remaining + are of equal priority and are done left to right.
 
10 + 9 + 5 = 19 + 5 = 24

Equal Priority for * and /

Priority of Arithmetic Operators
operator
meaning
priority
^
power
1
-
negation
2
*
multiply
3
/
divide
3
+
addition
4
-
subtraction
4
Examine the priority chart again: Notice that * and / have the same priority. When there are several * and /, do them left to right. For example:
12 / 3 * 2   --- all operators have same priority 
------           do them left to right
 
4 * 2 
 
8
The / and * have equal priority. The operators are done left to right.

QUESTION 6:

What is the result of the following?
10 * 2 / 4


Answer:

There are two operators of equal priority in
10 * 2 / 4
so they are done in order left to right:
10 * 2 / 4  =  20 / 4 = 5
------
.

+ and - have Equal Priority

Notice that + and - also have equal priority. If they are the only operators in an expression, do the work from left to right.

QUESTION 7:

What is the result of the following?
12 - 2 + 4


nswer:

There are two operators of equal priority in
12 - 2 + 4
so they are done in order left to right:
12 - 2 + 4 = 10 + 4 = 14
------
.

Mixtures of * / and + -

When the operators in an arithmetic expression have a mixture of priorities, remember to do the highest priority first. If there are many operators in an expression, first find the highest priority operators. The leftmost of them will be done first. (However power, ^, is an exception to this rule. But for clarity you should never use two ^ in a row, although this is legal.)

QUESTION 8:

In the following, what operator is done first?
2 * 4 + 3 - 8 / 4


Answer:

2 * 4 + 3 - 8 / 2  =  2 * 4 + 3 - 8 / 2 
                      -----
* and / have the same priority, so do the leftmost of them first. The + and the - share a lower priority so they will not be done until later.

Same Example

After the first operation (  *  ) is done, the result is:
2 * 4 + 3 - 8 / 2  =  8 + 3 - 8 / 2
-----

QUESTION 9:

What operator is done next?
8 + 3 - 8 / 2


Answer:

2 * 4 + 3 - 8 / 2  =  2 * 4 + 3 - 8 / 2 
                      -----
* and / have the same priority, so do the leftmost of them first. The + and the - share a lower priority so they will not be done until later.

Same Example

After the first operation (  *  ) is done, the result is:
2 * 4 + 3 - 8 / 2  =  8 + 3 - 8 / 2
-----

QUESTION 9:

What operator is done next?
8 + 3 - 8 / 2


Answer:

8 + 3 - 8 / 2  =  8 + 3 - 4
        -----
The single / has higher priority than the + and the -, so it is done first. Now there are two operators of equal priority, so they are done left to right:
8 + 3 - 4  =  11 + 4  =  15
-----

Negative Numbers (again)

Priority of Arithmetic Operators
operator
meaning
priority
^
power
1
-
negation
2
*
multiply
3
/
divide
3
+
addition
4
-
subtraction
4
 
Examine the operator priority chart again. Notice that "-" is in the chart in two places. As you saw in chapter one, this is because "-" is used in two different ways:
  • The first meaning is "negative number". This use has high priority.
  • The second meaning is "subtraction". This use has low priority.
Since "negation" has high priority, it will be done first:
10 + -8 / 2 = 10 + (-8)/2 = 10 + -4 = 6

QUESTION 10:

What is the result of the following?
-12 + 2 + 4


Answer:

In the expression -12 + 2 + 4 the "-" means "negative" and is firmly attached to the 12:
-12 + 2 + 4 = (-12) + 2 + 4 = (-10) + 4 = -6
---           ---------       ---------
Once the negative is attached to the 12, the rest is done by going left to right since the two + are of equal priority.

Exponents

Priority of Arithmetic Operators
operator
meaning
priority
^
power
1
-
negation
2
*
multiply
3
/
divide
3
+
addition
4
-
subtraction
4
 
In the priority chart, exponent is the highest priority of all. This means that it will be done before anything else. Remember that "^" means "raised to the power of".

QUESTION 11:

What operator will be done first in the following?
10 * 3 ^ 2 - 5


Answer:

The ^ operator is higher priority than any of the others, so it is done first. (If you are having trouble remembering priorities, notice that the operators from lowest to highest priority are the same order you learned them in grade school.)
10 * 3 ^ 2 - 5  =  10 * 9 - 5
     -----
Now the rest follows the usual order: 10 * 9 - 5 = 90 - 5 = 85.

Arithmetic in Basic Programs

We are still talking about QBasic programs. Arithmetic expressions are just a part of them. Now that you know about operator priority you should be able to do more complicated arithmetic in PRINT statements (and elsewhere, when we get to it...)

QUESTION 12:

What will the following program print to the monitor?
' Mixed Operators
'
PRINT  3 + 12 / 2
end

Answer:

The program will print 9 to the monitor, because:
3 + 12 / 2 = 3 + 6  = 9

A Story Problem

Remembering operator priority makes it easier to get the arithmetic right in story problems. Recall the fluid ounces measure of volume:
  • 16 fl. oz. per pint
  • 32 fl. oz. per quart
  • 12 fl. oz. per most beverage cans

QUESTION 13:

While studying for a final exam, you stayed up all night. The next day you find the following empty containers in your room:
  • Three 12 oz. cans of Jolt
  • Two pint bottles of Mountain Dew
  • One quart bottle of Pepsi
Write a program to print out how many fluid ounces of beverage you consumed.

Answer:

' Fluid oz. of beverage
'
PRINT 3 * 12 + 2 * 16 + 32, " ounces consumed"
END
  • Three 12 oz. cans of Jolt = 3 * 12 ounces
  • Two pint bottles of Mountain Dew = 2 * 16 ounces
  • One quart bottle of Pepsi = 32 ounces
The program prints:
100  ounces consumed
Because of operator priority, the number of each type of container was multiplied by the container size.

(Parentheses)

Just as in ordinary algebra, parentheses may be used in arithmetic expressions to re-arrange the order in which operations are performed. Arithmetic inside parentheses is done first. So
(10 + 6) / 2
means "add 10 to 6" then divide the result by 2. Here is a program to average two numbers:
'Compute the average of 10 and 6
'
PRINT "The average is", (10 + 6) / 2
END
Without using ( ) this program would be hard to write.

QUESTION 14:

You have taken three tests in a course and received the grades:
  • 68 (the Jolt all-nighter did not help)
  • 84
  • 92
Write a program to print out the average of your test grades.

Answer:

' Average of three test grades
'
PRINT "Average Test Grade:", (68 + 84 + 92) / 3
END
When the PRINT statement executes will do the arithmetic (first the addition, then the division).
(68 + 84 + 92) / 3  = 244 / 3  = 81.33333 
--------------
   do first
Then it will print to the monitor:
Average Test Grade:     81.33333 

(Parentheses) and Division

A common combination is to divide the sum of several numbers by the sum of several other numbers. In paper-and-pencil arithmetic this might look like:
    12 - 8 + 4
    ----------
      2 + 6
The big horizontal division line makes the grouping clear: the arithmetic above the line is done, then the arithmetic below the line is done, and then the two results are divided. In QBasic do this with TWO SETS of parentheses:
(12 - 8 + 4) / (2 + 6)
The insides of BOTH sets of ( ) must be done before the division is performed. So the above is done like:
(12 - 8 + 4) / (2 + 6)  =  8 / (2 + 6)  =  8 / 8  =  1
------------                   -------
   first                        next

QUESTION 15:

What will the following program write to the monitor:
' Division example
'
PRINT (10 + 2) / (3 + 3)
END


Answer:

(10 + 2) / (3 + 3)  =  12 / (3 + 3)  =  12 / 6  =  2
--------                    -------
do first                    do next

Miles per Gallon

Problems asking for "miles per gallon" or "dollars per hour" or "pounds per calorie" are asking for the first value (say miles) to be divided by the second value (say gallon). Sometimes the two values are not given directly--so you must do subtraction or addition before doing the division for the "per".

QUESTION 16:

When the gas tank of an automobile was first filled the odometer read 53,438.5 miles. When the tank was next filled the odometer read 53,659.2 miles and needed 8.23 gallons of gasoline.
Examine the following program. Will it correctly calculate miles per gallon?
' Miles per Gallon
'
PRINT "miles per gallon =", 53659.2 - 53438.5 / 8.23
END



Answer:

No — parenthesis are needed around the two odometer readings so that the number of miles are calculated first, and the division is carried out second:
' Corrected Miles per Gallon
'
PRINT "miles per gallon =", (53659.2 - 53438.5) / 8.23
END

No Commas inside of Numbers

When large numbers are written on paper, commas are used to make them more readable. In QBasic, numbers do not have commas inside of them

QUESTION 17:

For your graduation party you buy a 5 gallon keg of grape soda. After the party, the keg has 1.5 gallons still left in it. How many 8 ounce glasses of grape soda did your guests drink? (There are 128 fluid ounces per gallon.)
Write a program to solve this problem.


Answer:

' Glasses of Grape soda
'
PRINT "glasses of soda =", 128 * (5 - 1.5) / 8
END
The parentheses are needed:
  • Number of gallons used = (5 - 1.5)
  • Number of ounces in the gallons used = 128 * (5 - 1.5)
  • Number of 8 ounce glasses of soda = 128 * (5 - 1.5) / 8

(Extra Parenthesis)

In the above program we relied on both parentheses and operator priority to do the arithmetic in the correct order:
128 * ( 5 - 1.5 ) / 8  =   128  * 3.5 / 8  =  448 / 8  =  56 
      -----------          ----------         -------
        do first            do next           do last
Remember that since * and / have equal priority, when there are two of them in an expression the leftmost is done first.
Sometimes you would like to use parentheses to carefully show in what order the arithmetic will be done, even if the parentheses are not really needed. For example, the above program could have been written as:
' Glasses of Grape soda
'
PRINT "glasses of soda =", (128 * (5 - 1.5)) / 8
END                        
                           ^               ^                           
The two parentheses marked with a "^" are not needed. This program will calculate and print exactly the same thing as the previous program. But now the extra parentheses make clear what will be done before the division by 8 is carried out.

QUESTION 18:

What will the following program print?
' Extra Parentheses
'
PRINT  (12 - 6 + 2)
END                        


Answer:

8
The rule for parentheses is that what is inside parentheses is calculated first. In (12 - 6 + 2) everything is inside parentheses, so the parentheses don't have any effect. But they don't hurt anything.

Nested Parenthesis

When there are sets of parentheses inside parentheses the innermost set of parentheses is calculated first. The innermost set of parentheses are nested within the outer set. For example:
( 5 *  (1 + 2)  ) / 3  =  ( 5 * 3 ) / 3  =  15 / 3 = 5
       -------            ---------
      innermost            do next
      so do first

QUESTION 19:

What will the following program print to the screen:
PRINT (4 * (10 - 7)) / 6


Answer:

2 is printed to the monitor:
(4 * (10 - 7) ) / 6  =  (4 * 3) / 6  =  12 / 6  =  2
      ------            -------
     first              second

Complicated Pricing

Examine the following story problem:
Bob's Copy Shoppe charges 3 cents per page plus 5 cents per staple. You have a booklet that is made by stapling 7 pages together. Say that you want 25 copies of the booklet.

QUESTION 20:

Will the following program correctly calculate the price?
' Duplicating costs: 7 pages, 3 cents per page, 5 cents per staple
' 25 copies
PRINT  (7 * 3 + 5) * 25 / 100, "dollars"
END


Answer:

Yes -- the program will calculate the correct price in dollars. Study how the arithmetic is carried out. The value inside the parentheses is the cost in cents of each booklet. That value is multiplied by the number of copies, 25, to get the total cost in cents. The total cost in cents is divided by 100 to get the cost in dollars.
(7 * 3 + 5)  *  25 / 100  =  (21 + 5)    * 25 / 100  =  26 * 25 / 100  =
-----------                  --------                   -------
do first                    keep working                do next
 
 
650 / 100 = 6.50
---------
finally

Arithmetic Inside Parentheses

The first thing done is to work with the parentheses:
(7 * 3 + 5)  *  25 / 100  =  (21 + 5)   *  25 / 100
-----------                  --------                
do first                    keep working   
Inside the parentheses are two operators: * and +. Do the * first, because it has highest priority. Then keep working by doing the +:
 (21 + 5)   *  25 / 100  = 26 * 25  /  100
 --------                
keep working   
When the insides of the ( ) is completed you are left with a number, 26. The rest of the work is done using the left to right rule:
26 * 25  /  100  =  650 / 100 = 6.5
-------
leftmost
of two operators of
equal priority

QUESTION 21:

What does the following program print to the monitor?
' Parentheses first
'
PRINT ( 2 * 3 + 2 ) / 4


Answer:

2 is printed to the monitor:
( 2 * 3 + 2 ) / 4  =  ( 6 + 2 )  /  4  =  8 / 4  =  2
  -----                 -----
The () is evaluated first, which takes two steps because there are two operators.

Parenthesis must Match

For every left parenthesis "(" there must be a right parenthesis ")" and the two ( ) must enclose something that makes sense. The following is correct:
( 3 * 3 + 4 ) / 2.3
The following is not correct (it has a SYNTAX error):
( 3 * 3 + ) 4 / 2.3

QUESTION 22:

Does the following program have a syntax error?
' Possible error
'
PRINT "Answer is", (5 + 4) / 9 )
END


Answer:

Yes — the program has a syntax error because there is no match for the rightmost parenthesis. It is not needed. The following program is correct:
' No syntax error
'
PRINT "Answer is", (5 + 4) / 9 
END

End of the Chapter

That is the end of this chapter. You may wish to review the following:
The next chapter will discuss variables, which are important in writing longer programs. And there will be Story Problems Galore!

Reactions:

0 comments :

Post a Comment

This Blog Provides Many Tips & Tricks About Computer.
Once Visit This Blog Again.
Thank You. (By Blog Author)

Related Posts Plugin for WordPress, Blogger...

 
Blogger Widgets