lunes, 7 de abril de 2014

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.












 




No hay comentarios:

Publicar un comentario