lunes, 7 de abril de 2014

Arrays

Arrays

A Hat Many programs deal with large amounts of data. For example, a program that works with images might deal with millions of numbers. If each number were kept in its own variable, there would be millions of variables, each with its own name. This would be awkward. QBasic can use an array to store a large amount of data, avoiding the need for so many variables.

Chapter Topics:

  • Collections of things.
  • Arrays.
  • Subscripts.
  • The LET statment and arrays.
  • Variables as subscripts.
  • Expressions as subscripts.

QUESTION:

Imagine that you had a collection of 500 hats, and that you wanted to name each hat. What scheme could you use to name your hats?

If you own just a few hats, individual names might work, but if you own many hats it is much easier to number them. The first hat is numbered "1," the second hat is numbered "2," and so on up to "500."
Now you could ask for "hat 32" or maybe send "hat 84" out for cleaning. If you add new hats to your collection, you can assign each one a new number in sequence. By using numbers to designate hats, you have a never-ending supply of hat names.
Collections of things often have acquisition numbers like these so that the items of the collection can easily be identified.

QUESTION:

Now imagine that you also have a collection of 100 ties. Can you give each tie its own number?

You feel like stepping out for the night, and look at your collection. You decide to wear
 
hat 73 
tie 19
No problem.
There are two things that are needed to ask for an item:
  1. The name of the collection ("hat" or "tie").
  2. The item number.
The numbering scheme within one collection is independent of other collections. You can have hat number 13 and also have tie number 13, assuming that both exist.

QUESTION:

Say (as before) that you have 500 hats. Can you ask for hat number 577?

In programming, when you have a collection of similar items, each with an item number, the collection is called an array, and the item number is called a subscript.
To refer to a specific item in an array do this:
arrayName( subscript )
The name of the array is followed by the item number (the subscript) inside of parentheses.
For example, say that DAY$ is an array of strings—one for each day of the week. Then,
LET DAY$(1) = "Monday"
makes "Monday" the first string of the array:
  1. DAY$ is the name of the array (the collection of items).
  2. the (1) selects item number 1.

QUESTION:

What (do you suppose) the following does?
LET DAY$(1) = "Monday"
PRINT "The day is", DAY$(1)
(Don't run this program yet. It needs more work.)

Tell QBasic how many items are in your array like this:
DIM arrayName( 1 TO size )
DIM asks for an array. The arrayName is the name of the array. It will have subscripts 1, 2, 3, 4, ... up to size.
Here is how to ask for an array named DAY$ that holds strings numbered from one to seven:
DIM DAY$( 1 TO 7 )

QUESTION:

If DAY$ is as above, is the following statement correct?
DAY$(8) = "Memorial Day"
 
Here is a program that uses an array:
DIM DAY$(1 TO 7) ' Make an array of seven strings. LET DAY$(1) = "Monday" ' Make "Monday" the first string. PRINT "The day is", DAY$(1) ' Print out the first string. END The program is complete. You can enter it into QBasic and run it. It writes out:
The day is Monday When this program begins, it creates an array. The array holds seven items, and each item is a string. Each string starts out as the "empty string"—it contains no characters. Then the string "Monday" is put into the first position. Here is a picture of the array after the first two statements have executed:
Monday
 
 
 
 
 
 
1
2
3
4
5
6
7
The array is a collection of numbered "slots". In this picture there are seven slots, numbered 1, 2, 3, ... 7. "Monday" is in the first slot, DAY$(1).

QUESTION:

Fill in the blank so that "Tuesday" is put into the second slot.
LET DAY$(_____) = "Tuesday" 
 
Here is how this statement would work as part of a complete program:
DIM DAY$(1 TO 7) ' Make an array of seven strings LET DAY$(1) = "Monday" ' Make "Monday" the first item LET DAY$(2) = "Tuesday" ' Make "Tuesday" the second item PRINT "The day is", DAY$(1) ' Print out the first item. END After the second LET statement, the array looks like this:
Monday
Tuesday
 
 
 
 
 
1
2
3
4
5
6
7

QUESTION:

Put a statement at the end of the program that will print out the second day.
 


You can change the data in an array. For example, the following program changes the first item of the array:
DIM DAY$(1 TO 7)               ' Make an array of seven strings
LET DAY$(1) = "Monday"            ' Make "Monday" the first item
PRINT "The day is", DAY$(1)       ' Print out the first item.
LET DAY$(1) = "Manic Monday"      ' Change the first item to "Manic Monday"
PRINT "The day is", DAY$(1)       ' Print out the first item.

END
When the program runs, it will print out:
The day is    Monday
The day is    Manic Monday

QUESTION 8:

Fill in the blanks of the following program so that the array DAY$ is filled with the days of the week, in order:
DIM DAY$(1 TO 7)               ' Make an array of seven strings
LET DAY$(1) = "Monday"            ' Make "Monday" the first item
LET DAY$( _____ ) =  _________    
LET DAY$( _____ ) =  _________    
LET DAY$( _____ ) =  _________    
LET DAY$( _____ ) =  _________    
LET DAY$( _____ ) =  _________    
LET DAY$( _____ ) =  _________    
END 
 
Here is the program that fills every slot of the array with the name of a day:
DIM DAY$(1 TO 7) ' Make an array of seven strings LET DAY$( 1 ) = "Monday" ' Make "Monday" the first item LET DAY$( 2 ) = "Tuesday" LET DAY$( 3 ) = "Wednesday" LET DAY$( 4 ) = "Thursday" LET DAY$( 5 ) = "Friday" LET DAY$( 6 ) = "Saturday" LET DAY$( 7 ) = "Sunday" END After all the slots have been filled, here is how the array looks:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
1
2
3
4
5
6
7

QUESTION:

Imagine that the following statements are in the program, just before END. Fill in the blanks so that the days of the week are printed out in order.
PRINT "The days are ", DAY$( __ ), DAY$( __ ), DAY$( __ ), DAY$( __ ) PRINT DAY$( __ ), DAY$( __ ), " and " DAY$( __ )
 

The program does not do anything practical. It is just an example of how arrays work. Here is another not-very-practical program: Say that you have an important date this week, and want the program to print out what day it is on. The following program uses the string variable HOTDATE$ to hold the name of the important day. That name will be copied from one of the array slots:
DIM DAY$(1 TO 7)               ' Make an array of seven strings
LET DAY$(1) = "Monday"            ' Make "Monday" the first item
LET DAY$(2) = "Tuesday"    
LET DAY$(3) = "Wednesday" 
LET DAY$(4) = "Thursday"     
LET DAY$(5) = "Friday"    
LET DAY$(6) = "Saturday"     
LET DAY$(7) = "Sunday"    

LET HOTDATE$ = DAY$(5)            ' Copy the fifth DAY$ into HOTDATE$
PRINT "Important date on:", HOTDATE$ 
END

QUESTION:

What does the above program write out?

An expression such as this
DATE$(5)
is called a subscripted variable. The name of the whole array is DATE$. The subscript, 5, is used to pick a single slot of the array. A subscripted variable is the combination of the array name and a subscript.
You can use a subscripted variable anyplace an ordinary variable can go. For example, in the above program a value was copied from a subscripted variable to an ordinary variable:
LET HOTDATE$ = DATE$(5)

QUESTION:

Your Friday evening hot date has been cancelled. Change the statement so that HOTDATE$ is changed to "Saturday" (change only the subscript in the program).

Well, that was easy. To ask for the 6th item in the array, all you do is use subscript 6. What if the 6 is kept in a variable? Inspect the following program:
DIM DAY$(1 TO 7)               ' Make an array of seven strings
LET DAY$(1) = "Monday"            ' Make "Monday" the first item
LET DAY$(2) = "Tuesday"    
LET DAY$(3) = "Wednesday" 
LET DAY$(4) = "Thursday"     
LET DAY$(5) = "Friday"    
LET DAY$(6) = "Saturday"     
LET DAY$(7) = "Sunday"    

LET WHICH = 6
LET HOTDATE$ = DAY$(WHICH)    
PRINT "Important date on:", HOTDATE$ 
END
The program uses correct syntax. The expression DAY$(WHICH) is a correct subscripted variable.

QUESTION:

What will the above program write out?


Remember that when a LET statement executes, it goes through several steps:

A LET Statement

  1. Finds memory for each NEW variable in the statement. (If there are no new variables, this step does nothing.)
  2. Does the calculation on the RIGHT of the equal sign. (If there is nothing to calculate, it just uses the value that is there.)
  3. Replaces the contents of the variable to the LEFT of the equal sign with the result of the calculation.
LET statements used with subscripted variable are no exception. However, a bit of extra work is done to deal with the subscript:
LET WHICH = 6

      +-------  Step 1.  Memory is found for the variable HOTDATE$
      |
      |
LET HOTDATE$ = DAY$( WHICH )
             |     |
             |     |  
             |     +----- Step 2. A value is found for the expression on the RIGHT.
             |                    This now involves getting the value in WHICH,
             |                    then getting the value in DAY$(6), 
             |                    the string "Saturday"
             |
             +------ Step 3.  The value is copied into the variable HOTDATE$

This is easy enough with the above statement, but things can get much more complicated.

QUESTION:

Do things have to get more complicated?

Here is an example of things getting a little bit complicated:
DIM DAY$(1 TO 7)               ' Make an array of seven strings
LET DAY$(1) = "Monday"            ' Make "Monday" the first item
LET DAY$(2) = "Tuesday"    
LET DAY$(3) = "Wednesday" 
LET DAY$(4) = "Thursday"     
LET DAY$(5) = "Friday"    
LET DAY$(6) = "Saturday"     
LET DAY$(7) = "Sunday"    

LET WHICH = 1
LET HOTDATE$ = DAY$(WHICH+2)   
PRINT "Important date on:", HOTDATE$ 
END
In this program, the subscript in the last LET statement is the result of a calculation.

QUESTION:

What does this program write out?

Here are the complicated parts of the program:
LET WHICH = 1
LET HOTDATE$ = DAY$(WHICH+2)   
You can understand what goes on by going through the steps of a LET statement:
  1. First, memory is found for HOTDATE$.
  2. Second, a value for the right of the "=" is calculated:
    • WHICH is replaced with its value: 1
    • The calculation 1+2 is done, resulting in: 3
    • The string in DAY$(3) is found: "Wednesday"
  3. The value "Wednesday" is copied into HOTDATE$
Done!
Go through these steps a few times. Understanding how this works now will save you effort later on.

QUESTION:

How much later on?



FOR Loops

FOR Loops

This chapter discusses another way of doing loops: the FOR statement. FOR statements are especially convenient for implementing counting loops. DO WHILE loops can be used for the same purpose, but are less convenient.

Chapter Topics:

  • The three parts of a loop.
  • The FOR statement.
  • Syntax of the FOR statement.
  • Making tables of values using the FOR statement.
  • Common bugs with FOR statements.
  • Adding up a list of numbers.

QUESTION:

(Review:) What will this loop print out?
' Counting Loop
'
LET COUNT = 0            'Statement 1
'
DO  WHILE COUNT <= 2     'Statement 2
  PRINT COUNT            'Statement 3
  LET COUNT = COUNT + 1  'Statement 4
LOOP 
END
 
 
That was an easy question. But there is a good chance that you got it wrong. This is because there are three things you have to think about to get the correct answer:
  • The starting value of the counter.
  • How the counter is tested in the WHILE.
  • How the counter is incremented in the body of the loop.
The statements that do these things are spread out in the program:
' Counting Loop ' LET COUNT = 0 'Statement 1: start the counter ' DO WHILE COUNT <= 2 'Statement 2: test the counter PRINT COUNT 'Statement 3 LET COUNT = COUNT + 1 'Statement 4: increment the counter LOOP END But all you want to do (in this program) is to count 0, 1, 2.

QUESTION:

Wouldn't it be nice to have an easy way to say "count up from zero to two" (or whatever range you wanted)?

Here is a program that does the same thing as the previous program, but uses a FOR loop to say "count up from zero to two."

' Counting Loop---using a FOR
'
FOR COUNT = 0 TO 2       'Statement 1
  PRINT COUNT            'Statement 2
NEXT COUNT               'Statement 3
END
Statement 1 does three things:
  • It uses the variable COUNT for counting.
  • It starts the count at zero.
  • It lets the count go up to the value 2.

QUESTION:

What statement is in the body of the loop?

It would be OK to say that statement 3 is also in the loop body, but really it is a "bracket" that shows where the loop body ends (like the LOOP statement in a DO WHILE loop.)
' Counting Loop---using a FOR
'
FOR COUNT = 0 TO 2       'Statement 1
  PRINT COUNT            'Statement 2
NEXT COUNT               'Statement 3
END
As always, use indenting to show the statements that are contained between two brackets. The NEXT COUNT has one other purpose: it shows where COUNT changes from its current value to the next value. This change is done automatically. You should not put in a statement to do it.

QUESTION:

What is the next value in this loop after 0?

Here is a diagram that shows how the COUNT changes as the program runs:
' Counting Loop---using a FOR
'
'                    values of COUNT changing over time --->
' 
FOR COUNT = 0 TO 2   0        1         2         3
  PRINT COUNT          0         1         2
NEXT COUNT                1         2         3
END
  • COUNT starts out at 0, stays 0 for the PRINT statement, then changes to 1 at the NEXT COUNT statement.
  • Execution returns to the top of the loop
  • AT the top of the loop COUNT is 1, it stays 1 for the PRINT statement, then changes to 2 at the NEXT COUNT statement.
  • Execution returns to the top of the loop
  • At the top of the loop (again) COUNT is 2, it stays 2 for the PRINT statement, then changes to 3 at the NEXT COUNT statement.
  • Execution returns to the top of the loop
  • Now at the top of the loop it is 3, but 3 is greater than the ending count 2, so the loop is exited.

QUESTION:

What does the following program print?
' Counting Loop 
FOR COUNT = 1 TO 4
  PRINT COUNT
NEXT COUNT        
END
 
You can use any variable for the counter variable in a FOR loop. But usually you should dedicate one variable to the task of counting, and use other variables for what ever other purposes you have. The variable that is dedicated to keeping the count is sometimes called a loop control variable. It is an ordinary numeric variable. There is nothing special about it except in how it is used.
Here is a program that counts from 5 to 10. The loop control variable is named I.
' Counting Loop---count from 5 to 10 ' FOR I = 5 TO 10 PRINT I; ' notice the semicolon, but don't worry about it just now NEXT I END

QUESTION:

What is printed by the above program?

In general, the FOR statement looks like this:
FOR counter = startingValue TO endingValue
  loopBody
NEXT counter
Remember that the term syntax means "the grammar of a program." Syntax tells you how a program (or part of a program) should look. Here are some rules about FOR statements:
  1. The counter is a numeric variable.
  2. You can use counter in the loopBody, but don't change it (this happens automatically with the NEXT.)
  3. startingValue and endingValue can be arithmetic expressions or variables.
  4. loopBody can be any number of statements.
  5. NEXT counter shows the end of the loop body, and shows where counter will change to its next value.
These rules look worse than they are. A few examples will make them clear. Here is a correct program:
' Counting Loop 
'
LET START = 1
LET FINISH = 5
FOR I = START TO FINISH
  PRINT I;         
NEXT I        
END

QUESTION:

Find at least 4 rules from the above list that this program illustrates.

The program is correct, so all the syntax notes are followed. The loop body in this program only has one statement.
  1. counter is a numeric variable.
  2. You can use counter in the loopBody, but don't change it (this happens automatically with the NEXT.)
  3. startingValue and endingValue can be arithmetic expressions or variables.
  4. loopBody can be any number of statements.
  5. NEXT counter shows the end of the loop body.
Here is the program with four of the notes illustrated.
' Counting Loop 
'
LET START = 1      ' Note 3
LET FINISH = 5     ' Note 3
FOR I = START TO FINISH     ' Notes 1 and 3
  PRINT I;                  ' Notes 2 and 4
NEXT I              ' Note 5
END
This program prints the integers from one to five, all on one line.

QUESTION:

Does syntax tell you how the FOR statment works (not just how it looks)?

 
Here is the general form of the FOR (again):
FOR counter = startingValue TO endingValue
  loopBody
NEXT counter
Some rules about how the FOR statement works:
  1. The first time loopBody is executed, counter has the value startingValue.
  2. Each time control hits the NEXT counter statement, counter is increased by 1, and control is sent back to the top.
  3. The final time loopBody is executed, counter has the value endingValue.
  4. If startingValue is greater than endingValue, the loopBody will not be executed even once.
The last rule looks a little odd, but sometimes it is important. Here is a program that illustrates it:
' Counting Loop 
'
LET START = 7
LET FINISH = 5
FOR I = START TO FINISH
  PRINT I;  
NEXT I  
END

QUESTION:

  1. Is the program's syntax correct?
  2. What does the program print out?
The program is correct in syntax. The startingValue in the FOR statement is 7. This is OK so far as syntax goes. The program asks to start I out at 7 and count up to 5. Since I is already larger than 5, the loop is just skipped.
Here is a program where this behavior makes better sense:
' Counting Loop with user input
'
PRINT "What start do you want"
INPUT START
'
PRINT "What finish do you want"
INPUT FINISH
'
FOR COUNT = START TO FINISH
  PRINT COUNT;  
NEXT COUNT
'
END
Sometimes the data input from a user means that only part of a program should execute. It is nice that this happens automatically without additional statements.

QUESTION:

  • If the user types 10 for START and 14 for FINISH what will the program print?
  • If the user types 5 for START and 3 for FINISH what will the program print?
Say that you want a program to write out the squares of numbers from zero to 25. Remember that the square of a number is the number times itself. You want the output to look something like this:
Number       Square
0            0
1            1
2            4
3            9
     . . .
25           625
The program needs to do two things: (i) count from zero to 25, and, (ii) calculate the square of each number. This sounds like a good place for a FOR loop. Here is a start on the program:
' Make a table of squares from 0 to 25
'
PRINT "Number", "Square"
'
LET START = ____________
'
LET FINISH = ____________
'
FOR NUM = START TO FINISH
  PRINT  ______________, _______________   
NEXT NUM
'
END

QUESTION:

Fill in the blanks so that the program works.


 

String Variables

String Variables

A sequence of characters is called a string. So far we have been using strings for labeling the output of programs. This chapter will discuss more ways to use strings.

Chapter Topics:

  • String variables
  • Names for string variables
  • What characters can be in strings
  • Changing the contents of string variables
  • INPUT with strings
  • Relational expressions and logical expressions with strings

QUESTION:

In all our programs so far, what does a variable hold?

The sequence of characters "Miles per Gallon" in the following program is a string:
LET MILES = 200
LET GALLONS = 10
PRINT MILES / GALLONS, "Miles per Gallon"
END
So far you have been using strings for labeling the output of your programs or for prompting the user to enter a number. This chapter will discuss more ways to use strings.
Computer programs that work with strings are very common. For example, word processing programs manipulate character data. These programs use string variables to hold the character data.
Remember what a variable is:
A variable is a small amount of computer memory that has been given a name. You (the programmer) think of the name you want to use. The QBasic system finds some memory for that name.
So far in this course you have been using numerical variables to store numbers in the computer's memory. For example, the variables GALLONS and MILES in the previous program are numerical variables.
A string variable is a variable that holds a character string. It is a section of memory that has been given a name by the programmer. The name looks like those variable names you have seen so far, except that the name of a string variable ends with a dollar sign, $.
The $ is part of the name. If you forget to put it at the end of a name, the QBasic system will think you want a numerical variable.

QUESTION:

Which of the following are correct names for string variables?
  • NAME$
  • WORDS
  • person$
  • $sum
  • VAL $

Here is a program that uses a string variable.
LET NAME$ = "Sherlock Holmes"
PRINT NAME$
END
When this program is run the following happens:
  1. Execution starts with the first statement:
    • Since the variable NAME$ has not been seen before, the system finds memory for it.
    • The variable starts out empty—there are no characters stored in it.
    • Now the characters from right of the = are copied into the variable.
    • (The quote marks "" are not copied since they are not part of the string.)
  2. Execution continues with the second statement:
    • The characters stored in memory in the variable NAME$ are printed out.
The following will appear on the monitor screen:
Sherlock Holmes

QUESTION:

Here is a slightly different program:
LET NAME$ = Sherlock Holmes
PRINT NAME$
END
What do you think will happen with this new program? (Hint: this is a trick question.)

The correct program is:
LET NAME$ = "Sherlock Holmes"
PRINT NAME$
END
The quote marks are needed to show what characters are part of the string. Without the quote marks it is not clear what the programmer wants.

QUESTION:

Here is the program again, with a slight change:
LET NAME$ = "Sherlock Holmes"
PRINT NAME
END
What do you think will happen with this new program? (Hint: this is another trick question.)


When a string variable starts out (the first time it is seen in a program) it starts out empty. It contains no characters. This is like numerical variables starting out containing a zero. If a string variable is seen for the first time in a LET statement, then it will immediately filled with characters:
LET NAME$ = "Sherlock Holmes"
     |       ---------------
     |              |
     |              |
     |              +--- 2. but the LET statement will immediately
     |                      put these characters in it.
     |
     +---- 1. when NAME$ is created it will be empty.
Usually you don't need to think about this. However if you misspell a variable name, what your program might do is explained by this rule.

QUESTION:

Here is another program:
LET NAME$ = "Professor Moriarty"
PRINT NAM$
END
What do you think will be printed on the screen? (Hint: this is yet another trick question.)

String variables contain strings of characters. The characters can be any printable character on the keyboard, including spaces and punctuation (but not function keys, the enter key, and some others.) In a LET statement you show what characters you want in the string by starting with a quote (  "  ) then typing in whatever you want, then ending with a quote (  "  ) . The quote marks will not be part of the string stored in memory.
Space is a character. It takes up as much memory as any other character. Here is a program that puts a long string into the variable NAME$ .
LET NAME$ = "Dr. John H. Watson, M.D."
PRINT NAME$
END
All the characters between the first and last " are put into NAME$. The spaces, comma, periods, and upper and lower case letters are copied to the variable exactly as in the LET statement.
A string can have very many characters in it. There is a limit to how big it can be, but you won't need to worry about that.

QUESTION:

How many characters are in the following string? (Remember that the quote marks are not part of the string.)

"A B C D "
 
Look at the following program:
' Assignment with numerical variables LET CASH = 100 LET WORTH = CASH PRINT WORTH ' END The first LET statement creates the variable CASH then puts the number 100 into it:
CASH
100
The second LET statement creates the variable WORTH, then gets a number from CASH to copy into WORTH:
WORTH
100
The number in CASH does not change. The program prints 100 to the screen.

QUESTION:

Could the programmer use another LET statement to change the number that is in WORTH?

Just as with numeric variables, string variables can be changed as the program runs. String variables can be changed:
  • In LET statements using string literals.
  • In LET statements using other string variables.
  • In INPUT statements.
Here is an example of the first two:
' Assignment with string variables
'
LET NAME$ = "Luke Skywalker"
PRINT NAME$
'
LET NAME$ = "Darth Vader"
PRINT NAME$
'
LET PERSON$ = NAME$
PRINT PERSON$
'
END
  1. The first LET statement creates NAME$ and puts "Luke Skywalker" into it.
  2. The PRINT statement prints that out.
  3. The next LET statement copies "Darth Vader" into NAME$, replacing what was there before.
  4. The next PRINT statement prints "Darth Vader"
  5. The last LET statement creates PERSON$. Then it gets characters from NAME$ and copies them into PERSON$.
  6. The last PRINT statement prints "Darth Vader" because that is what is in PERSON$
So the screen will look like:
Luke Skywalker
Darth Vader
Darth Vader

QUESTION:

Do you think you can change a string variable by copying a number into it, like:
LET NAME$ = 45.08
 
 

 


Logical Expressions

Logical Expressions

The IF statements and the DO WHILE statements of the previous chapters could only ask simple questions, like COUNT < 10 or HUE >= 16. Often simple questions like these are not enough. This chapters discusses ways to ask more complicated questions.

Chapter Topics:

  • Relational Expressions (review)
  • Logical Expressions
  • AND Operator in QBasic
  • Checking that a number is in range
  • Syntax of Logical Expressions
  • OR Operator in QBasic
  • Comparison between AND and OR

QUESTION:

You have decided to bake some cookies (much cheaper than getting them at the Mall.) An interesting cookie recipe calls for 4 cups of flour and 1 cup of sugar. You look in your supplies and find 3 cups of flour and 2 cups of sugar.
Can you bake cookies with the supplies that you have?

The question about whether you have enough supplies has two parts:
You need at least 4 cups of flour   AND   You need at least 2 cups of sugar
Since you do not have enough flour, you don't have enough supplies.

QUESTION:

What if you had 9 cups of flour and 1 cup of sugar. Now could you follow the recipe?

In order to bake cookies two things must be true:
  • You must have at least 4 cups of flour.
  • You must have at least 2 cups of sugar.
If one of these requirements is false, then you do not have enough ingredients. A QBasic program that follows this logic is:
' Cookie Ingredients Checker
'
PRINT "How much flour do you have"
INPUT FLOUR
PRINT "How much sugar do you have"
INPUT SUGAR
'
IF FLOUR >= 4 AND SUGAR >= 2 THEN
  PRINT "You have enough ingredients"
ELSE
  PRINT "You do not have enough"
END IF
'
END
The IF statement is asking a question with two parts:
IF FLOUR >= 4 AND SUGAR >= 2 THEN
   ----------     ----------
   flour part     sugar part
Each one of these parts is a relational expression (as in the previous chapters.) A relational expression looks at two numbers and gives you TRUE or FALSE.

QUESTION:

Say that you enter 9 for FLOUR and 1 for SUGAR. What answer (TRUE or FALSE) does each of the parts give you?
               
FLOUR >= 4  ________________

SUGAR >= 2  ________________
 
Here is the program again:
' Cookie Ingredients Checker ' PRINT "How much flour do you have" INPUT FLOUR PRINT "How much sugar do you have" INPUT SUGAR ' IF FLOUR >= 4 AND SUGAR >= 2 THEN PRINT "You have enough ingredients" ELSE PRINT "You do not have enough" END IF ' END For you to have enough ingredients, both relational expressions must be TRUE. This is the role of the AND between the two relational expressions. The AND requires that both
FLOUR >= 4 and
SUGAR >= 2 are true before the entire question is true. The entire question must be true in order for the true branch to execute.
The two part question is an example of a logical expression. A logical expression looks at the TRUE and FALSE answers of relational expressions. It will itself give you a TRUE or FALSE.

QUESTION:

Look at the program. How will the monitor screen look if the user types 6 for FLOUR and 4 for SUGAR?

When execution gets to the IF statement, it finds that
FLOUR >= 4   —— true, because 6 >= 4
and
SUGAR >= 2    —— true, because 4 >= 2
Since both sides are true, the two part question gives us TRUE.
AND is used in a logical expression to insist that there is a TRUE on both sides:
this side must be true  AND this side must be true
If both sides are true, the entire AND expression is true. If either side (or both) are false, the entire AND expression is false. AND is called a logical operator because it combines two true/false values into a single true/false value.
A compact way of saying what AND does is:
  • true AND true = true     -- This is the only true.
  • false AND true = false
  • true AND false = false
  • false AND false = false
AND is used to check that every requirement is met.

QUESTION:

Look at the logical expression:
FLOUR >= 4 AND SUGAR >= 2 
What will the expression give us if FLOUR is 2 and SUGAR is 0?

 

Single-branch IF Statements

Single-branch IF Statements

This chapter looks at more ways to use the IF-THEN-ELSE statement.

Chapter Topics:

  • Single-branch IF statements.
  • Problems with unexpected data.
  • Picking the right relational symbol.
  • Several IF statements in a program.

QUESTION:

You are walking through the Mall and are a little bit hungry. You approach a cookie store and are tempted by the pleasant aromas. What will you do?

The decision is about whether to buy cookies or just stroll on by. The decision looks like this:
Start at the top, then follow the line to the question:
Are You Hungry?
The answer to the question is either TRUE or FALSE.

If the answer is TRUE,
follow the line labeled TRUE,
to the box "Buy Cookies",
then follow the line to "Done".
If the answer is FALSE
follow the line directly to "Done".

QUESTION:

How is this chart different from the ones in the previous chapter?



The "cookie problem" is about whether to do something extra. The choice is about whether to add a visit to the cookie shop to your shopping trip. Here is a QBasic program that imitates the cookie problem. The user types "1" if hungry, and "0" if not:
PRINT "Enter 1 if you are hungry; 0 if you are not"
INPUT HUNGER
'
IF HUNGER > 0 THEN
  PRINT "Buy Cookies"    ' true branch
END IF
'
PRINT "Keep Shopping"     ' this statement is always done
END
The words IF, THEN, and END IF are brackets that divide the program into branches. This is just like the decisions of the previous chapter, but now the only branch is the true branch.
  • The IF statement always asks a question (usually about the number in a variable.)
  • If the answer is TRUE the true branch is executed.
  • If the answer if FALSE the true branch is skipped.
  • In both cases, execution continues with the statement after the END IF.

QUESTION:

The user runs the program and enters "1". What will the program print?

Here is the program again:
PRINT "Enter 1 if you are hungry; 0 if you are not"
INPUT HUNGER
'
IF HUNGER > 0 THEN
  PRINT "Buy Cookies"    ' true branch
END IF
'
PRINT "Keep Shopping"     ' this statement is always done
END
And here is the program as a chart:
Look at both the program and the chart to see how they correspond.

QUESTION:

Say that the user enters a 0. What will the program will print?

Here is the program again.
PRINT "Enter 1 if you are hungry; 0 if you are not"
INPUT HUNGER
'
IF HUNGER > 0 THEN
  PRINT "Buy Cookies"    ' true branch
END IF
'
PRINT "Keep Shopping"     ' this statement is always done
END
The relational expression (the question) in the IF statement tests if HUNGER is greater than zero. If the user enters "1" the expression is TRUE and the "Buy Cookies" branch will execute. But any number greater than zero will also work.

QUESTION:

What will happen if the user enters a 10?

Programs with decisions (or loops) in them are controlled by relational expressions. Relational expressions always give TRUE or FALSE, even for undexpedted data. The user did not follow the instructions, but the relational expression went ahead and used what was entered to get TRUE. Then the true branch was executed. This might not be what the user wanted; perhaps the user thought 10 should mean "thirsty." Computer programs have a hard time with unexpected data, like the 10.
The IF-THEN-END type of decision has only one branch, which is either skipped or not skipped. If there is a block of statements you want to skip sometimes and execute other times you put it in an IF-THEN-END stucture. Now you just have to be sure to ask the right question in the IF.
Say that you are at the Mall again, and have found a nice $44.95 sweater, but might not have enough money to buy it. (You spent too much on cookies.) Here is a program that decides if you can buy the sweater:
PRINT "How much money do you have"
INPUT CASH
'
IF ________________ THEN
  PRINT "Buy the Sweater"    ' true branch
END IF
'
PRINT "done"
END

QUESTION:

What relational expression should be in the blank? (Assume that there is no sales tax.)

Sweater Program  
Here is what happens for one run of the program:
How much money do you have
? 78.23
Buy the Sweater
done
The true branch was executed because the relational expression was true. Here is another run of the program:
How much money do you have
? 14.96
done
The true branch is skipped because the relational expression was FALSE. Relational expressions always give TRUE or FALSE. Use the correct relational symbol (=, >, <, and others) to ask a question that will be TRUE when you want the true branch to be executed.

QUESTION:

Would the relational symbol < have worked in the above program?


Decision Making

Decision Making

In this chapter you will look at how computer programs make decisions based on numbers and variables. This is done with a statement called the IF-THEN-ELSE statement. This is a very useful statement. It will be an important building block in building up large programs.

Chapter Topics:

  • Two-way Decisions.
  • QBasic IF-THEN-ELSE statement.
  • Outline of a two-way decision.
  • Relational Expressions.
  • Relational Symbols.
  • Example Programs.

QUESTION:

You are driving in your car and it starts to rain. The rain falls on your windshield and makes it hard to see. What should you do with the windshield wipers?

The windshield wipers are controlled with an ON-OFF switch. The decision to turn the switch on looks like this:
two way decision
In this picture of a decision, you are supposed to start at the top, then follow the line to the question:
is it raining?
The answer to the question is either TRUE or FALSE.
If the answer is TRUE, 
     follow the line labeled TRUE,
     do the directions in the box "turn wipers on",
     follow the line to "continue"

If the answer is FALSE
     follow the line labeled FALSE,
     do the directions in the box "turn wipers off",
     follow the line to "continue"

QUESTION:

How many ways can you go from "start" to "continue"?

The "windshield wiper" decision is a two-way decision (sometimes called a "true-false" decision.) It seems small, but in programming very complicated decisions can be made up of many small decisions.
Here is a QBasic program that includes a two-way decision:
PRINT "Enter a Number"
INPUT NUMBER
'
IF NUMBER >= 0 THEN
  PRINT "The number is zero or positive"    ' true branch
ELSE
  PRINT "The number is negative"    ' false branch
END IF
'
PRINT "Bye"     ' this statement is always done
END
The words IF, THEN, ELSE, and END IF are brackets that divide the part of the program into two branches. The ELSE is like a dividing line between the "true branch" and the "false branch".
  • The IF statement always asks a question (usually about the number in a variable).
    • The answer will be TRUE or FALSE.
  • If the answer is TRUE only the true-branch is executed.
  • If the answer is FALSE only the false-branch is executed.
  • No matter which branch was chosen, execution continues with the statement after the END IF.
A two-way decision is like picking which of two roads to take to the same destination. The fork in the road is the IF statement, and the two roads come together just after the END IF statement.

QUESTION:

The user runs the program and enters "12". What will the program print?

Here is the program again, done as a chart. Because the answer to the question was "true", the path on the left was done.
two way decision in a program
The "two-way split" of the program is easy to see in a two dimensional chart. It is harder to see this in a program.

QUESTION:

The user runs the program and enters "-5". What will the program print?

Here is the program again with some added statements:
PRINT "Enter a Number"
INPUT NUMBER
'
IF NUMBER >= 0 THEN
  PRINT "The number is zero or positive"    ' true branch
  PRINT "Positive numbers are > 0"          ' true branch
ELSE
  PRINT "The number is negative"    ' false branch
  PRINT "Negative numbers are < 0"  ' false branch
END IF
'
PRINT "Bye"     ' this statement is always done
END
The statements in the true branch are executed when the question in the IF statement is TRUE. There can be as many statements as you want in the true branch. The true branch consists of the statements between the IF statement and the ELSE statement.
Of course, the statements in the false branch are executed when the question in the IF statement is FALSE. There can be as many statements as you want in the false branch. The false branch consists of the statements between the ELSE statement and the END IF statement.

QUESTION:

In answer to the question, the user enters a 17. What will the new program print?

Here is how an outline of how to make a two-way decision:
... statements done before the decision
'
IF condition THEN
    ....  ' true branch
    ....  
    ....  ' true branch
ELSE
    ....  ' false branch
    ....
    ....  ' false branch
END IF
'
... statements done after the branch comes back together
Here are some details:
  • The IF condition THEN must be on one line.
  • The condition compares variables and values.
    • The statements in the true branch must be one per line.
    • There can be as many statements in the true branch as you need.
  • The ELSE statement must be by itself on a line.
    • The statements in the false branch must be one per line.
    • There can be as many statements in the false branch as you need.
  • The END IF statement must be by itself on a line.
The condition looks like the part of a DO WHILE condition statement that compares what is held in a variable with other values. You can use the same comparisons: <, <=, =, and so on.

QUESTION:

Is the following program correct?
PRINT "Enter a Number"
INPUT NUMBER
'
IF NUMBER >= 0 THEN
  PRINT "The square root is:", SQR( NUMBER )
ELSE  PRINT "There is no square root"
  PRINT "Run the program again."
END IF
'
PRINT "Bye" 
END
 
The IF, THEN, ELSE, and END IF are like brackets that emphasize the parts of the two-way branch. The QBasic system requires that you put the ELSE and END IF on their own lines to keep the true and false branches clear.
PRINT "Enter a Number" INPUT NUMBER ' IF NUMBER >= 0 THEN PRINT "The square root is:", SQR( NUMBER ) ELSE PRINT "There is no square root"       <---- Wrong!!! PRINT "Run the program again." END IF ' PRINT "Bye" END So the above program is incorrect because the ELSE was not alone on its line.

QUESTION:

How would you fix the above program?


 




Loops

Loops

Many machines do their work by using repeated motions, cycles. The engine in your car performs the same motions over and over again as it burns gasoline to provide power. Electric motors are similar; they convert electric power into spinning motion. Both of these machines are useful because they do the same things over and over and can keep going as long as we want.
Computer programs, also, use cycles. Much of the usefulness of computer software comes from doing things in cycles. In programming, cycles are called loops. When a program has a loop in it, some statements are done over and over as long as is needed to get the work done. Most computer programs execute millions of program statements each time they are used. Most of these statements are the same statements being executed over and over many times. This chapter discusses loops in QBasic.

Chapter Topics:

  • The DO ... LOOP
  • Using CONTROL-BREAK to exit a loop.
  • The loop body.
  • Indenting loop bodies.
  • Sequential Execution and Looping Combined.
  • The SOUND statement.

QUESTION:

Think of some machines (mechanical or otherwise) that use cycles.

Here is a program that uses a loop:
' Example of a loop
'
DO                        
  PRINT "Type a number"
  INPUT NUMBER
  PRINT "6% of the number is", NUMBER * 0.06
LOOP                     
END
The DO statement marks the beginning of several statements that will be done again and again. The LOOP statement marks the end of those statements. When this program runs this is what happens:
  • The program starts with the DO statement. The DO shows the beginning of the loop.
  • The first PRINT statement is executed and prints "Type a number".
  • The INPUT statement is executed and gets a number to put in the variable NUMBER.
    • Say that the user typed in 100.
  • The second PRINT statement prints "6% of the number is" and then computes and prints six percent of NUMBER.
    • If the NUMBER is 100, the program will print "6% of the number is 6"
  • The LOOP statement marks the end of the loop.
At this point, the statements between DO and LOOP have each executed one time. They are about to execute a second time.

QUESTION:

What does the monitor look like at this time?

Here is the example program, again:
' Example of a loop
DO                       
  PRINT "Type a number"
  INPUT NUMBER
  PRINT "6% of the number is", NUMBER * 0.06
LOOP                     
END
The statements between DO and LOOP have each been executed once. The variable NUMBER has the value 100 in it:
NUMBER
100
Now the statements inside the loop start again with the first statement after DO:
  • For a second time, the PRINT statement prints "Type a number".
  • For a second time, the INPUT statement gets a number to put in the variable NUMBER.
    • Say that the user typed in 50. The number 50 will replace what was previously in the variable.
  • For a second time, the second PRINT statement prints "6% of the number is" and then computes and prints 50 * 0.06.
  • The LOOP statement marks the end of the loop.
At this point, variable NUMBER now has the new value of 50 in it:
NUMBER
50
The monitor now shows:
Type a number
? 100
6% of the number is 6
Type a number
? 50
6% of the number is 3

QUESTION:

What do you suppose happens next. Have the user enter the number 200.

Now the monitor shows:
Type a number
? 100
6% of the number is 6
Type a number
? 50
6% of the number is 3
Type a number
? 200
6% of the number is 12
The variable NUMBER has the new value of 200 in it:
NUMBER
200
The program will continue forever, performing the statements inside the DO ... LOOP again and again. If you run this program, you will have to stop it, somehow. To stop the program, hit CONTROL-BREAK. (Hold down the key marked "Ctrl" then tap the key marked "Break.")

QUESTION:

Why not just let the program run until it ends?

Look again at the program:
' Example of a loop
DO                        
  PRINT "Type a number"
  INPUT NUMBER
  PRINT "6% of the number is", NUMBER * 0.06
LOOP                     
END
The DO and the LOOP are matched like brackets ( ) or [ ]. The statements inside of them will be done over and over, starting with the first enclosed statement and going on in sequence. You can have as many statements as you need between DO and LOOP:
DO     ' start of loop
       '   first  statement to be repeated 
       '   second statement to be repeated
       '   third  statement to be repeated
       '
       '
       '   last   statement to be repeated
LOOP   ' end of loop
END

QUESTION:

Do you see anything in the DO or the LOOP statement that says how many times the statements between them are to be repeated?

The statements between the DO and LOOP are called the body of the loop. So you can say that for the example program, the loop body is repeated endlessly.
Soon you will learn how to write loops that do not repeat endlessly. Sometimes, however, endlessly repeating loops are useful.

A Story Problem

Say that you are in charge of putting price tags on new merchandise in a clothing store. A new shipment of several hundred items has just arrived. You have a list that tells you the wholesale price of each item. The markup in your store is 50 percent, so the price tag should be 1.5 times the wholesale price. You would like a program that asks you for the wholesale price of an item and then prints the retail price, and keeps doing that over and over (since you have hundreds of items).

QUESTION:

In rough outline, what do you suppose the program looks like?
 
The steps you want to repeat are about the same as you would do with paper and pencil. A QBasic program can do them automatically. The DO ... LOOP makes the program cycle endlessly until all the work has been completed. Here is the program:
' Retail price calculator for 50% markup
' 
DO     
  PRINT "Enter wholesale price"            ' ask the user for the wholesale price 
  INPUT WHOLESALE                          ' get the price, put it in a variable
  PRINT "Retail price:", WHOLESALE * 1.5   ' compute and print out the retail price
LOOP  
END

QUESTION:

Say that the first three items have wholesale prices of 100 dollars, 200 dollars, and 50 dollars. What will the monitor look like after you have entered those items?

Here is our program:
' Retail price calculator
' with 50% markup
DO     
  PRINT "Enter wholesale price"            ' ask the user for the wholesale price 
  INPUT WHOLESALE                          ' get the price, put it in a variable
  PRINT "Retail price:", WHOLESALE * 1.5   ' compute and print out the retail price
LOOP  
END
The DO and the LOOP bracket the loop body. To clearly indicate which statements are in the loop body, indent each statement between DO and LOOP. This is as important to programming as grouping sentences into paragraphs is important to writing good English.

QUESTION:

Are prices in a store always marked up by 50 percent?

Here is the situation:
  • A shipment of several hundred items has arrived at your store.
  • You have a list that tells you the wholesale price of each item.
  • The markup is to be a certain percent.
  • The program should repeatedly ask you for the wholesale price of an item and then print the retail price.
Let us say that different shipments have different markups. One shipment might be marked up 50 percent; another might be marked up 100 percent.
So you want a program that first asks the user for the markup percent. It just asks once and then uses that percent for the rest of its work. The program then repeatedly asks for the wholesale price and prints the retail price, as before.

QUESTION:

In rough outline, how will this modified program look? (Hint: the repeated statements are nearly the same as before.)

Here is the QBasic program which follows the outline:
' Retail price calculator
' with markup entered by the user

PRINT "Enter the amount of markup in percent"
INPUT MARKUP
LET RATE = 1 + MARKUP / 100 

DO     
  PRINT "Enter wholesale price"            ' ask the user for the wholesale price 
  INPUT WHOLESALE                          ' get the price, put it in a variable
  PRINT "Retail price:", WHOLESALE * RATE  ' compute and print out the retail price
LOOP
END
Most of the work of the program is done in the DO ... LOOP. The first three statements are done to set things up and need to be done only once. (We are assuming that the MARKUP is the same for all items so we need to enter it only once.)

QUESTION:

The user wishes to run the program using a markup of 10%. What do the first three statements of the new program do? What numbers are stored in MARKUP and RATE?

Here is what happens in detail:
  1. The first statement writes "Enter the amount of markup in percent" on the monitor.
  2. The next statement:
    • Finds memory for the variable MARKUP.
    • Writes a "?" on the monitor.
    • Puts what the user typed (let us say 10) into MARKUP.
  3. The third statement:
    • Needs to calculate a number for 1 + MARKUP / 100
    • So it looks in MARKUP and gets a 10.
    • Does the division first because division is high priority: 1 + 0.1
    • Does the addition: 1.1
    • Puts the resulting number in MARKUP.

QUESTION:

After the first three statements have executed, what happens with the program? (Just say what happens in general; no details are needed.)

So now the program is about to start repeating the statements in the loop body. Memory looks like this:
MARKUP
10
RATE
1.1
Look at the looping part of the program:
' Retail price calculator
' with markup entered by the user
PRINT "Enter the amount of markup in percent"
INPUT MARKUP
LET RATE = 1 + MARKUP / 100
DO     

  PRINT "Enter wholesale price"            ' ask the user for the wholesale price 
  INPUT WHOLESALE                          ' get the price, put it in a variable
  PRINT "Retail price:", WHOLESALE * RATE  ' compute and print out the retail price

LOOP
END
The loop works as it did in the previous program, except that now the multiplication involves two variables. Here is what the screen might look like:
Enter the amount of markup in percent
? 10
Enter wholesale price
? 100
Retail price: 110
Enter wholesale price
? 200
Retail price: 220
Enter wholesale price
? 50
Retail price 55
Enter wholesale price
?
As before, end the program by typing CONTROL-BREAK.

QUESTION:

It might be nice to print out the RATE used to multiply prices after the user enters the MARKUP. Think of a PRINT statement that will do this. Where should it be placed in the above program?

The PRINT statement should be the fourth statement of the sequential statements in front of the DO:
' Retail price calculator
' with markup entered by the user
PRINT "Enter the amount of markup in percent"
INPUT MARKUP
LET RATE = 1 + MARKUP / 100
PRINT "The price multiplier is:", RATE
DO     
  PRINT "Enter wholesale price"            ' ask the user for the wholesale price 
  INPUT WHOLESALE                          ' get the price, put it in a variable
  PRINT "Retail price:", WHOLESALE * RATE  ' compute and print out the retail price
LOOP
END
When the program starts up, the first four statements will be done in sequence:
Enter the amount of markup in percent
? 10
The price multiplier is:    1.1
After that, the program runs as before.

QUESTION:

  • How many times is a statement outside of a loop executed?
  • How many times is a statement inside of a loop executed? 
Often a store has different markups for different items. New Spring clothing might have a markup of 50%. Items like socks might have a markup of 15%. In this situation you would like the markup program to ask for the percent markup for each item. Here is a run of the new program working:
Enter the amount of markup in percent
? 50
The price multiplier is:    1.50
Enter wholesale price
? 100
Retail price:   150
Enter the amount of markup in percent
? 15
The price multiplier is:    1.15
Enter wholesale price
? 100
Retail price:   115
Enter the amount of markup in percent
? 10
The price multiplier is:    1.1
Enter wholesale price
? 100
Retail price:   110
Enter the amount of markup in percent
? 
Notice what is being repeated each time.

QUESTION:

Look at the previous version of the program. How would you modify it so that it performs like the above example? (Hint: no new statements are needed. All you need to do is move some statements to a new place in the program.)

The statements now between the DO and WHILE are repeated each time the loop body is executed.
' Retail price calculator
' with markup entered by the user
' for each item
DO     
  PRINT "Enter the amount of markup in percent"
  INPUT MARKUP
  LET RATE = 1 + MARKUP / 100
  PRINT "The price multiplier is:", RATE
  PRINT "Enter wholesale price"            ' ask the user for the wholesale price 
  INPUT WHOLESALE                          ' get the price, put it in a variable
  PRINT "Retail price:", WHOLESALE * RATE  ' compute and print out the retail price
LOOP
END

QUESTION:

Do statements inside of a loop look much different from those that are not?

Look again at the program's output:
Enter the amount of markup in percent
? 50
The price multiplier is:    1.50
Enter wholesale price
? 100
Retail price:   150
Enter the amount of markup in percent
? 15
The price multiplier is:    1.15
Enter wholesale price
? 100
Retail price:   115
Enter the amount of markup in percent
? 10
The price multiplier is:    1.1
Enter wholesale price
? 100
Retail price:   110
Enter the amount of markup in percent
? 
This is hard to read. The program would be improved if:
  1. It wrote a brief message to greet the user when the program starts out. This should happen just once.
  2. It wrote a blank line after printing each retail price. This can be done with statement that is just the command PRINT, and nothing else on the line.

QUESTION:

Add two new statements to the above program to implement these two new features.


The statements between DO and LOOP are called the loop body. Each time the loop is repeated, these statements are executed in sequence.

QUESTION:

Modify the program so that it writes
Hello World
How are You?
repeatedly.












 




Beginning Graphics

Beginning Graphics

Up until now, our programs did output by printing characters to the monitor. Programs can also output graphics to the monitor. This chapter discusses ways to draw simple pictures on the monitor screen.

Chapter Topics:

  • SCREEN statement
  • COLOR statement
  • PSET statement
  • LINE statement
  • The graphics screen
  • Pixels
  • Arithmetic and graphics
  • Variables and graphics
  • CIRCLE statement
  • INPUT and graphics
Different computers have different graphics hardware. Electronic signals must be sent to this hardware to start it going before your program can do graphics. The QBasic statement that starts up graphics is:
SCREEN 12
This SCREEN statement says we want to use graphics in "mode 12." There are about 13 modes. Most modes are for older computers and are of no interest to us.

QUESTION 1:

Do you think that your computer has graphics hardware?

SCREEN Statement

Read this entire page before entering and running the example program.
A program must have a SCREEN statement before it does any graphics. A computer that is more than fifteen years old might need to use one of the older SCREEN modes. We will always use SCREEN 12. Here is a graphics program which puts one spot on the monitor screen. To be safe, close down any other programs you have running on your computer before you run this one.
'Put a spot on the screen at column 30 row 50
SCREEN 12
PSET (30, 50)
END
When you run the program, the QBasic system starts up the graphics hardware and a graphics screen will appear on your monitor. This screen is a temporary replacement for the screen that you usually see on your monitor. You should see a small spot close to the upper left of the monitor screen.
The monitor screen will be filled with the graphics screen. (The above image is smaller than the graphics screen you will see.) At the bottom of the screen you should see the prompt:
Hit any key to continue
Hit some key (like "enter") and you will go back to the QBasic screen which shows your program. However, the QBasic screen will now completely fill the monitor screen.

To return to the normal Screen:

To get back to the usual situation where QBasic fills just one window on the screen, do this:
  1. Press and hold down the keys <alt><enter> (press the "Alt" key, keep holding it down, and press the "enter" key).
  2. You should be back to the normal screen. If not, click the mouse in the screen and repeat <alt><enter>
  3. .
This is an awkward procedure, so practice it a few times before you enter long programs.

QUESTION 2:

What is wrong with the following program?
'Put a spot on the screen at column 30 row 50
PSET (30, 50)
SCREEN 12
END

PSET

Here is the correct version of the program:
'Put a spot on the screen at column 30, row 50
SCREEN 12
PSET (30, 50)
END
The SCREEN statement starts up the graphics hardware so that now other graphics statements can be done.
The PSET statement stands for Pixel Set. A pixel is a dot on a computer graphics screen. Pixel stands for picture element. "Set" means to "turn on," so this statement turns on one dot on the screen. All computer graphics pictures are made of thousands of pixels. The PSET statement looks like this:
PSET (column, row)
Column and row can be numbers or variables. The part of the statement (column, row) says where on the graphics screen to set the pixel.

QUESTION 3:

Look at the following piece of graph paper. What is the column and row number of the square with the X?

Columns and Rows

Here is that graph paper again, now with more squares marked:
The position of each square is given by its column number and row number. For instance, the square with the # is column=1 row=5. The square with the $ is column=5 row=1. Notice that you have to be careful to get column and row in the right order.

QUESTION 4:

What is the column and row of the square marked with ?


X and Y

People usually talk about places on the computer graphics screen as "X and Y" rather than "column and row."
Here is the graph paper again, but now the sides are labeled "X" and "Y":
X starts at zero on the left and increases to the right. Y starts at zero at the top and increases going down (this is unlike graphs in math books where Y usually increases going up).

QUESTION 5:

What are the X and Y values of the squares marked with *, #, $, and ?


The Computer Graphics Screen

Remember the SCREEN statement:
SCREEN 12
This sets up the graphics hardware and selects mode 12. Selecting mode 12 is like selecting a sheet of graph paper. When you select mode 12 you get:
  • A range of X from 0 to 639.
  • A range of Y from 0 to 479.
  • 16 possible colors for pixels.
(Don't memorize these numbers. But look at them to understand get some idea of what you can do.)
With 640 columns and 480 rows you have 640 times 480 squares on the graph paper. Or, there are 640 * 480 = 307,200 pixels on the graphics screen. If you had actual graph paper with this many columns and rows, the squares on the paper would be very small.

QUESTION 6:

Write a QBasic program that sets the pixel at X = 150, Y = 32.

Setting Many Pixels

If you want to make a longer program you can start with the above program and used the "Edit" menu and the mouse to "copy" and then "paste" copies of the PSET statement:
'SET A PIXEL AT (150, 32)
'
SCREEN 12
PSET (150, 32)
PSET (150, 32)
PSET (150, 32)
PSET (150, 32)
PSET (150, 32)
PSET (150, 32)
PSET (150, 32)
END
So far this is not an improvement, since the new program just sets the same pixel over and over. But now you can use the mouse to go to various characters, remove them with the delete key and then type in new values:
'NEW PROGRAM BASED ON THE OLD
'
SCREEN 12
PSET (150, 32)  ' set X = 150  Y = 32
PSET ( 50, 30)  ' set X =  50  Y = 30
PSET ( 75, 42)  
PSET ( 25, 72)  
PSET ( 10, 90)  
PSET (  0,  0)  
PSET ( 13,  5)  
END
The new program sets seven different pixels. Usually you do not set pixels one by one like this; better ways to draw pictures will be described later.

QUESTION 7:

Many recent movies, such as Toy Story have been made with computer graphics. The computers that were used cost hundreds of thousands of dollars. How do you suppose the graphics screen on those computers compares to the graphics screen on ours?

 

The COLOR Statement

Even though the computers used for Toy Story were much more expensive than ours, their computer graphics is fundamentally the same as ours:
  • The graphics screen looks like graph paper.
  • Each square of the graph paper (a pixel) has X and Y coordinates.
  • Each pixel is set to a color.
  • Digital images are made by setting the color of each pixel.
It would be awful if you had to say what color each and every pixel should be. So the graphics screen starts out black and you can set just the pixels you want. Here is an example program:
' Setting pixels to color 4
SCREEN 12
COLOR 4
PSET (3, 3) ' set column 3 row 3
PSET (7, 3) ' set column 7 row 3
PSET (7, 7) ' set column 7 row 7
PSET (3, 7) ' set column 3 row 7
END
If you run this program you will get four red dots in the upper left corner of the screen. The COLOR 4 statement picks the color to use (out of the 16 available.) It is like picking a colored pencil out of a box. Now four pixels are set (with PSET) to color 4. Here is what the picture will look like:
Here is what it looks like on the graphics screen:
(This picture has been enlarged to show the four tiny pixels.)

QUESTION 8:

Are red pixels easier to see than white pixels?

The COLOR statement looks like this:
COLOR C      ' C is a color number, 
             ' for screen 12 it is 0 up to 15.
Here is a list of numbers and colors. This list works for screen 12 and some others (but not all screens).
Color NumberColor Color NumberColor
0Black 8Gray
1Blue 9Light Blue
2Green 10Light Green
3Cyan 11Light Cyan
4Red 12Light Red
5Magenta 13Light Magenta
6Brown 14Yellow
7White 15Bright White

QUESTION 9:

What will the following program show on the graphics screen?
' Setting pixels to color 2 (Green)
SCREEN 12
COLOR 2
PSET ( 1, 3 )  ' set column 1 row 3
PSET ( 3, 3 )  ' set column 3 row 3
PSET ( 5, 3 )  ' set column 5 row 3
PSET ( 7, 3 )  ' set column 7 row 3
END
Try to make a sketch of your answer on a piece of scrap paper.

Lines

In computer graphics, a line is made by setting many adjacent pixels to the same color. You could draw a line by using the PSET statement many times. But there is an easier way. To draw a line of pixels all of the same color use the LINE statement:
LINE  (startX, startY)-(endX, endY)
This statement:
  • Uses the current pen color.
  • Sets all the pixels along a line starting at (startX, startY) and ending at (endX, endY)
  • If a pixel along the line has already been set, it is set to the current pen color.
Here is a program that does the same as the previous program, except using a LINE statement:
' Setting 10 pixels in row 3
' to color 4 (Red)
'
SCREEN 12
COLOR 4
LINE (1, 3) - (10, 3) ' draw a line from (1,3) to (16,3)
END
The program is much shorter than the one that uses PSET. The picture on the graphics screen will look like this (slightly enlarged):
 

QUESTION 12:

The upper left corner of graphics screen 12 is (x=0, y=0); the lower right corner of the screen is (x=639, y=479). Write a program that draws a red diagonal line from the upper left corner to the lower right corner.

Several Lines

The image will look like this (in this picture, the size of the graphics screen has been made much smaller and the line has been made thicker):
Here is a program that draws a small square in the upper left corner:
' 
' Small Red Square
'
SCREEN 12
COLOR 4
LINE (1, 1) - (1, 10)   ' Left side of square
LINE (10, 1) - (10, 10) ' Right side of square
LINE (1, 1) - (10, 1)   ' Top side of square
LINE (1, 10) - (10, 10) ' Bottom of square

END
On graph paper, the square looks like this:
Of course, on the actual graphics screen the red square is much smaller.

QUESTION 13:

Modify the above program so that it draws the same square, but now:
  • The top and bottom line of the square are red (color 4)
  • The left and right line of the square are yellow (color 14)

Painting Over Pixels

Now the square looks like:
Since the red lines were drawn last, the corner pixels like (1, 1) and (10, 10) are drawn with red. Here is an enlarged view of the upper left corner of the graphics screen:

QUESTION 14:

Is it critically important what color the corners are?

Changing Color

With computer graphics, when you set a pixel to a color, its previous color is completely gone. You can't mix colors by setting a pixel to several different colors. Here is a program that draws a red line from (1, 5) to (10, 5), then draws a yellow line from (5, 5) to (10, 5). The second line will over-paint half of the first line.
' 
' Two-tone Line
'
SCREEN 12
COLOR 4                 ' Pen color 4 (red)
LINE (1, 5) - (10, 5)   ' Horizontal red line in row 5
                        ' starts in column 1 goes to column 10
                        
COLOR 14                ' Pen color 14 (yellow)
LINE (5, 5) - (10, 5)   ' Horizontal yellow line in row 5
                        ' starts in column 5 goes to column 10
                        ' replaces part of previous line
END

QUESTION 15:

Did the two colors blend together?

Jagged Lines

This is not actually a good way to draw things. Usually you don't want to change the color of pixels you have already painted, except for the pixels at the corners of figures that have been painted in several colors.
Say you wrote a program to draw a line from (x=0, y=3) to (x=11, y=6):
' Diagonal Line
'
SCREEN 12
COLOR 4                ' Pen color 4 (red)
LINE (0, 3) - (11, 6)   
END
The program will fill in the start and end pixels with red and fill in the pixels in-between. But the line will not be smooth because sometimes there will be abrupt changes between one red pixel and the next:
You can't get a smooth line because a pixel is like a square of graph paper that is either completely filled with one color or completely filled with another.
With less expensive computer graphics, diagonal lines can be very jagged. Sometimes in newspapers and magazines you can tell when a picture has come out of a computer because of its rough, grainy appearance. Here are some magnified jaggy lines on part of a graphics screen:
With expensive computers, the squares of the graph paper of the graphics screen are so small that they are hard to notice.

QUESTION 16:

You are having problems with jagged, grainy graphics on your computer. Will buying a bigger monitor help?


Circles

Circles are important in drawing pictures. The statement to draw a circle is:
CIRCLE  (centerX, centerY), Radius
In the CIRCLE statement:
  • the center of the circle is (centerX,centerY)
  • the radius of the circle is Radius
  • centerX, centerY, and Radius can be numbers or variables
  • the circle is drawn with the current pen color
The circle that QBasic draws is a like that you could draw with a compass on paper--(centerX,centerY) says where to put the compass point, and Radius says how big the circle is.
Here is a program to draw a circle at the center of the screen:
' Draw a circle at the center of the screen
SCREEN 12
COLOR 7
CIRCLE  (320, 240), 50
END
There are 640 columns across, so the middle of the screen for X is 320. There are 480 rows down, so the middle of the screen for Y is 240. The picture will look something like this:
 

QUESTION 17:

What is the radius of the circle?

domingo, 6 de abril de 2014

The INPUT Statement

The INPUT Statement

In this chapter you will learn about the QBasic INPUT statement. The INPUT statement gets data from the computer keyboard.

Chapter Topics

  • Input and Output in a computer system.
  • INPUT statement.
  • Prompting the user.
  • Entering number data.
  • Using several INPUT statements.
Up until now in these notes, all the data a program uses have been part of the program itself. For example:
' Calculate Miles per Gallon
'
LET MILES = 45678.3 - 45149.6
LET GALLONS = 12.5
PRINT MILES / GALLONS
END
The data is the first odometer reading (45149.6), the second odometer reading (45678.3), and the number of gallons.

QUESTION 1:

Will this program do the same thing each time it is run?

Input Devices

Consider the program.
LET MILES = 45678.3 - 45149.6
LET GALLONS = 12.5
PRINT MILES / GALLONS
END
Every time you run the program it will do exactly the same thing. The next time you fill up your gas tank again, you would have to change the program to calculate with the new values. The program is not very useful.
Most useful computer programs input data from various sources when they run. Input means data that comes from outside the program. A program that does this can work with new data each time it is run.

Sources of Input Data

  • the keyboard
  • a hard disk
  • a floppy disk
  • a CD-ROM
  • the mouse
  • a video camera
  • an audio digitizer (part of a sound board)
  • the Internet
  • hundreds of other sources
For us, most data will come from the user of a program typing on the keyboard. Some sources of data (like audio data) require special hardware. A piece of hardware that is a source of input to a computer program is called an input device.

QUESTION 2:

Pac-man was once a popular game found in video arcades. The game was really a computer program controlling the picture on the video screen. Think of several types of input data that the program used.

Output Devices

As they run, most computer programs output data to various places. In programming, output means data that the program sends outside of itself to a some device. For us, output mostly will go to the computer monitor.

Output can be sent to:

  • the monitor
  • a hard disk
  • a diskette (floppy disk)
  • the printer
  • a sound board
  • the Internet
  • hundreds of other places
A piece of hardware that uses data from program is called an output device.

QUESTION 3:

Some devices on the list of input devices and on the list of output devices. What were some of these devices?

I/O

The hard disk of a computer system is used for both input to a program and output from a program. Other devices are exclusivelyexclusively input devices (such as the keyboard or mouse) or output devices (such as the printer and monitor.)
Input and Output are so important to a computer system that the abbreviation I/O is used. Any device which does either input, output, or both is called an I/O device. The movement of data from or to such a device is often called "I/O".

QUESTION 4:

Which of the following are NOT I/O devices?

The INPUT Statement

QBasic uses the INPUT statement to input data from the keyboard. Here is a program that asks the user for a number, then prints out that number times two:
' Double a Number
'
PRINT "Type a number"     'Ask the user for a number
INPUT NUMBER              'Get it from the keyboard, put it in NUMBER
PRINT NUMBER * 2          'Print the number times two.
END
Here is how this program looks in the QBasic window:
Program window
These statements will execute one by one in sequence. To run the program push "shift-F5" or use the menu "alt-R, S" (as usual).

QUESTION 5:

What is the first thing the program writes to the monitor

Running the Program

The first statement is an ordinary PRINT statement that writes a string to the monitor.
' Double a Number
'
PRINT "Type a number"     'Ask the user for a number
INPUT NUMBER              'Get it from the keyboard, put it in NUMBER
PRINT NUMBER * 2          'Print the number times two.
END
Now the second statement INPUT NUMBER executes. The INPUT statement is used to get data from the keyboard. It will:
  • Print a question mark "?" to the screen.
  • Wait until the user has typed in a number.
  • Get the number when the user hits the "enter" key.
  • Put the number in the variable NUMBER.
Just after this statement starts the monitor will look something like:
Type a number
? 
The question mark came from the INPUT statement. The INPUT statement is waiting for the user (you) to type a number. Say that you type 23. Now the monitor looks like:
Type a number
? 23
To enter the number, hit the enter key. The INPUT statement puts the 23 into the variable NUMBER. Next, the PRINT statement executes.

QUESTION 6:

What will the monitor finally look like?


Several Runs of the Program

You can run the program again, without making any change to it. (Push "shift-F5" to start each run.) You can enter different data for each run. Here is an example of three runs of the program:
After each run of the program, push any key to return to the QBasic screen. The picture shows the DOS window after the program was run three times.

QUESTION 7:

Does the program work with floating point numbers?

Variables with INPUT

The INPUT statement must use a variable as a place to put the data it gets. Remember that a variable is a small amount of computer memory that has been given name. There is nothing special about the variable used with INPUT. Here is the same program as before, except that it uses a different variable name. It will do exactly the same thing as the first version.
' Double a Number
PRINT "Type a number"     'Ask the user for a number
INPUT MyData              'Get it from the keyboard, put it in MyData
PRINT MyData * 2          'Print twice the number.
END
The variable should be the correct type for the expected input. Remember (from chapter 3) that the last character of a variable name indicates what the variable is expected to hold. For example, a variable VALUE# can potentially hold a very big floating point number. A variable DATA% is expected to hold an integer (no decimal point). Here is a program that does input of an integer:
' Integer Input
PRINT "Type an integer"   'Ask the user for an integer
INPUT DATA%               'Get it from the keyboard, put it in DATA%
PRINT DATA% * 2           'Print twice the number.
END

QUESTION 8:

Say that the user types 1.2 when the INPUT statement of this program asks for data. What will the monitor show after the user hits "enter"?


Nice Variable Names

For these notes, programs will mostly use ordinary variables like NUMBER that do not have a special character at the end of their name. These variables can hold a useful range of floating point numbers. If you enter a number like "1" (which you might think is an integer) the number is stored in the variable as "1.0" which is really the same thing. This avoids problems like the above.
Usually a program is written to solve a problem dealing with things in the world. Numbers are input to the program that describe real things. It is very useful to use variable names that describe what the numbers mean.
Here is a program that asks the user for the number of fluid ounces and calculates the number of gallons. Notice how the names of the variables make it much easier to see what is going on:
' Convert Fluid ounces to Gallons
'
PRINT "Enter number of fluid ounces" 
INPUT OUNCES
PRINT "Number of gallons:", OUNCES / 128
END

QUESTION 9:

Write a program that asks the user for the number of grams and prints the number of kilograms. There are 1000 grams per kilogram. Use the above program as a model.
(Write this program with paper and pencil, or just "think" it. The best thing to do would be to use QBasic to write the program and run it before you go on.)

Prompting the User

Say the above program were run and that the user entered 734 grams. The monitor would look like:
Enter number of grams
? 734
Number of kilograms:    0.734
The string "Enter number of grams" is called a prompt. A prompt is a short phrase which tells the user of a computer program what is expected. The program is said to prompt the user for input.
You should be careful that the prompt makes sense to the user of a program. The prompt is for the user; it doesn't "tell" the INPUT statement what to do. Here is a poorly written version of the "grams to kilograms" program:
' Convert grams to kilograms
PRINT "Enter number" 
INPUT GRAMS
PRINT "result:", GRAMS / 1000
END
When this program is run, and the user enters data as before, the user sees:
Enter number
? 734
result:    0.734
The answer is correct, and Mr. Spock might be happy with the program (since "logically" the two programs are the same). But the second version is not user-friendly and is prone to user error. Maybe the user though the program was converting ounces to pounds. Nothing on the monitor would correct this mistaken notion.

QUESTION 10:

Write a program which converts OUNCES to POUNDS. The program should write an informative prompt to the user, INPUT the number of ounces, then write the number of pounds.