Chapter 8. DECISION-MAKING USING THE IF AND EVALUATE STATEMENTS

CHAPTER OBJECTIVES

Upon completion of this chapter, you should be able to

  • Explain how numeric and alphanumeric fields are compared.

  • Describe the rules for forming numeric and alphanumeric literals.

  • Describe and demonstrate the use of the various IF statements.

  • Describe and demonstrate the use of the EVALUATE statement.

LOGICAL CONTROL STRUCTURES

In this chapter we focus on some instructions that enable the program to make decisions that affect the order in which statements are executed. Such instructions are referred to as logical control structures.

The full range of logical control structures used in any program, regardless of the programming language, is

  1. Sequence.

  2. Selection (IF-THEN-ELSE).

  3. Iteration (PERFORM).

  4. Case (EVALUATE).

In this chapter, we focus first on the IF-THEN-ELSE structure that permits programs to execute one or more instructions depending on the contents of fields. Then, we present the case structure, which is executed using the EVALUATE verb. In the next chapter, we consider iteration in detail, focusing on the PERFORM statement and its options.

THE IF CONDITIONAL STATEMENT

A conditional statement performs operations depending on the existence of some condition. Such statements generally begin with the word IF and are called IF-THEN-ELSE or selection structures.

THE INSTRUCTION FORMAT FOR AN IF STATEMENT

The basic instruction format for IF statements is

Instruction Format

THE INSTRUCTION FORMAT FOR AN IF STATEMENT

THEN is Optional. The THEN clause in the instruction format is bracketed [], which means that it is optional. When used, it has no effect on the execution of the IF statement. Thus, we will not include it in our examples.

The ELSE is also optional because it is enclosed in brackets. If some operation is required only if a condition exists and nothing different need be done if the condition does not exist, the entire ELSE clause may be omitted.

An imperative statement, as opposed to a conditional statement, performs an operation regardless of any existing conditions. ADD AMOUNT-IN TO AMOUNT-OUT and MOVE NAME-IN TO NAME-OUT are examples of imperative statements that do not test for conditions but simply perform operations. COBOL statements are divided into two broad categories: (1) imperative, which perform operations, and (2) conditional, which test for the existence of one or more conditions. Another way to say that "a condition exists" is to say that "a condition is met" or "a condition is true."

The flowchart and pseudocode excerpts that correspond to an IF-THEN-ELSE selection structure are

THE INSTRUCTION FORMAT FOR AN IF STATEMENT

Terminating the IF Statement. The IF statement may be terminated with the scope terminator END-IF or a period. When you use a scope terminator, a period at the end of the line is optional, except if it is the last statement in a paragraph. Then it requires a period.

A SIMPLE IF STATEMENT

An IF statement may test for a simple condition that may be a single relational test of the following form:

  1. IF identifier-1 IS EQUAL TO identifier-2.

  2. IF identifier-1 IS LESS THAN identifier-2.

  3. IF identifier-1 IS GREATER THAN identifier-2.

These three tests are considered simple relational conditions. Another example of a simple conditional is

A SIMPLE IF STATEMENT

In this example, the message 'NO TRANSACTIONS THIS MONTH' is printed only if AMOUNT-IN is zero. If AMOUNT-IN is not zero, processing continues with the next sentence without performing any operation. The ELSE clause is unnecessary in this instance.

AN IF STATEMENT WITH ELSE CLAUSE

The ELSE clause is used when two conditions exist. That is, the condition being tested can be true or false. In this situation, certain operations are performed when the condition is true, and different operations are performed when the operation is false. Consider the following.

AN IF STATEMENT WITH ELSE CLAUSE

There are two possible results of the test performed by the preceding statement.

  1. AMOUNT1 is equal to AMOUNT2.

  2. AMOUNT1 is not equal to AMOUNT2.

Explanation:

  1. If AMOUNT1 is equal to AMOUNT2, the DIVIDE operation is performed and the second part of the statement, beginning with the ELSE clause, is ignored. Then, the program continues executing with the sentence following the END-IF scope terminator, disregarding the clause that begins with the word ELSE.

  2. If the two fields are not equal, then the DIVIDE operation is not executed. Only the ELSE portion of the statement, the ADD operation, is executed. In either case, the program continues executing with the sentence following the END-IF scope terminator.

By using the word IF, we test the initial condition and perform the instruction specified. By using ELSE, we can perform an operation if the initial condition is not met, or is false.

More than One Operation Can Be Performed When a Condition Exists. More than one operation may be executed for each true or false condition in an IF statement. The following will perform two MOVE operations if AMOUNT1 is equal to AMOUNT2, or two ADD operations if AMOUNT1 is not equal to AMOUNT2.

AN IF STATEMENT WITH ELSE CLAUSE

Notice how the imperative statements (MOVE and ADD) are indented. Indent statements within the IF instruction to make programs easier to read and debug. Use the following coding style for conditionals.

AN IF STATEMENT WITH ELSE CLAUSE

The technique of indenting and coding each statement on a separate line makes reading the program easier, but it does not affect compilation or execution. When an error occurs on an IF condition line, it is easier to determine the cause of error if that line contains a single statement than if it were written as follows.

IF AMOUNT1 IS EQUAL TO AMOUNT2 ADD 5 TO TOTAL ELSE ADD 10 TO TOTAL.

In this sentence, the exact clause or statement that caused an error would be more difficult to determine.

RELATIONAL OPERATORS

Using Relational Operators in Place of Words. The following symbols for simple relational conditions are valid within a COBOL statement:

SYMBOL

MEANING

<

IS LESS THAN

>

IS GREATER THAN

=

IS EQUAL TO

<=

IS LESS THAN OR EQUAL TO

>=

IS GREATER THAN OR EQUAL TO

A COBOL conditional, then, may have the following form.

RELATIONAL OPERATORS

Note that a blank is required on each side of the symbols <,>,=,<=,>=. A conditional can also compare a field to an arithmetic expression.

RELATIONAL OPERATORS

Do Not Mix Field Types in a Comparison. Conditional statements must use fields with the same data types to obtain proper results, as in this statement:

RELATIONAL OPERATORS

CODE-IN must be an alphanumeric field, since it is compared to an alphanumeric literal. As in MOVE operations, the literal should have the same format as the data item.

If CODE-IN has a PICTURE of 9s, the following conditional would be appropriate.

RELATIONAL OPERATORS

Similarly, to ensure correct results, fields that are compared to one another should have the same data types, whether numeric or alphanumeric. Thus, in this statement, both COUNTERl and COUNTER2 are either numeric or alphanumeric:

RELATIONAL OPERATORS

NUMERIC FIELDS SHOULD NOT CONTAIN BLANKS

Suppose we write this:

NUMERIC FIELDS SHOULD NOT CONTAIN BLANKS

If AMOUNT-IN were a field defined as numeric, but actually contained a blank or any other alphabetic character, the operation would result in a decimal data error, which causes the program to terminate abnormally. This error will occur because numeric fields must contain numeric data when used in arithmetic or comparison operations. Blanks are not valid numeric data. Be certain, then, that if a field is defined as numeric, it actually contains numbers.

HOW COMPARISONS ARE PERFORMED

When comparing numeric fields, the following are all considered equal.

012 12.00 12 +12.

Numeric comparisons are performed in COBOL algebraically. Although 12.00 does not have the same internal configuration as 012, their numeric values are known to be equal.

Similarly, when comparing alphanumeric fields, the following are considered equivalent:

ABC ABC▵ ABC▵▵
(▵ denotes a blank position).

Low-order or rightmost blanks will not upset the equivalence. Only significant or nonblank positions are compared, from left to right. Consequently, ▵ABC is not equal to ABC▵ since A is not equal to blank.

EBCDIC COLLATING SEQUENCE

When performing a comparison, the hierarchy of the comparison, called the collating sequence, depends on the computer being used. As mentioned in Chapter 1, the collating sequence for IBM mainframe and midrange computers is EBCDIC. Characters are compared to one another in EBCDIC:

EBCDIC COLLATING SEQUENCE

For numeric comparisons, 012 < 022 < 042, and so on. Similarly, the computer is able to determine if data is arranged alphabetically using uppercase letters, because A is considered less than B, which is less than C, and so on. Thus,

ABCD < BBCD < XBCD, and so on.

Note, however, that lowercase letters are less than uppercase letters. Suppose you are performing an alphabetic sequence check. Smith is considered < SMITH. Note, too, that Stu < SAM. Mixing uppercase and lowercase letters, then, could produce different results in a comparison.

Similarly, if alphanumeric fields are being compared where there may be a mix of letters and digits, letters are less than numbers. Consider the following comparison.

EBCDIC COLLATING SEQUENCE

If ADDRESS-IN has a value of 'ROUTE 109', 'ROUTE 109' is less than '10 0 MAIN ST' because the first character, R, compares "less than" the number 1; hence 1 would be added to TOTAL.

Tip

DEBUGGING TIP

Do not allow alphanumeric fields to be entered as all uppercase and lowercase letters when entering data in fields. This reduces the risk that comparisons might give problematic results. If, for example, we compare NAME-IN to 'PAUL' and we inadvertently entered the name 'paul, ' the comparison would result in an unequal condition. As a convention, we recommend you use either all uppercase letters or an uppercase first character and lowercase for the remaining characters.

ENDING CONDITIONAL SENTENCES WITH A PERIOD OR AN END-IF SCOPE TERMINATOR

If the scope terminator END-IF is not used in an IF statement, the placement of periods can affect the logic. Consider the following.

ENDING CONDITIONAL SENTENCES WITH A PERIOD OR AN END-IF SCOPE TERMINATOR

Because the statement ADD PRICE2 TO TOTAL ends with a period, the last statement, MOVE 0 TO ITEM2, is always executed regardless of the comparison.

The preceding program excerpt may be flowcharted and written as pseudocode as shown in Figure 8.1

If a period were accidentally omitted after ADD PRICE2 TO TOTAL, then MOVE 0 TO ITEM2 would be considered part of the ELSE clause and would not be executed if PRICE1 were less than PRICE2. YOU can see that the placement of the period, then, can significantly affect the logic.

The scope terminator END-IF can be used to definitively specify the boundaries of an IF.

ENDING CONDITIONAL SENTENCES WITH A PERIOD OR AN END-IF SCOPE TERMINATOR

The END-IF marks the boundary of the IF statement without the need for a period. A period is optional after END-IF. If you use scope terminators to delimit instructions, then all periods except for the last one in the paragraph can be omitted.

If you are using an ELSE clause, never place a period before the ELSE. Include an END-IF or period only at the end of the sentence following all imperative statements that apply to the ELSE.

Program excerpt and pseudocode for IF statement.

Figure 8.1. Program excerpt and pseudocode for IF statement.

THE CONTINUE CLAUSE

There are times when you might want to execute a series of steps only if a certain condition does not exist. The COBOL expression CONTINUE enables you (1) to avoid performing any operation if a condition exists, and (2) to execute instructions only if the ELSE condition is met.

CONTINUE must be the only clause following a condition, since it indicates that no action is to be performed. Consider the following.

THE CONTINUE CLAUSE

If AMOUNT1 is equal to AMOUNT2, no operation will be performed, and the program will continue execution with the sentence following the END-IF. If

AMOUNT1 is not equal to AMOUNT2, 1 is added to TOTAL, and the program continues execution with the sentence following the END-IF.

We recommend that you avoid using CONTINUE by coding the preceding as follows.

THE CONTINUE CLAUSE

NESTED CONDITIONAL IF STATEMENT

A nested conditional is a conditional in which an IF statement itself can contain additional IF clauses. Consider the following.

NESTED CONDITIONAL IF STATEMENT

This is an example of a nested conditional. Because complex nesting of conditions can sometimes be confusing, we recommend that nested conditionals always be balanced by having each IF clause paired with an ELSE, as shown in the following:

NESTED CONDITIONAL IF STATEMENT

In our nested conditionals, each END-IF scope terminator will be paired with the preceding IF, except for the last END-IF, which is paired with the first IF. The use of END-IF to delimit each IF clause reduces the risk of errors. That is, it can sometimes make a logical difference in the meaning of the full statement. Consider the following comparison.

NESTED CONDITIONAL IF STATEMENT

This example conforms to the original format specified for an IF instruction, but statement-1 is a conditional rather than an imperative statement. This makes this example a nested conditional. The tests performed follow:

  1. If AMOUNT is not equal to 6, the last ELSE, PERFORM 100-RTN-1, is executed.

  2. If AMOUNT = 6, the second condition (which corresponds to statement-1) is tested as follows:

    1. (IF AMOUNT = 6) and (TAX = 10), 200-RTN-2 is performed.

    2. (IF AMOUNT = 6) and (TAX is not equal to 10), 300-RTN-3 is performed.

This procedure may also be written in terms of a decision table.

DECISION TABLE

Condition 1

Condition 2

Action

AMOUNT = 6

TAX =10

PERFORM 200-RTN-2

AMOUNT = 6

TAX ≠ 10

PERFORM 300-RTN-3

AMOUNT ≠ 6

TAX = anything

PERFORM 10 0-RTN-l

Decision tables list the various conditions that may occur and the actions to be performed. Decision tables are frequently prepared by software developers to map out or chart complex logic that requires execution of different modules depending on the results of numerous tests.

A nested conditional is really a shortcut method of writing a series of conditionals.

A nested conditional is used for the following reasons: (1) it minimizes coding effort where numerous conditions are to be tested, and (2) it tests conditions just as they appear in a decision table.

Consider the following decision table.

Condition 1

Condition 2

Action

A = B

C = D

PERFORM 100-RTN-A

A = B

C ≠ D

PERFORM 200-RTN-B

A ≠ B

anything

PERFORM 300-RTN-C

We could write this decision table as a nested conditional.

NESTED CONDITIONAL IF STATEMENT

The indenting of clauses helps to clarify the relationships between statements and should be consistently employed when coding nested conditionals. This will not only help in reading the sentence, but it will make it easier to debug your program as well. Parentheses may be included for clarification.

Thus, the general format for an IF is this:

Instruction Format

NESTED CONDITIONAL IF STATEMENT

In a nested conditional, statements 1 and 2 above can themselves be conditional statements. END-IF reduces the risk of logic errors. Consider the following.

Condition 1

Condition 2

Action

A = 5

B < 20

MOVE 30 TO C

A = 5

B >= 20

do nothing

A ≠ 5

B = anything

MOVE 25 TO D

NESTED CONDITIONAL IF STATEMENT

COMPOUND CONDITIONAL

The compound conditional offers even greater flexibility for selection and enables the IF statement to be used for more complex problems. With the compound conditional, the software developer can test for several conditions with one statement.

OR IN A COMPOUND CONDITIONAL

To perform an operation or a series of operations if any one of several conditions exists, use a compound conditional with conditions separated by OR. This means that if any one of several conditions exists, the imperative statement(s) specified will be executed. Consider the following examples.

OR IN A COMPOUND CONDITIONAL
OR IN A COMPOUND CONDITIONAL

By using OR in a compound conditional, any one of the conditions specified causes execution of the statement(s). If none of the conditions is met, the program either executes the ELSE clause, if specified, or continues with the statement following the END-IF scope terminator. Any number of conditions separated by ORs may be specified in a single statement.

In the second example, 60 0-ERROR-RTN is executed only if AMOUNT1 is greater than or equal to AMOUNT3 and AMOUNT1 is not equal to AMOUNT4. If either AMOUNT1 is less than AMOUNT3, or AMOUNT1 is equal to AMOUNT4, AMOUNT1 will be added to TOTAL, and the next sentence will be executed.

LIMITATIONS ON A COMPOUND CONDITIONAL

Using the preceding instruction format, note that the following is invalid.

Invalid Syntax:

LIMITATIONS ON A COMPOUND CONDITIONAL

With compound conditionals, the word IF is specified only once.

IMPLIED OPERANDS

In compound conditionals, it is not always necessary to specify both operands for each condition. The following example tests two simple conditions: (1) TOTAL = 7 and (2) TOTAL = 8.

IMPLIED OPERANDS

Since the identifier TOTAL is omitted from the second condition test, it is an implied operand. A full condition must be specified following the word IF. In a conditional such as IF condition-1 OR condition-2, condition-1 must include a full test; but subsequent conditions can have implied operands, where the first operand of the next condition is the one that is implied. In the clause IF TOTAL = 7 OR 8, for example, the compiler assumes you mean to compare TOTAL to 8 as well as to 7. The preceding statement can also be written as follows:

IMPLIED OPERANDS

Not Greater Than or Equal To Is Equivalent to Less Than

Note that the following three routines produce identical results.

IMPLIED OPERANDS

That is, if AMOUNT-IN is not greater than or equal to 5, it must be less than 5.

AND IN A COMPOUND CONDITIONAL

If a statement or statements are to be executed only when all of several conditions are met, use the word AND in the compound conditional. Thus, either AND or OR (or both) can be used in a compound conditional, as in this example:

Instruction Format

AND IN A COMPOUND CONDITIONAL

All conditions must be met when AND is used in a compound condition. The ELSE clause is executed if any one of the stated conditions is not met.

Suppose we want to perform 40 0-PRINT-RTN if all the following conditions are met.

AMOUNT1 = AMOUNTA; AMOUNT2 = AMOUNTB; AMOUNT3 = AMOUNTC

If one or more of these conditions is not met, 50 0-ERROR-RTN should be performed. We may use a compound conditional for this:

AND IN A COMPOUND CONDITIONAL

If all the conditions are met, 40 0-PRINT-RTN is executed. If any one of the conditions is not met, 500 -ERROR-RTN is executed.

USING AND AND OR IN THE SAME STATEMENT

There are times when both the AND and OR are required within the same compound conditional. Suppose we wish to write a routine to perform 700 -PRINTRTN if AMOUNT is between 10 and 20, inclusive of the end points (i.e., including 10 and 20).

On first sight, we might consider coding a compound conditional as follows.

USING AND AND OR IN THE SAME STATEMENT

This statement, however, will function properly only if AMOUNT is an integer. The number 10 .3, for instance, is between 10 and 20, but it will not pass the preceding tests. For a similar reason, we cannot write

USING AND AND OR IN THE SAME STATEMENT

If AMOUNT is 9.8, it is not between 10 and 20; but it passes both tests. Thus, we want to perform 700-PRINT-RTN if

(1) AMOUNT = 10,

USING AND AND OR IN THE SAME STATEMENT

We could write the compound conditional as

USING AND AND OR IN THE SAME STATEMENT

ORDER OF EVALUATION OF COMPOUND CONDITIONALS

When using both AND and OR in the same compound conditional as in the preceding example, the order of evaluation of each condition is critical. For example, consider

ORDER OF EVALUATION OF COMPOUND CONDITIONALS

Suppose A = 2, B = 2, C = 3, D = 4, E = 5,

ORDER OF EVALUATION OF COMPOUND CONDITIONALS

Order of Evaluation: Possibility 1

IF A = B OR C = D and E = F

If this is the order of evaluation, there are two ways that 600-STEP-1 will be executed: (1) A = B and E = F, or (2) C = D and E = F. That is, E and F must be equal and either A must be equal to B or c must be equal to D. Since E does not equal F, 600-STEP-1 will not be executed if this order of evaluation is correct.

Suppose, however, that the preceding instruction is evaluated as follows:

Order of Evaluation: Possibility 2

IF A = B

ORDER OF EVALUATION OF COMPOUND CONDITIONALS

If this is the order of evaluation, there are two ways that 600-STEP-l will be executed: (1) A = B, or (2) C = D and E = F. That is, either A and B are equal or C must equal D and E must equal F. Because the first condition, A = B, is met, the PERFORM will occur if this order of evaluation is correct.

Hence, if the second order of evaluation is the one actually used by the program, 600-STEP-l is executed; but if the first is used, the paragraph is not executed. Only one of these evaluations is correct. Now that the importance of the order of evaluation is clear, we will consider the hierarchy rules for compound conditionals:

  1. Conditions surrounding the word AND are evaluated first.

  2. Conditions surrounding the word OR are evaluated last.

  3. When there are several AND or OR connectors, the AND conditions are evaluated first, as they appear in the statement, from left to right. Then, the OR conditions are evaluated, also from left to right.

  4. To override Rules 1–3, use parentheses around conditions you want to be evaluated first.

Using these hierarchy rules and the preceding example, the conditions will be evaluated as follows:

IF C = D AND E = F or A = B.

With A = 2, B = 2, C = 3, D = 4, E = 5, and F = 6, 60 0-STEP-1 will be executed because A = B. To change the order so that the evaluation is performed as in possibility 1 above, write the condition as

ORDER OF EVALUATION OF COMPOUND CONDITIONALS

In this case, 600-STEP-l will not be executed.

Let us reconsider a previous example, in which we want to print AMOUNT if it is between 10 and 20, inclusive. This is often written mathematically as 10 ≤ AMOUNT ≤ 20; if 10 is less than or equal to AMOUNT and, at the same time, AMOUNT is less than or equal to 20, then we wish to print AMOUNT.

Let us determine if the following statement results in the proper test.

ORDER OF EVALUATION OF COMPOUND CONDITIONALS

Using the hierarchy rules for evaluating compound conditionals, the first conditions tested are those surrounding the word AND. Then, from left to right, those surrounding the OR expressions are evaluated. Thus, we have

IF AMOUNT = 20 AND AMOUNT = 10

ORDER OF EVALUATION OF COMPOUND CONDITIONALS

The compound conditional test in possibility 1 is always false because the value for AMOUNT can never equal 10 and, at the same time, be equal to 20. Since the first expression tested will never be true, it can be eliminated from the statement, which then reduces to this:

ORDER OF EVALUATION OF COMPOUND CONDITIONALS

Obviously, this is not the solution to the original problem. In fact, using the preceding conditional, all values for AMOUNT will cause 700-PRINT-RTN to be executed. If AMOUNT were, in fact, greater than 20, it would cause 700-PRINT-RTN to be performed since it passes the test: AMOUNT > 10. (Any number > 10 passes this test.) If AMOUNT were less than 10, it would cause 700-PRINT-RTN to be executed since it passes the test: AMOUNT < 20. (Any number < 20 passes this test.)

The original statement would be correct if we could change the order of evaluation. We want the comparisons performed according to the following hierarchy:

IF AMOUNT < 20 OR AMOUNT =20
ORDER OF EVALUATION OF COMPOUND CONDITIONALS
and AMOUNT = 10 OR AMOUNT > 10

To change the normal order of evaluation, place parentheses around the conditions you want to be evaluated first, as a unit. Parentheses override the other hierarchy rules so that all conditions within parentheses are evaluated together. Thus, the following statement is correct.

ORDER OF EVALUATION OF COMPOUND CONDITIONALS

When in doubt about the normal sequence of evaluation, use parentheses. Even when they are not necessary, as in IF (A = B AND C = D) OR (E = F) . . ., they ensure that the statements are performed in the proper sequence. Moreover, they help the user better understand the logic of a program.

By using the <= and >= operators, the preceding can be simplified as

ORDER OF EVALUATION OF COMPOUND CONDITIONALS

THE EVALUATE STATEMENT: THE CASE STRUCTURE

The EVALUATE verb is used to implement the case structure. This verb can test for a series of conditions and is often used instead of IF statements. The EVALUATE verb has the following instruction format:

Instruction Format

THE EVALUATE STATEMENT: THE CASE STRUCTURE

Suppose an input field called YEARS-IN-COLLEGE-IN is used to determine the type of processing to be performed. Using an IF statement, we could write

THE EVALUATE STATEMENT: THE CASE STRUCTURE

Once an IF condition is met in a nested conditional and its imperative statements are executed, all the ELSE clauses are bypassed and execution continues after the END-IF.

To ensure correct processing, we added a fifth condition to perform an error routine if the input field is invalid.

The EVALUATE verb enables the series of cases to be written more clearly and efficiently, and in a more structured form. We could write

THE EVALUATE STATEMENT: THE CASE STRUCTURE

The WHEN OTHER clause is executed when YEARS-IN-COLLEGE-IN is not 1, 2, 3, or 4.

Once a condition in an EVALUATE is met, there is no need for the program to test other conditions in the statement. Thus, after a condition in a WHEN is met and the corresponding imperative statements are executed, execution continues with the statement following END-EVALUATE.

The flowchart for this case structure is shown in Figure 8.2.

Flowchart for case structure.

Figure 8.2. Flowchart for case structure.

Note that we can EVALUATE an identifier or an expression such as TRUE. Another way to write the preceding EVALUATE, then, is

Flowchart for case structure.

We may also use a THRU clause with the EVALUATE. Suppose you wish to print class grades based on a student's average. The following is valid:

Flowchart for case structure.

We can also write this as

Flowchart for case structure.

We can use the EVALUATE in conjunction with condition-names as well.

Flowchart for case structure.

In this instance, GRADE would have condition-names associated with it as follows:

Flowchart for case structure.

Note that to say EVALUATE GRADE WHEN EXCELLENT . . . will result in a syntax error. You must say EVALUATE GRADE WHEN 1 . . . or EVALUATE TRUE WHEN EXCELLENT. . ..

The EVALUATE statement can be written in numerous ways. These are the three most common:

Example

Flowchart for case structure.
Flowchart for case structure.
Flowchart for case structure.

When evaluating an identifier, the WHEN clause must specify precise values—for example, WHEN 1, WHEN 0 THRU 10, and so on. We could also write EVALUATE TRUE WHEN identifier >= 1 AND <= 20 . ..

DATA VALIDATION

In this section, we focus on how IF statement can be used for data validation.

THE SIGN TEST

If a numeric field is to have either positive or negative values, we may include a sign test to validate input data.

We can test whether a field is POSITIVE, NEGATIVE, or ZERO with a sign test, as in this example:

THE SIGN TEST

Designating Fields as Signed Negative or Positive

To test a field for its sign implies that the field may have a negative value. A numeric field will be considered unsigned or positive by the program unless there is an S in its PICTURE clause. Thus, 05 AMOUNT1 PIC 9(2) is a two-position unsigned field and 05 AMOUNT2 PIC S9 (2) is a two-position signed field, unless SIGN Is LEADING SEPARATE or TRAILING SEPARATE is specified (which would make it a three-position signed field).

If you move −12 to AMOUNT1, AMOUNT1 will contain 12 because it is unsigned. Moving −12 to AMOUNT2 will result in −12 in AMOUNT2, since AMOUNT2

allows for a sign. Use S in a PIC clause of a numeric field that may have negative contents.

The phrase IF A IS EQUAL TO ZERO is the same as IF A IS ZERO. If a numeric field contains an amount less than zero, it is considered negative. If it has an amount greater than zero, then it is considered positive.

−382 is negative 382 is positive +382 is positive

TESTING FOR REASONABLENESS

Routines in a program can minimize the risk of errors going undetected, but they cannot be expected to detect all errors. Many of these routines include tests to determine if data is reasonable. Thus, although we may not be able to guarantee the validity of a salary field entered as 35000, for example, we can certainly flag as a probable error a salary field with a value of 998325. Tests for reasonableness include the following.

Range Tests. One way to validate data is to make certain that fields pass a range test; that is, the value contained in a particular field should fall within preestablished guidelines. If a valid account number contains codes from 00001 to 85432 and also from 87001 to 89005, we may include a range test as part of our validity check, like this:

TESTING FOR REASONABLENESS

Limit Tests. When a field is not to exceed a given value, we can perform a limit test. For example, a manager may establish a rule that the quantity on hand for any part must not exceed 980 units. The program should make certain that this limit is not exceeded, as in this example:

TESTING FOR REASONABLENESS

With a range test, both ends of an identifier are compared, but with a limit test the comparison is in only one direction. To test that AMOUNT1 is > 7 and < 25 is a range test, but to test that AMOUNT2 is > 250 is a limit test.

A WORKING-STORAGE entry may be defined with a VALUE clause in place of a literal in the PROCEDURE DIVISION. Consider the following alternative to the previous example.

TESTING FOR REASONABLENESS

In this example, WS-MAXIMUM-QOH is an independent item in WORKING-STORAGE defined as

05 WS-MAXIMUM-QOH PIC 9(3) VALUE 980.

The software developer decides whether to use a WORKING-STORAGE data item to store a constant in a work field or specify the constant as a literal in the PROCEDURE DIVISION. As a general rule, however, any literal that will be used more than once in the PROCEDURE DIVISION should be given an assigned storage area and a data-name in WORKING-STORAGE. Also, if the value may change from time to time, it would be easier to change the VALUE clause in WORKING-STORAGE than to look for the constant in the PROCEDURE DIVISION.

THE CLASS TEST

If an input field has a PIC of 9s, the software developer should make certain that the field does, in fact, have numeric data. Suppose we want to add AMOUNT-IN to TOTAL, where AMOUNT-IN is an input field. Since input is always subject to data-entry errors, it is possible that the AMOUNT-IN field might be entered erroneously with nonnumeric data or spaces. In such a case, ADD AMOUNT-IN TO TOTAL would result in a decimal data error, causing the program to terminate abnormally.

The following test may be used to minimize such errors.

THE CLASS TEST

If the ELSE option is executed with the NUMERIC class test, then either the field contains alphabetic data (only letters and/or spaces) or it contains alphanumeric data, meaning any possible characters. If AMOUNT-IN contains 123AB, for example, the ELSE clause will be executed since the contents of the field are not strictly numeric.

Use the NUMERIC class test to ensure that a field to be used in arithmetic has a numeric value. If a field is to be alphabetic, you could similarly use the ALPHABETIC class test. Consider the following example of an ALPHABETIC class test:

A one-position field in a record contains the number of dependents an employee claims for income tax purposes. To obtain the exemption amount to be deducted, we multiply the number of dependents by 2000. If, however, the employee claims 10 dependents, an A is placed in the field; if he or she claims 11 dependents, a B is placed in the field, and so on. We should only perform the multiplication if the field does not contain a letter, as follows:

THE CLASS TEST

CHECKING FOR MISSING DATA

One main source of error occurs when input fields are missing data. If specific fields must contain data, they should be checked before processing continues, like this:

CHECKING FOR MISSING DATA

Alternatively, we could use a class test to determine if SOCIAL-SECURITY-NUMBER contains nonnumeric data.

CHECKING FOR MISSING DATA

ALPHABETIC CLASS TEST

Any letter, either uppercase or lowercase, or blank, is considered ALPHABETIC. The three alphabetic class tests are these:

Reserved Word

Meaning

ALPHABETIC

A-Z, a-z, and blank

ALPHABETIC-UPPER

A-Z and blank

ALPHABETIC-LOWER

a-z and blank

Consider this example.

ALPHABETIC CLASS TEST

NEGATING CONDITIONALS

NEGATING SIMPLE CONDITIONALS

All simple relational, class, or sign tests may be written using a negated conditional with the use of NOT in the conditional statement. Consider the following two statements that are equivalent.

NEGATING SIMPLE CONDITIONALS
NEGATING SIMPLE CONDITIONALS

NOT NEGATIVE Is Not Equal to POSITIVE

To say, however, IF AMOUNT 1 IS NOT NEGATIVE, is not the same as saying AMOUNT1 IS POSITIVE. If AMOUNT1 is zero, it is neither one. Thus, the following two statements are not equivalent.

NEGATING SIMPLE CONDITIONALS
NEGATING SIMPLE CONDITIONALS

These are not equivalent if AMOUNT1 = 0.

Suppose AMOUNT1 is equal to 0. In example 1, 200-ADD-RTN is executed; in example 2, 100-NEGATIVE-RTN is executed. Similarly, to say IF CODE-IN IS NOT ALPHABETIC, is not the same as saying IF CODE-IN IS NUMERIC. If CODE-IN is alphanumeric, containing combinations of letters, digits, and special characters, then it is neither ALPHABETIC nor NUMERIC. Thus, the following two statements are not equivalent.

NEGATING SIMPLE CONDITIONALS
NEGATING SIMPLE CONDITIONALS

NEGATING COMPOUND CONDITIONALS

Negating compound conditionals can cause a logic error. The following example will explain the error and how it can be avoided:

The following is a routine to perform 200 -MARRIED-RTN if MARITAL-CODE is not equal to 'S' (single) or 'D' (divorced); otherwise 10 0-UNMARRIED-RTN is performed:

NEGATING COMPOUND CONDITIONALS

But suppose we want to use negated conditionals. On first thought, you may decide simply to negate each simple condition, like this:

NEGATING COMPOUND CONDITIONALS

An evaluation of this statement will show that the preceding is not correct. As written, one of two conditions must exist for 200-MARRIED-RTN to be executed, as in this example:

MARITAL-CODE IS NOT EQUAL TO 'S'
NEGATING COMPOUND CONDITIONALS
MARITAL-CODE IS NOT EQUAL TO 'D'

Suppose MARITAL-CODE is 'M' (for married); 200-MARRIED-RTN will be executed, which is what we want. If MARITAL-CODE is 'S', however, we wish 10 0-UNMARRIED-RTN to be executed. In the preceding conditional, the first condition is not met since MARITAL-CODE does equal 'S'. However, the second condition is met since MARITAL-CODE is not equal to 'D', but is equal to 'S'. Only one condition needs to be satisfied for 200-MARRIED-RTN to be executed. Since the second condition is satisfied, 200-MARRIED-RTN will be executed instead of 100-UNMARRIED-RTN, which is really the procedure we should execute.

Similarly, suppose MARITAL-CODE is 'D'. We want 10 0-UNMARRIED-RTN to be executed, but note again that 200-MARRIED-RTN is executed. The first condition is satisfied, because MARITAL-CODE is not equal to 'S'. It is equal to 'D'). Since only one condition needs to be satisfied, 200-MARRIED-RTN is executed. In fact, the sentence as written will always cause 200-MARRIED-RTN to be executed, regardless of the contents of MARITAL-CODE.

The point of this illustration is a lesson in Boolean algebra, called DeMorgan's Rule, which says, When negating conditions separated by OR: IF NOT (CONDITION1 OR CONDITION2 . . .), the stated conditions become IF NOT CONDITION1 AND NOT CONDITION2 AND. . . . Hence, the IF statement could be written as IF NOT (MARITAL-CODE = 'S' OR MARITAL-CODE = 'D') or as the following example

NEGATING COMPOUND CONDITIONALS

We negate AND statements using a similar rule: IF NOT (A = B AND C = D) . . . can be written IF A NOT = B OR C NOT = D. . ..

The hierarchy rules for statements that include negated conditionals, then, are

  1. NOT is evaluated first.

  2. AND (from left to right, if more than one) is evaluated next.

  3. OR (from left to right, if more than one) is evaluated last.

CONDITION-NAMES: CHECKING CODED FIELDS FOR VALID CONTENTS

Coded fields are frequently used in input records to minimize keystrokes and to keep the input record format shorter. Thus, a field used to indicate an individual's marital status is not likely to be keyed as "SINGLE," "MARRIED," or "DIVORCED." Rather, MARITAL-STATUS might be a one-position field that is coded with 'M' for married, 'S' for single, and 'D' for divorced.

A condition-name is a user-defined word established in the DATA DIVISION that gives a name to a specific value that an identifier could assume. An 88-level entry specified in the DATA DIVISION is a condition-name that denotes a possible value for an identifier. We may use several condition-names along with one field:

CONDITION-NAMES: CHECKING CODED FIELDS FOR VALID CONTENTS

When the field called MARITAL-STATUS is equal to 'S', we will call that condition SINGLE. The 88-level item is not the name of a field but the name of a condition; it refers specifically to the elementary item directly preceding it. SINGLE is a condition-name applied to the field called MARITAL-STATUS, since MARITAL-STATUS directly precedes the 88-level item. The condition SINGLE exists or is "true" if MARITAL-STATUS = 'S'.

A condition-name is always specified on the 88-level and has only a VALUE clause associated with it. Since a condition-name is not the name of a field, it will

not contain a PICTURE clause. The condition-name must be unique, and its VALUE must be a literal consistent with the data type of the field preceding it. That is, if MARITAL-STATUS is an alphanumeric field, the condition name must be an alphanumeric literal.

For readability, we indent each 88-level item to clarify its relationship to the data-name directly preceding it. Any elementary item on level numbers 01–49 in the FILE or WORKING-STORAGE SECTIONS may have a condition-name associated with it.

Condition-names are defined in the DATA DIVISION to simplify processing in the PROCEDURE DIVISION. A condition-name is an alternate method of expressing a simple relational test in the PROCEDURE DIVISION.

The condition-names may be used in an EVALUATE statement to determine which routine to execute, as in this example:

CONDITION-NAMES: CHECKING CODED FIELDS FOR VALID CONTENTS

In addition, the condition-names may be used in an IF statement, as follows.

CONDITION-NAMES: CHECKING CODED FIELDS FOR VALID CONTENTS

In either example above, the condition-names are tested and not the conditional variable MARITAL-STATUS.

Consider this example where condition-names provide a description for letter grades.

CONDITION-NAMES: CHECKING CODED FIELDS FOR VALID CONTENTS

Assuming that the above VALUES are the only valid ones, a PROCEDURE DIVISION test may be as follows.

CONDITION-NAMES: CHECKING CODED FIELDS FOR VALID CONTENTS

We may also say IF NOT FAILING PERFORM 270-PASS-RTN, if we can be sure that the condition NOT FAILING guarantees an entry from 'A' through 'D' only. But if GRADE contained a 'G' it would be processed improperly in 270-PASS-RTN and not recognized as an error. The following might be better.

CONDITION-NAMES: CHECKING CODED FIELDS FOR VALID CONTENTS

CREDIT-GIVEN is a condition that is met if GRADE has a value of 'A', 'B', 'C', or 'D'.

A condition-name may contain a VALUE clause that specifies a range of values. The word THRU is used to indicate this range, as in

CONDITION-NAMES: CHECKING CODED FIELDS FOR VALID CONTENTS

THRU is a COBOL reserved word. VALID-GRADE is a condition-name that is met if GRADE has any of the values 'A', 'B', 'C', 'D', or 'F'.

Consider another example.

CONDITION-NAMES: CHECKING CODED FIELDS FOR VALID CONTENTS

The condition-name VALID-YEAR is true if YEAR-OF-TRANSACTION, the field directly preceding it, has any value from 1999 to 2005, inclusive of the end points 1999 and 2005. Similarly, the statement IF NOT VALID-YEAR PERFORM 280-ERROR-IN-YEAR-RTN will cause 280-ERROR-IN-YEAR-RTN to be performed if YEAR-OF-TRANSACTION is less than 1999 or greater than 2005.

VALUE ALL may be used to specify repeated entries for a literal, like this:

CONDITION-NAMES: CHECKING CODED FIELDS FOR VALID CONTENTS

If CODE-1 = 'AAAAA' then the condition CODE-ON will be met.

VALUE ALL could also be used to initialize the field itself, as in this example:

05 LITERAL-1 PIC X(10) VALUE ALL 'AB'.

LITERAL-1 will contain ABABABABAB.

Condition-names are frequently used for indicating when an AT END condition has been reached, as in

CONDITION-NAMES: CHECKING CODED FIELDS FOR VALID CONTENTS

SET STATEMENT

One function of the SET statement is to set a condition-name to TRUE. Consider the following SET statement.

SET NO-MORE-RECORDS TO TRUE.

When this format of the SET statement is executed, the value NO associated with the condition-name NO-MORE-RECORDS is placed in its conditional variable ARE-THERE-MORE-RECORDS, according to the rules of the VALUE clause. Thus, when SET NO-MORE-RECORDS to TRUE is executed, the value 'NO ' is placed in the conditional variable ARE-THERE-MORE-RECORDS. If multiple condition-names are specified, only one condition-name can be TRUE at one time.

CASE PROBLEM

This case problem illustrates the use of the IF and EVALUATE statements. The Payroll Manager of the Best Deal Stores Company needs an Employee Pay Report for all employees of the company.

The Systems Flowchart, Input Specifications for the Employee Pay File, and Output Specifications showing the layout of the report to be produced, are illustrated here:

Systems flowchart

CASE PROBLEM

Record description layout for employee pay file—EMPPAYPF

Field Description

Type

Size

Position

COBOL Field-name

Employee Number (K)

S

9,0

1–9

EP-EMPLOYEE-NUMBER

Store Number

S

4,0

10–13

EP-STORE-NUMBER

First Name

A

15

14–28

EP-FIRST-NAME

Middle Initial

A

1

29–29

EP-MIDDLE-INITIAL

Last Name

A

15

30–44

EP-LAST-NAME

Department Number

S

3,0

45–47

EP-DEPARTMENT-NUMBER

Hourly Rate

P

5,2

48–50

EP-HOURLY-RATE

Hours Worked

P

3,1

51–52

EP-HOURS-WORKED

Sales

P

5,0

53–55

EP-SALES

Calculations to be Performed:

Bonus is calculated as follows.

If sales exceed $10,000, bonus = 10 percent of sales.
If sales are between $6,000 and $10,000, bonus = 6 percent of sales.
If sales are between $3,000 and $6,000, bonus = 3 percent of sales.
If sales are less than $3,000, bonus = 1 percent of sales.

Gross Pay = Hours Worked * Hourly Rate + Bonus.

Federal Tax Rate: If Gross Pay is equal to or exceeds $50,000, Federal Tax equals a flat tax of 22 percent.

If Gross Pay is less than $50,000, Federal Tax equals a flat tax of 14 percent.

State Tax Rate: If Gross Pay is equal to or exceeds $75,000, State Tax equals a flat tax of 12 percent.

If Gross Pay is between $50,000 and $75,000, State Tax equals a flat tax of 9 percent.

If Gross Pay is between $25,000 and $50,000, State Tax equals a flat tax of 6 percent.

If Gross Pay is less than $25,000, State Tax equals a flat tax of 3 percent.

Pension Plan Contribution = Gross Pay * 7.5 percent.

Health Insurance Contribution is $10.50 for every employee.

Life Insurance Contribution: If Gross Pay exceeds $50,000, the employee portion of the Life Insurance Contribution is 1.5 percent of Gross Pay over $45,000.

Total Tax = Federal Tax + State Tax.

Total Deductions = Pension Plan Contribution + Health Insurance Contribution + Life Insurance Contribution + Total Tax.

Net Pay = Gross Pay - Total Deductions.

Printer spacing chart for Employee Gross Pay report

CASE PROBLEM
Solution for program CPCH08A.

Figure 8.3. Solution for program CPCH08A.

Report produced from program CPCH08A.

Figure 8.4. Report produced from program CPCH08A.

END-OF-CHAPTER AIDS

CHAPTER SUMMARY

  1. Simple Relational for Selection.

    1. The relational conditions that may be used in an IF statement are

       

      IS EQUAL TO

       
       

      =

       
       

      IS LESS THAN

       
       

      <

       

      IF identifier-1

      IS GREATER THAN

      identifier-2

       

      >

       
       

      IS LESS THAN OR EQUAL TO

       
       

      < =

       
       

      IS GREATER THAN OR EQUAL TO

       
       

      > =

       
    2. If the condition exists, all statements are executed up to (1) the ELSE clause or (2) the END-IF or the period if there is no ELSE clause.

    3. If the condition does not exist, the statements after the word ELSE, if specified, are executed, or (if there is no ELSE clause) processing continues after the END-IF or with the next sentence.

    4. Comparisons are algebraic or logical:

      1. Numeric: 12.0 = 12.00 = 12 = +12

      2. Alphanumeric: ABC = ABC▵= ABC▵▵

    5. With the EBCDIC collating sequence, lowercase letters are less than uppercase letters and letters are less than numbers.

  2. Other Types of IF Statements.

    1. Compound Condition

      1. Format

        IF condition-1 OR condition-2 . ..
        IF condition-1 AND condition-2 . ..
      2. Hierarchy

        1. (1) If ORs and ANDS are used in the same sentence, ANDS are evaluated first from left to right, followed by ORs.

        2. (2) Parentheses can be used to override hierarchy rules.

  3. The EVALUATE statement is often used as an alternative to selection.

  4. Data Validation.

    1. Range tests—to ensure that data falls within a preestablished range.

    2. Limit tests—to ensure that data does not exceed a preestablished limit.

    3. Format tests—to ensure, for example, that numeric fields do, in fact, contain numeric data.

    4. Tests for missing data—to ensure that all critical fields contain nonzero or nonblank data.

    5. Sequence checks—to ensure that data is in the correct sequence.

  5. Other Tests

    1. Sign test

      IF identifier-1 IS {POSITIVE/NEGATIVE . . ./ZERO}

      Identifier-1 must have an S in its PIC clause if it is to store data with a negative value.

    2. Class Test

      IF identifier-1 IS {NUMERIC/ALPHABETIC} . ..

    3. Negated Conditionals

      1. (1) Any test can be preceded with a NOT to test the negative of a conditional.

      2. (2) IF NOT (A = B OR A = C) is the same as IF A NOT = B AND A NOT = C.

  6. Condition-Names

    1. Coded on the 88-level directly following the field to which it relates. For example,

      05 CODE-IN PIC X.

      88 OK-CODE VALUE '6'.

    2. A condition-name specifies a condition in the PROCEDURE DIVISION. For example,

      IF OK-CODE

      PERFORM 200-OK-RTN

      END-IF

KEY TERMS

Case structure

Class test

Coded field

Collating sequence

Compound conditional

Conditional statement

Condition-name

Data validation

Decimal data error

EVALUATE

Imperative statement

Limit test

Negated conditional

Range test

SET

Sign test

Simple condition

CHAPTER SELF-TEST

TRUE-OR-FALSE QUESTIONS

  • 1. In a compound conditional, statements surrounding the word AND are evaluated first.

  • 2. The IF statement may be terminated with the scope terminator END-IF or a period.

  • 3. The clause IF A is POSITIVE is the opposite of the clause IF A IS NEGATIVE, and the clause IF A IS NUMERIC is the opposite of the clause IF A IS ALPHABETIC.

  • 4. Numbers are considered greater than uppercase letters in the EBCDIC collating sequence.

  • 5. Fields being compared in an IF statement must always be the same size.

  • 6. On most computers, at least one space must precede and follow every symbol such as <, >, and =.

  • 7. Comparing numeric fields to nonnumeric literals can cause erroneous results.

  • 8. The class test is frequently used before an arithmetic operation to ensure that a field designated as numeric actually contains numeric data.

  • 9. The hierarchy of operations in a compound conditional can be overridden by parentheses.

  • 10. Using a conditional, ABC = ABC▵ = ▵ABC, where ▵ is a blank.

FILL-IN-THE BLANKS

  1. The hierarchy rule for evaluating compound conditionals states that conditions surrounding the word___are evaluated first followed by conditions surrounding the word___.

  2. A(n)___statement performs operations depending on the existence of some condition.

  3. A(n)___statement performs an operation regardless of any existing conditions.

  4. The___clause is used with the IF statement when two conditions exist.

  5. Using IS GREATER THAN OR EQUAL TO is the same as using the symbol

  6. The___collating sequence is used on IBM mainframe and midrange computers.

  7. A___conditional is a conditional in which an IF statement itself contains additional IF clauses.

  8. Two tests that can be used for reasonableness are the___test and___test.

  9. A___is a user-defined word defined in the DATA DIVISION that gives a name to a specific value that a data-field can assume.

  10. The___verb is used to implement the case structure.

GENERAL QUESTIONS

  1. What is wrong with the following statements?

    a.    IF A IS EQUAL TO '127'
        ADD A TO B
        END-IF
    b.    IF A EQUALS B
        MOVE 1 TO A
        END-IF
    c.    IF A IS LESS THEN B
        MOVE 2 TO CODE1
        END-IF
    d.    IF C = D
        MOVE 0 TO COUNTER.
        ELSE
        MOVE 100 TO COUNTER
        END-IF
  2. Write the following routine.

    GENERAL QUESTIONS
  3. Write a routine to move the smallest of three numbers A, B, and C to a field called PRINT-SMALL.

  4. What, if anything, is wrong with the following entries? Correct all errors.

    1. IF A = B OR IF A = C

      PERFORM 100-RTN-X

      END-IF

    2. IF B = 3 OR 4

      PERFORM 100-RTN-X

      END-IF

    3. IF C < A + B

      PERFORM 500-STEP-5

      END-IF

    4. IF A < 21 OR A = 21 AND A = 5 OR A > 5

      PERFORM 100-RTN-1

      END-IF

  5. Write a single statement to execute 500-PARAGRAPH-5 if A is between 3 and 13, exclusive of the end points. Write this two ways: (1) using an IF and (2) using an EVALUATE.

  6. Write a single statement to perform 300-PARAGRAPH-3 if the following conditions are all met; otherwise perform 200-PARAGRAPH-2: (a) A = B; (b) C = D; (c) E = F.

PRACTICE PROGRAM

The Sales Department would like you to write a program that reads the Customer Purchase File and prints a Purchase Discount Report. The problem definition is as follows:

Notes:

  1. If purchases exceed $500.00, allow 5 percent discount.

    If purchases are between $100.00 and $500.00, allow 2 percent discount.

    If purchases are less than $100.00, allow 1 percent discount.

  2. Discount amount = Purchases * Discount percent.

  3. Net amount = Purchases - Discount amount.

Systems flowchart

PRACTICE PROGRAM

Record description layout for customer purchase file

Field Description

Type

Size

COBOL Field-name

Customer Name

A

30

CP-CUSTOMER-NAME

Customer Purchases

P

7,2

CP-CUSTOMER-PURCHASES

Printer spacing chart for customer discount report

PRACTICE PROGRAM

Structured Pseudocode

MAIN-MODULE
START
PERFORM Initialization-Rtn
PERFORM Process-Record-Rtn UNTIL no more records
PERFORM Termination-Rtn
STOP
INITIALIZATION-RTN
Move 50 to Line Counter
Read a Record
PROCESS-RECORD-RTN
Clear output print area
Move Customer Number to output print area
Move Purchases to output print area
IF Sales Amount > 500.00
THEN
Discount Percent = .05
ELSE
IF Sales Amount >= 100
THEN
Discount Percent = .02
ELSE
IF Sales Amount < 100
THEN
Discount Percent = .01
ENDIF
END-IF
END-IF
Multiply Purchases by Discount Percent
Giving Discount Amount
Subtract Discount Amount from Sales Amount
Giving Net Amount
IF Line Counter >= 60
PERFORM Heading-Rtn
ENDIF
Write detail line
Add 1 to Line Counter
Read a record
HEADING-RTN
Print headings
Move 4 to Line Counter
TERMINATION-RTN
Move Total Purchases to output print area
Move Total Discount to output print area
Move Total Net Amount to output print area
Write Total Line

REVIEW QUESTIONS

GENERAL QUESTIONS

Code the following flowchart exercises in Questions 1–2 with a single statement:

GENERAL QUESTIONS
  1. Write a routine for determining FICA (Social Security tax) where a field called SALARY is read in as input. FICA is equal to 7.65 percent of SALARY up to $57,600. SALARY in excess of $57,600 and up to $135,000 is taxed at 1.45 percent for Medicare only.

  2. Find the largest of four numbers A, B, C, and D and place it in the field called HOLD-IT.

  3. Are the following groups of statements equivalent?

    a. IF A = B
    ADD C TO D
    ELSE
    ADD E TO F
    END-IF
    PERFORM 600-PRINT-RTN.
    IF A = B
    ADD C TO D
    PERFORM 600-PRINT-RTN
    ELSE
    ADD E TO F
    END-IF
    IF A IS POSITIVE
    PERFORM 600-RTN-X
    ELSE
    PERFORM 700-RTN-Y
    END-IF
    IF A IS NOT NEGATIVE
    PERFORM 600-RTN-X
    ELSE
    PERFORM 700-RTN-Y
    END-IF
    IF DISCOUNT IS GREATER THAN TOTAL
    PERFORM 500-ERROR-RTN
    ELSE
    SUBTRACT DISCOUNT FROM TOTAL
    END-IF
    IF TOTAL > DISCOUNT
    OR TOTAL = DISCOUNT
    CONTINUE
    ELSE
    PERFORM 500-ERROR-RTN
    END-IF
    SUBTRACT DISCOUNT FROM
    TOTAL.
  4. What, if anything, is wrong with the following statements?

    a.

    IF A IS NOT EQUAL TO B OR

     

    A IS NOT EQUAL TO C

     

    PERFORM 400-RTN-4

     

    END-IF

    b.

    IF A = 3 OR IF A = 4

     

    PERFORM 200-PRINT-RTN

     

    END-IF

  5. Doughnuts cost 25¢ each if a customer purchases fewer than a dozen. The doughnuts are 18¢ if 12 or more are purchased. Write a program excerpt using the EVALUATE verb to read in the number of doughnuts purchased and calculate the total price.

  6. Write a program excerpt to determine and print the concert ticket price for each purchase order. The ticket price depends on whether or not the request is for (1) a weekend and (2) orchestra seats. The following table shows the various prices for different combinations of requests.

    Weekend

    Yes

    Yes

    No

    No

    Orchestra

    Yes

    No

    Yes

    No

    Price

    $48

    $36

    $44

    $24

    Input is as follows.

    Field Description

    Type

    Size

    COBOL Fieldname

    Customer Number

    S

    5,0

    CR-CUSTOMER-NUMBER

    Customer Name

    A

    20

    CR-CUSTOMER-NAME

    Request Weekend

    S

    1,0

    CR-REQUEST-WEEKEND

    Request Orchestra

    S

    1,0

    CR-REQUEST-ORCHESTRA

    CR-REQUEST-WEEKEND

    CR-REQUEST-ORCHESTRA

    1 = Yes

    l = Yes

    0 = No

    0 = No

  7. Write a program excerpt to read in a file of exam grades and print the percent of students who received a grade of 85 or higher. Write this two ways: (1) using an IF and (2) using an EVALUATE.

  8. Write a program excerpt to determine whether a field called FIELDA, with a PIC 9(2), contains an odd or even number. (Hint: You may use the DIVIDE . . . REMAINDER for this, or some other technique.)

DEBUGGING EXERCISES

  1. Consider the following coding.

    DEBUGGING EXERCISES
    1. Under what conditions is a record written? (Hint: The punctuation is more critical here than the indentations.)

    2. Suppose AMOUNT1 = 5400 initially. A program interrupt will occur. Determine the reason.

    3. Correct this program excerpt so it will run properly.

  2. The following coding will result in a syntax error. Explain the reason.

    DEBUGGING EXERCISES
  3. Consider the following specifications.

    DEBUGGING EXERCISES
    1. The following coding will result in a syntax error. Explain the reason.

      DEBUGGING EXERCISES
    2. Consider the following.

      DEBUGGING EXERCISES

      Will a syntax error result? Explain your answer. Under what condition will 800-RTN-X be performed?

    3. Suppose that RECORD-1 was not initialized and you included the following coding in the PROCEDURE DIVISION.

    DEBUGGING EXERCISES

    Under what conditions, if any, will a syntax error occur? Under what conditions, if any, would a program interrupt occur?

PROGRAMMING ASSIGNMENTS

  1. Write a program for a rental car company that prints the amount owed by each customer. The amount owed depends on the miles driven, the number of days the car was rented, and the type of car rented. Toyotas rent at $26 per day and 18¢ per mile. Lincolns rent at $32 per day and 22¢ per mile. Cadillacs rent for $43 per day and 28¢ per mile. The first 100 miles are free, regardless of the car rented.

    Systems flowchart

    PROGRAMMING ASSIGNMENTS

    Record description layout for customer car rental file

    Field Description

    Type

    Size

    COBOL Field-name

    Customer Last Name

    A

    20

    CR-CUSTOMER-LAST-NAME

    First Initial

    A

    1

    CR-FIRST-INITIAL

    Type of Car

    S

    1,0

    CR-TYPE-OF-CAR

    Miles Driven

    P

    5,0

    CR-MILES-DRIVEN

    Number of Rental Days

    P

    3,0

    CR-NO-OF-RENTAL-DAYS

    Type of Car:

    1. Toyota

    2. Lincoln

    3. Cadillac

    Printer spacing chart for customer car rental report

    PROGRAMMING ASSIGNMENTS
  2. Write a program for the Electra Modeling Agency. The program will read the Model Master File and print a report containing the names of all who fit these specifications:

    1. Blond-haired, blue-eyed males over 6' tall and weighing between 185 and 200 pounds.

    2. Brown-haired, brown-eyed females between 5' 2" and 5' 6" and weighing between 110 and 125 pounds.

    All other combinations should not be printed. For each record printed, include the actual colors for eyes and hair.

    Record description layout for model master file

    Field Description

    Type

    Size

    COBOL Field-name

    Model Name

    A

    20

    MM-MODEL-NAME

    Weight (1bs.)

    P

    3,0

    MM-WEIGHT

    Height (inches)

    P

    2,0

    MM-HEIGHT

    Eye Color

    S

    1,0

    MM-EYE-COLOR

    Hair Color

    S

    1,0

    MM-HAIR COLOR

    Sex

    A

    1

    MM-SEX

    Codes:

    Eyes

    Hair

    Sex

    1 = Blue

    1 = Blond

    M = Male

    2 = Brown

    2 = Brown

    F = Female

    3 = Other

    3 = Other

     

    Printer spacing chart for model search report

    PROGRAMMING ASSIGNMENTS
  3. The Driver Accident File contains one record for each driver involved in an accident in the past year. Write a program to summarize these accident records to obtain the following information.

    1. The percentage of drivers under 25.

    2. The percentage of drivers who are female.

    3. The percentage of drivers from New York (State Code = NY).

    Record description layout for driver accident file

    Field Description

    Type

    Size

    COBOL Field-name

    Driver Number

    S

    4,0

    DA-DRIVER-NUMBER

    State Code

    A

    2

    DA-STATE-CODE

    Date of Birth

    S

    6,0

    DA-DATE-OF-BIRTH

    Sex

    A

    1

    DA-SEX

    Printer spacing chart for driver accident report

    PROGRAMMING ASSIGNMENTS
  4. Write a program to print out the patient name and diagnosis for each record from the Medical Diagnosis File.

    Notes:

    1. Assume that all patients have at least one symptom.

    2. If a patient has lung infection and temperature, the diagnosis is PNEUMONIA.

    3. If a patient has a combination of two or more symptoms (except the combination of lung infection and temperature), the diagnosis is COLD.

    4. If the patient has any single symptom, the diagnosis is OK.

    Record description layout for medical diagnosis file

    Field Description

    Type

    Size

    COBOL Field-name

    Patient Name

    A

    20

    MD-PATIENT-NAME

    Lung Infection

    S

    1,0

    MD-LUNG-INFECTION

    Temperature

    S

    1,0

    MD-TEMPERATURE

    Sniffles

    s

    1,0

    MD-SNIFFLES

    Sore Throat

    s

    1,0

    MD-SORE-THROAT

    Printer spacing chart for patient diagnosis report

    PROGRAMMING ASSIGNMENTS
  5. The International Cherry Machine (ICM) Company encourages its employees to enroll in college courses. It offers them a 70 percent rebate on the first $800 of tuition, a 50 percent rebate on the next $500, and a 30 percent rebate on the next $300. Write a program that reads the Employee Tuition File and prints the Tuition Rebate Report.

    Record description layout for employee tuition file

    Field Description

    Type

    Size

    COBOL Field-name

    Employee Name

    A

    20

    ET-EMPLOYEE-NAME

    Tuition

    P

    5,0

    ET-TUITION

    Printer spacing chart for employee tuition rebate report

    PROGRAMMING ASSIGNMENTS
  6. The LENDER Bank offers mortgages on homes valued up to $500,000. The required down payment is calculated as follows:

    4 percent of the first $60,000 borrowed
    8 percent of the next $30,000 borrowed
    10 percent of the rest.

    The amount borrowed cannot exceed 50 percent of the value of the house.

    Write a program to read the Bank Mortgage File and print the LENDER Bank Mortgage Report. If the mortgage amount requested is no more than 50 percent of the value of the house, the mortgage application will be approved. If the mortgage is approved, print the down payment amount required, and indicate that the mortgage is approved. If the mortgage is not approved, do not print the down payment, and indicate that the mortgage was not approved.

    Record description layout for bank mortgage file

    Field Description

    Type

    Size

    COBOL Field-name

    Customer Name

    A

    20

    BM-CUSTOMER-NAME

    Amount to Borrow

    P

    5,0

    BM-AMOUNT-TO-BORROW

    Value of House

    P

    7,0

    BM-VALUE-OF-HOUSE

    Printer spacing chart for Lender bank mortgage report

    PROGRAMMING ASSIGNMENTS
  7. The Pass-Em State College has a Student GPA File from which the administrator wants to print a Student GPA Summary Report. This report will be a summary showing the number of students in each class and the average student GPA by class within each of the different schools. The report also prints the total number of students in the college as well as the average GPA of the total student population.

Systems flowchart

PROGRAMMING ASSIGNMENTS

Record description layout for student GPA file

Field Description

Type

Size

COBOL Field-name

Student Number

S

9,0

SG-STUDENT-NUMBER

Student Name

A

20

SG-STUDENT-NAME

Class

S

1,0

SG-CLASS

School

S

1,0

SG-SCHOOL

GPA

P

3,2

SG-GPA

Credits Earned

P

3,0

SG-CREDITS-EARNED

Class Codes

1 = Freshman

2 = Sophomore

3 = Junior

4 = Senior

School Codes

1 = Business

2 = Liberal Arts

3 = Technology

Printer spacing chart for student GPA summary report

PROGRAMMING ASSIGNMENTS
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset