CHAPTER 1 — Small Programs
In this chapter you will learn to write small programs in the computer programming language called QBasic. These small programs won't do very much. But in following chapters you will write programs that do much more.
Chapter Goals
• QBasic statements.
• The PRINT statement.
• The END statement.
• Arithmetic operators.
• Strings.
• Sequential execution.
• Syntax errors.
• Bugs.
The small programs in this chapter perform calculations similar to the arithmetic done with a electronic calculator. QBasic does much more than that. But in this chapter, pretend that QBasic is a calculator that uses a keyboard for input. Instead of punching buttons on a calculator, you will write a program.
QUESTION 1:
With a calculator does it matter in which order you push the buttons?
Answer:
Yes.
Programs
When you use a calculator to compute 10 plus 5, you must push:
10
+
5
=
... in exactly that order. Pushing
+
10
=
5
... will not work. The order is important. The same is true for computer programs.
A program is like a recipe for baking cookies: it is a list of instructions which are followed one-by-one in the correct order.
QUESTION 2:
Isn't it odd that a machine can follow a list of instructions?
Answer:
Yes. Until a few decades ago few people believed that this was possible. One of the intellectual goals of this course is for you to understand how machines can follow instructions.
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.
QUESTION 3:
How many statements are in this program?
Answer:
Two.
END is a statement. It tells the system to end this run of the program.
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.
QUESTION 4:
What do you think the above program prints on the computer monitor?
Answer:
15
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.
Answer:
15
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
Answer:
No, the program is not correct. The computer follows instructions in order. If the first instruction is END the computer ends its run of the program.
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?
Answer:
The program adds 10 to 5 and prints 15 on the monitor.
Comments are Ignored by QBasic
The new program does exactly the same thing as the old program. The two programs are the same except for the comment in the new program. Since comments are ignored, the two programs do the same thing when they are run.
Comments are intended to make it easier for humans to figure out what a program does. When you write a program, you should use comments to explain what you are doing. QBasic ignores comments and just does what the statements ask.
QUESTION 7:
Write a program that adds 1.5 to 4.2 and prints the result on the monitor.
(Write the program with paper and pencil. You can just think the answer, if you want, but please try to answer before continuing.)
Answer:
' Program to add two numbers
PRINT 1.5 + 4.2
END
If you run this program it prints 5.7 on the computer monitor.
Floating Point Numbers
The numbers that you use with QBasic are the same as those you use with an electronic calculator. You can use numbers that include a decimal fraction such as the two numbers above.
Numbers such as 1.5 or 3.14159 or 123.821 are called floating point numbers because the decimal point "floats" among the digits to get to the correct location. A number without a decimal point, such as 12 or -23 or 194, is called an integer.
QBasic can do anything an electronic calculator can do (and much more). For example, it can multiply numbers. To multiply numbers, use * instead of the usual multiply symbol (which is not on the computer keyboard). The character * is on the same key as "8" on the computer keyboard.
QUESTION 8:
Write a program that MULTIPLIES 12.1 by 2 and prints the result on the monitor. (Write the program on a scrap of paper.)
Answer:
' Program to multiply two numbers
PRINT 12.1 * 2
END
If you run this program it prints 24.2 on the computer monitor.
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.
QUESTION 9:
Write a program that prints
The sky is falling.
to the computer monitor.
Answer:
' Chicken Little's Alarm
PRINT "The sky is falling."
END
Of course, the comment in your program might not be the same as mine.
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
Answer:
Cross patch, draw the latch,
Sit by the fire and spin.
The characters (including punctuation) inside the quote marks are printed. The quote marks are not printed.
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
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.
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
Answer:
Yes. The string in the PRINT statement does not have quotes around it.
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
Answer:
If the comment is correct, then the program has a bug since in the PRINT statement the two numbers are multiplied, not added.
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:
• Computer program
• Statement
• END statement
• Comment
• Floating point number
• String
• Sequential execution
• Syntax error
• Bug
• Arithmetic operators
• Two uses of the "-" sign
• Exponentiation "^"
For more exciting Story Problems, and lots more Math, be sure to look for Chapter 2, coming soon to a screen near you.
You have reached the end of the chapter.
Friday, December 5, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment