|
As we have seen, computers operate on a sequence of instructions, known as programs. To make program generation easy and programs readable by others, a logical approach is a reasonable requirement. Code should be structured in a manner that makes it easily understood. Mathematical analysis tells us that any problem may be solved by a series of steps that include one or more of three so called control structures...
We'll look at each of these next. The choice of which to use in what order depends on how you have set up your problem solution. SequenceA sequence control structure is a series of statements (operations) that do not involve choices or repeating. As a simple example, consider the problem of adding two values (X and Y):
SelectionDecisions are made with this control structure. The usual program statement associated with selection is IF...THEN...ELSE, where you do one thing or another based on the outcome of a test. Let's add overtime to a base pay if overtime was expended. In selection, a test variable is first checked. One of two paths is then taken depending on the test result.
In this case, if the test yields false then control passes to the next step in the program. If true, overtime pay is computed and added, then control is passed to the next step. LoopingOften, program logic will require a given task to be performed a number of times. There are three types of loop, depending upon the logical need:
The For... loop requires you to specify the number of times the program will repeat the given task. Where you are not certain, one of the other two looping types would be preferred. Here is an example,
Line 1 sets a memory location equal to zero. The next line defines a loop that will repeat exactly 100 times and execute the command found in the third line. This simple program fragment adds the positive integers between 1 and 100. Each time the For... statement is executed, the variable I is incremented by one, until its value reaches 100. The While..Do loop will continue to execute so long as a stated condition continues to be True. The test for the condition is made at the top of the loop.
This program fragment loops while number is even. Note that the test is performed first so the loop may never be executed if number is odd. The Repeat..Until loop, like the While..Do loop, continues until a condition changes. The major difference is that the Repeat loop is always executed at least once.
(Prints numbers 1 - 10 on the screen) |
Please use the contact
form for questions or comments about this web site.
Copyright © 2001
Computer Knowledge, All Rights Reserved
Pray the Rosary for peace.