МатематикаМоя статистика
Тест по COBOL
100 вопросов в 20 темах (лёгкий — 30, средний — 50, сложный — 20). Выберите темы, уровень и количество вопросов — к каждому ответу есть объяснение.
Структура программы и дивизионы, PICTURE и USAGE, уровни и 88-условия, MOVE и арифметика, условия и PERFORM, таблицы, строки, файлы и FILE STATUS, подпрограммы, COPY, SORT, функции, редактирование, мейнфрейм (JCL, CICS, DB2) и современный COBOL. Вопросы на английском.
Все вопросы теста 100
Нажмите на вариант ответа, чтобы проверить себя, или «Показать ответ».
Program structure5
In which order must the four divisions of a COBOL program appear?
- IDENTIFICATION, ENVIRONMENT, DATA, PROCEDURE
- IDENTIFICATION, DATA, ENVIRONMENT, PROCEDURE
- ENVIRONMENT, IDENTIFICATION, DATA, PROCEDURE
- Any order, as long as PROCEDURE is last
The divisions have a fixed order: IDENTIFICATION names the program, ENVIRONMENT describes the machine and files, DATA declares storage and PROCEDURE holds the code. A common slip is to put DATA before ENVIRONMENT because declarations feel more basic, but the compiler rejects that order.
In fixed-format source, what is column 7 used for?
- Sequence numbers
- The start of Area A, where paragraph names begin
- The indicator area: * or / for a comment, - for a continuation line, D for a debugging line
- Nothing; it must always be blank
Columns 1-6 hold sequence numbers, column 7 is the indicator area, Area A is 8-11 and Area B is 12-72. An asterisk in column 7 turns the whole line into a comment, so a statement accidentally shifted one column to the left can silently disappear.
In fixed-format source, which of these must begin in Area A (columns 8-11)?
- A MOVE statement
- A paragraph name such as MAIN-PARA.
- A level-05 data item
- The ELSE of an IF statement
Division and section headers, paragraph names, FD/SD entries and the level numbers 01 and 77 start in Area A; statements belong in Area B (12-72). Level numbers 02-49 may start in either area, so a level-05 item is not forced into Area A.
A subprogram called with CALL executes STOP RUN. What happens?
- Control returns to the statement after the CALL in the calling program
- Only the subprogram is cancelled; the caller continues from its first statement
- It is a compile error: STOP RUN is allowed only in the main program
- The whole run unit ends, and control never returns to the caller
STOP RUN terminates the entire run unit, wherever it is executed. To return to the caller a subprogram should use GOBACK (or EXIT PROGRAM); GOBACK in the main program ends the run, which is why many shops use GOBACK everywhere.
In fixed-format source, a long literal runs from column 40 to column 78 of a line. What happens to the characters in columns 73-78?
- They are kept, because literals may extend to column 80
- The compiler wraps them onto the next line automatically
- They are ignored, because columns 73-80 are the program identification area
- They are treated as a comment only if column 7 contains *
In fixed format only columns 8-72 hold source text; columns 73-80 were reserved for card identification and are ignored. Text past column 72 is silently cut off, which leads to truncated literals or confusing syntax errors; long literals must be continued with a hyphen in column 7 of the next line.
Data division and PICTURE5
What does PIC X(5) describe?
- A numeric item with 5 digits
- An alphanumeric item of 5 characters
- An alphabetic item that accepts only letters
- A 5-byte binary number
X stands for any character, and (5) repeats it five times, so PIC X(5) is the same as PIC XXXXX. Letters only would be PIC A, and digits PIC 9.
How many bytes does this item occupy?
01 WS-PRICE PIC 9(3)V99 VALUE 123.45.- 6
- 3
- 7
- 5
With the default USAGE DISPLAY each digit takes one byte, and V only marks where the decimal point is assumed, so it takes no storage: 3 + 2 = 5 bytes. Counting V as a character (giving 6) is the classic mistake; an actual stored point would need the editing symbol '.'.
What value does WS-A hold after this statement?
01 WS-A PIC 9(3).
...
COMPUTE WS-A = 5 - 8- 3, because the item has no S and keeps only the absolute value
- -3
- 997
- 0, because a negative result is replaced by zero
Without S in the PICTURE the item is unsigned, and when a result is stored in it only its absolute value is kept. The minus sign is lost silently, so any field that can go negative (balances, differences) must be declared with PIC S9...
What kind of item is WS-AMT?
01 WS-AMT PIC 9(3).99.- A numeric item with an implied decimal point, usable in any arithmetic
- An invalid declaration: a PICTURE cannot contain a period
- A numeric-edited item of 6 characters: it can receive results, but cannot be an operand in arithmetic
- An alphanumeric item, so MOVE to it is not allowed
A period inside a PICTURE is an actual decimal-point character, which makes the item numeric-edited (meant for display or printing) and 6 bytes long. It can be the target of MOVE or GIVING, but not an operand of ADD or COMPUTE; for calculations use V, the implied point.
What numeric value does X hold after the MOVE?
01 X PIC 99PPP.
...
MOVE 12345 TO X- 12345
- 12000
- 45
- 12
Each P is a scaling position: an assumed zero digit that is not stored, so PIC 99PPP holds two stored digits worth thousands and ten-thousands. The MOVE aligns on the decimal point, keeps 1 and 2, and drops 345, so the value is 12000; reading it as 12 forgets the scaling.
USAGE and storage5
If no USAGE clause is written for an elementary item, what USAGE does it have?
- DISPLAY
- COMP (BINARY)
- COMP-3 (PACKED-DECIMAL)
- It depends on whether the PICTURE contains S
The default is USAGE DISPLAY: one character per byte, including numeric items where each digit is one byte. Numbers declared without USAGE are therefore stored as text digits, which is readable in a dump but slower to compute with than binary or packed data.
How does USAGE COMP-3 (PACKED-DECIMAL) store a number?
- As a two's-complement binary integer
- As a floating-point value
- As one character per digit, with the sign in the last byte
- Two decimal digits per byte, with the sign in the last half-byte
Packed decimal stores each digit in a 4-bit nibble and puts the sign (C positive, D negative, F unsigned on IBM) in the rightmost nibble. It keeps exact decimal values like DISPLAY but in about half the space; binary is COMP, and floating point is COMP-1/COMP-2.
How many bytes does this item occupy?
01 WS-TOTAL PIC S9(7) COMP-3.- 7
- 4
- 3
- 8
Packed decimal needs one nibble per digit plus one for the sign: (7 + 1) / 2 = 4 bytes, rounded up in general. Answering 3 forgets the sign nibble, and 7 confuses packed with DISPLAY; an odd digit count like 7 is the efficient choice because no nibble is wasted.
In IBM Enterprise COBOL, how many bytes does PIC S9(9) COMP (BINARY) occupy?
- 9
- 2
- 4
- 8
On IBM, binary items with 1-4 digits take a halfword (2 bytes), 5-9 digits a fullword (4 bytes) and 10-18 digits a doubleword (8 bytes). The size is implementation-defined: GnuCOBOL, for example, can use 1-byte fields for small PICTUREs depending on its binary-size setting, so never assume binary sizes when sharing records between compilers.
On IBM Enterprise COBOL compiled with TRUNC(STD), what is the key difference between PIC S9(4) COMP and PIC S9(4) COMP-5?
- COMP-5 values are limited by the binary field size, not by the PICTURE, so it can hold 32767
- COMP-5 is packed decimal, COMP is binary
- COMP-5 is always 8 bytes long
- COMP-5 cannot be signed
COMP-5 is native binary: its range is the full halfword (-32768..32767), while COMP under TRUNC(STD) is truncated to the 4 decimal digits of its PICTURE (max 9999). This matters when exchanging values with C or system APIs; the exact truncation rules for COMP are compiler-option dependent (TRUNC on IBM, binary-truncate in GnuCOBOL).
Level numbers5
What is a level-88 entry?
- A data item that is always 88 bytes long
- A constant that cannot be changed
- An item that renames part of a record
- A condition name: a named test for whether its parent item has one of the listed values
An 88 entry takes no storage; it names a condition on the item above it, e.g. 88 IS-ACTIVE VALUE 'A'. Then IF IS-ACTIVE reads better than IF STATUS = 'A'. Renaming part of a record is level 66, not 88.
Which statement about FILLER is true?
- FILLER items take no storage
- A FILLER item can be referenced by qualifying it, e.g. FILLER OF PRINT-LINE
- A FILLER item cannot be referenced by name in procedure statements
- FILLER can only be used at level 01
FILLER reserves real storage, often with a VALUE such as spaces or a fixed label in a print line, but it has no usable name, so no statement can refer to it, not even with qualification. Its contents can still change when the whole group is moved (INITIALIZE, by contrast, skips FILLER by default), which is how print-line labels are set up.
What does DISPLAY WS-MM print?
01 WS-DATE PIC X(8) VALUE '20261102'.
01 WS-DATE-R REDEFINES WS-DATE.
05 WS-YYYY PIC 9(4).
05 WS-MM PIC 99.
05 WS-DD PIC 99.
...
DISPLAY WS-MM- 02
- 11
- 26
- Nothing, because a REDEFINES item has no VALUE
REDEFINES gives the same 8 bytes a second layout: WS-YYYY is bytes 1-4 ('2026'), WS-MM bytes 5-6 ('11'), WS-DD bytes 7-8 ('02'). The redefining item shares the storage, so it sees the VALUE of the original item even though it cannot have its own VALUE clause.
What do A and B contain after the MOVE?
01 G.
05 A PIC 9(3).
05 B PIC 9(3).
...
MOVE 5 TO G- A = '5' followed by two spaces, B = spaces: a group move is alphanumeric
- A = 005, B = 000
- A = 000, B = 005
- A = 005, B = 005
A group item is always treated as alphanumeric, so MOVE 5 TO G copies the character '5' to the left and pads the rest of the 6 bytes with spaces, with no numeric conversion. A and B then contain invalid numeric data; to set them, move to the elementary items or use INITIALIZE.
Which statement about a level-66 RENAMES entry is correct?
- It may appear anywhere in WORKING-STORAGE and rename any item
- It allocates new storage initialised from the renamed items
- It may rename a level-01 record or a level-88 condition
- It must follow the last entry of its record and cannot rename level 01, 66, 77 or 88 items
RENAMES creates an alternative name, without new storage, for one item or a contiguous range of items (A THRU B) inside a record, and its entries are written right after the record's last data entry. It cannot rename 01, 66, 77 or 88 entries, nor items with OCCURS; REDEFINES is the tool for overlaying a whole record.
MOVE and data conversion5
What does WS-CODE contain after the MOVE?
01 WS-CODE PIC X(5).
...
MOVE 'ABC' TO WS-CODE- ' ABC' (right-justified)
- 'ABC ' (left-justified, padded with spaces)
- 'ABC00'
- 'ABC' followed by two low-values
Alphanumeric moves align on the left and fill unused positions on the right with spaces. Right justification happens only if the receiving item has the JUSTIFIED RIGHT clause, and zero padding applies to numeric moves, not alphanumeric ones.
What does WS-N contain after the MOVE?
01 WS-N PIC 9(3).
...
MOVE 12345 TO WS-N- 123
- 999
- 345
- A runtime error is raised
Numeric moves align on the decimal point, so the integer digits line up from the right and the extra high-order digits (12) are cut off. No error is raised, which is why a too-small numeric field can corrupt data silently; the left-truncation result 123 is what an alphanumeric move would give.
What value does WS-N hold after the MOVE?
01 WS-N PIC 9(4)V99.
...
MOVE 123.456 TO WS-N- 0123.45
- 0123.46
- 1234.56
- 0012.34
The value is aligned on the decimal point: the integer part gets a leading zero (0123) and the fraction keeps only two digits (.45). MOVE never rounds; excess low-order digits are simply truncated, so to get .46 you need COMPUTE ... ROUNDED.
What does WS-OUT contain after the MOVE?
01 WS-OUT PIC **,**9.99.
...
MOVE 45.5 TO WS-OUT- '00,045.50'
- '**,*45.50'
- '***45.50'
- '****45.50'
The asterisk is check-protection: leading zeros in the * positions become asterisks, and an insertion character such as the comma inside the suppressed area is replaced by an asterisk too. The edited item is always 9 characters long, so the result is ****45.50; keeping the comma is the common mistake.
Which fields of OUT-REC receive data from MOVE CORRESPONDING IN-REC TO OUT-REC?
01 IN-REC.
05 CUST-ID PIC 9(5).
05 NAME PIC X(20).
05 AMOUNT PIC 9(5)V99.
01 OUT-REC.
05 NAME PIC X(30).
05 FILLER PIC X(2).
05 CUST-ID PIC Z(4)9.
05 TOTAL PIC Z(5)9.99.- All four fields, matched by position
- NAME and CUST-ID only
- NAME only, because CUST-ID is in a different position
- None, because the two groups have different layouts
MOVE CORRESPONDING pairs items by name, not by position, so NAME and CUST-ID are moved (CUST-ID with numeric editing) regardless of order. AMOUNT has no partner named AMOUNT, and FILLER never takes part; a renamed field like TOTAL is silently skipped, a common source of missing data.
Arithmetic5
After ADD A TO B, which item holds the sum?
- A
- Both A and B
- B
- Neither; a GIVING phrase is required
Without GIVING, ADD ... TO stores the result in the item after TO, replacing its old value, while A is unchanged. Use ADD A TO B GIVING C or ADD A B GIVING C to keep both operands intact.
What are Q and R after this statement?
01 Q PIC 99.
01 R PIC 99.
...
DIVIDE 5 INTO 17 GIVING Q REMAINDER R- Q = 0, R = 5
- Q = 3, R = 5
- Q = 2, R = 3
- Q = 3, R = 2
DIVIDE 5 INTO 17 means 17 / 5, so the quotient is 3 and the remainder 17 - 3 * 5 = 2. The trap is reading INTO like BY: DIVIDE 17 BY 5 is the same division, while DIVIDE 17 INTO 5 would compute 5 / 17.
What value does X hold?
01 X PIC 9.
...
COMPUTE X ROUNDED = 10 / 4- 3
- 2
- 2.5
- 0
10 / 4 = 2.5, and ROUNDED with the default mode rounds a half away from zero, giving 3. Without ROUNDED the fraction would simply be truncated to 2; the item has no decimal places, so 2.5 cannot be stored.
What is displayed, and what is X afterwards?
01 X PIC 99 VALUE 95.
...
ADD 10 TO X
ON SIZE ERROR
DISPLAY 'OVER'
NOT ON SIZE ERROR
DISPLAY X
END-ADD- 05 is displayed; X = 05
- OVER is displayed; X stays 95
- OVER is displayed; X = 05
- OVER is displayed; X = 99
95 + 10 = 105 does not fit in PIC 99, so a size error occurs. When ON SIZE ERROR is coded, the receiving item is left unchanged and the imperative statement runs; the truncated value 05 is what you typically get only when the phrase is missing, and even then the standard does not define the result.
Which of these statements is invalid?
- MULTIPLY 10 BY A
- ADD A B GIVING C
- MULTIPLY A BY 10
- SUBTRACT A FROM B GIVING C
Without GIVING, the operand after BY receives the product, so it must be a data item, not a literal. MULTIPLY A BY 10 has nowhere to store the result; write MULTIPLY A BY 10 GIVING C or MULTIPLY 10 BY A instead.
Conditions5
For an item WS-IN PIC X(4), what does IF WS-IN IS NUMERIC test?
- That the value is greater than zero
- That the item was declared with PIC 9
- That at least one character is a digit
- That every character is a digit 0-9
The NUMERIC class test on an alphanumeric item is true only if all its characters are digits, so '12 4' or '12 ' fail because spaces are not digits. It is the usual way to validate input before moving it to a numeric field; testing for a value above zero is a sign condition (IS POSITIVE).
What does WS-STATUS contain after the SET?
01 WS-STATUS PIC X VALUE 'Y'.
88 ST-OK VALUE 'Y'.
88 ST-FAIL VALUE 'N'.
...
SET ST-FAIL TO TRUE- 'N'
- 'Y'
- 'T'
- '1'
SET condition-name TO TRUE moves the condition's (first) VALUE into its parent item, so WS-STATUS becomes 'N' and ST-OK becomes false. It saves you from repeating the literal 'N' in code; there is no Boolean 'T' or 1 stored anywhere.
Inside an IF, what is the difference between NEXT SENTENCE and CONTINUE?
- They are synonyms
- CONTINUE skips to the next loop iteration; NEXT SENTENCE ends the loop
- CONTINUE does nothing and execution goes on after END-IF; NEXT SENTENCE jumps past the next period
- NEXT SENTENCE does nothing; CONTINUE jumps to the next paragraph
CONTINUE is a no-op placeholder, so control flows to whatever follows the IF. NEXT SENTENCE transfers control to the statement after the next period, which may skip several statements written after END-IF in the same sentence; that hidden jump is why modern code prefers CONTINUE.
BAL is 100 when this code runs. What is BAL afterwards?
IF BAL < 0
DISPLAY 'NEGATIVE'.
MOVE 0 TO BAL
ADD 1 TO BAL.- 101
- 1
- 100
- 0
The period after DISPLAY 'NEGATIVE' ends the whole IF, so MOVE 0 TO BAL is no longer part of it and always runs, then ADD makes BAL 1. Indentation means nothing to the compiler; using END-IF and no periods inside paragraphs avoids this bug.
A = 5 and B = -1. What is displayed?
EVALUATE TRUE ALSO TRUE
WHEN A > 0 ALSO B > 0
DISPLAY 'PP'
WHEN A > 0 ALSO ANY
DISPLAY 'PX'
WHEN OTHER
DISPLAY 'OO'
END-EVALUATE- PP
- PP and then PX
- OO
- PX
Each WHEN must match both subjects: the first fails because B > 0 is false, the second matches since A > 0 is true and ANY matches anything. EVALUATE runs only the first matching WHEN and never falls through, unlike a C switch without break.
Loops and PERFORM5
What does PERFORM PARA-A THRU PARA-C do?
- Executes PARA-A, PARA-B and PARA-C in source order and then returns after the PERFORM
- Executes PARA-A and PARA-C only
- Executes PARA-A repeatedly until PARA-C is reached by a GO TO
- Jumps to PARA-A and never returns
THRU defines a range: control runs from the first statement of PARA-A to the end of PARA-C, including every paragraph physically between them, then returns. Inserting a new paragraph in the middle of such a range silently adds it to the PERFORM, a typical maintenance trap.
What does DISPLAY I print after the loop?
01 I PIC 99.
...
PERFORM VARYING I FROM 1 BY 1 UNTIL I > 3
DISPLAY 'X'
END-PERFORM
DISPLAY I- 03
- 04
- 01
- 00
The condition is tested before each pass: I = 1, 2, 3 run the body, then I is incremented to 4, the test I > 3 is true and the loop ends. The counter keeps the value that stopped the loop, one step past the last processed value.
How many times is the body executed?
MOVE 10 TO N
PERFORM WITH TEST AFTER UNTIL N > 5
ADD 1 TO N
END-PERFORM- 0
- 5
- It loops forever
- 1
WITH TEST AFTER checks the condition after each pass, so the body always runs at least once, like do-while. With the default WITH TEST BEFORE the condition N > 5 would already be true and the body would run zero times.
What is wrong with this loop?
01 I PIC 9.
...
PERFORM VARYING I FROM 1 BY 1 UNTIL I > 9
DISPLAY I
END-PERFORM- Nothing; it displays 1 to 9
- It displays 1 to 8 only
- I can never exceed 9: 9 + 1 does not fit in PIC 9, so in practice I wraps to 0 and the loop never ends
- It does not compile, because VARYING needs an index
A one-digit counter cannot hold 10, so the increment overflows and the high-order digit is lost, typically giving 0, and the condition I > 9 is never true. The fix is to give the counter at least one spare digit (PIC 99); the exact overflow result is not defined by the standard, but it is never 10.
In COBOL 2002 / GnuCOBOL, what does EXIT PERFORM CYCLE do inside an inline PERFORM?
- Ends the current iteration and goes on with the next one
- Leaves the inline PERFORM completely
- Leaves the current paragraph
- Restarts the loop from the first iteration
EXIT PERFORM CYCLE works like continue in C: it skips the rest of the body and moves to the next iteration (increment and test). Plain EXIT PERFORM is the break that leaves the loop, and EXIT PARAGRAPH leaves the current paragraph; both forms of EXIT PERFORM are only valid in inline PERFORMs.
Tables5
Given 05 WS-ITEM PIC X(10) OCCURS 20 TIMES, how do you refer to the first element?
- WS-ITEM(0)
- WS-ITEM[1]
- WS-ITEM(1)
- WS-ITEM.FIRST
COBOL subscripts are written in parentheses and start at 1, so the elements are WS-ITEM(1) to WS-ITEM(20). Programmers coming from C often use 0, which is out of range and may read storage before the table unless subscript checking is enabled.
A table is declared with INDEXED BY IDX. How do you make IDX point to the third element?
- MOVE 3 TO IDX
- SET IDX TO 3
- ADD 3 TO IDX
- COMPUTE IDX = 3
An index is not an ordinary numeric item (on IBM it holds a byte offset), so it is changed with SET: SET IDX TO 3, SET IDX UP BY 1. MOVE, ADD and COMPUTE cannot target an index name, which is the usual compile error when treating it like a subscript.
What does SEARCH ALL require of the table?
- Nothing beyond OCCURS; it works on any table
- A subscript item declared PIC 9(4) COMP
- A VARYING phrase naming the subscript
- An ASCENDING or DESCENDING KEY clause, an INDEXED BY index, and data actually sorted on that key
SEARCH ALL is a binary search, so the table must declare its key order (ASCENDING/DESCENDING KEY) and an index, and the data must really be in that order. The compiler cannot check the sorting: an unsorted table compiles fine but SEARCH ALL then misses entries that are present.
A serial SEARCH sometimes reports "not found" for values that are in the table. What is the likely bug?
SEARCH WS-ITEM
AT END
DISPLAY 'NOT FOUND'
WHEN WS-CODE(IDX) = WS-KEY
DISPLAY 'FOUND'
END-SEARCH- The index is not reset with SET IDX TO 1 before the SEARCH, so it starts from a leftover position
- SEARCH needs an ASCENDING KEY clause
- AT END must come after the WHEN clause
- WHEN must use a subscript, not an index
A serial SEARCH begins at the current value of the index and moves forward, so after a previous search the index may already be past the wanted element. Always SET IDX TO 1 before SEARCH; only SEARCH ALL sets the index itself.
WS-CNT is 4. What does FUNCTION LENGTH(WS-TBL) return?
01 WS-TBL.
05 WS-CNT PIC 99.
05 WS-ITEM PIC X(3)
OCCURS 1 TO 10 TIMES DEPENDING ON WS-CNT.- 32
- 30
- 14
- 12
With OCCURS DEPENDING ON, the current size of the group uses the current value of the object: 2 bytes for WS-CNT plus 4 * 3 bytes = 14. Storage may be reserved for the maximum (32 bytes), but MOVE, LENGTH and writes use the current length, so set WS-CNT before using the group.
Strings5
WS-NAME PIC X(8) contains 'ABCDEFGH'. What is WS-NAME(3:4)?
- 'CDEFGH'
- 'CDEF'
- 'DEFG'
- 'CD'
Reference modification is (start:length) with positions counted from 1, so (3:4) takes 4 characters starting at the third: CDEF. Reading it as (start:end) gives CD, and counting from 0 gives DEFG.
What does WS-OUT contain after the STRING?
01 WS-FIRST PIC X(10) VALUE 'JOHN'.
01 WS-LAST PIC X(10) VALUE 'SMITH'.
01 WS-OUT PIC X(20).
...
MOVE SPACES TO WS-OUT
STRING WS-FIRST DELIMITED BY SPACE
', ' DELIMITED BY SIZE
WS-LAST DELIMITED BY SPACE
INTO WS-OUT
END-STRING- 'JOHN , SMITH' followed by spaces
- 'JOHN,SMITH' followed by spaces
- 'JOHN SMITH' followed by spaces
- 'JOHN, SMITH' followed by spaces
DELIMITED BY SPACE copies each name up to its first space, dropping the trailing padding, while DELIMITED BY SIZE copies the whole literal ', ' including its space. STRING does not pad the rest of the target, which is why WS-OUT is cleared with MOVE SPACES first; otherwise old data would remain after the text.
What does DISPLAY WS-LEN print?
01 WS-X PIC X(10) VALUE ' AB C'.
01 WS-LEN PIC 99.
...
MOVE FUNCTION LENGTH(FUNCTION TRIM(WS-X)) TO WS-LEN
DISPLAY WS-LEN- 04
- 10
- 03
- 06
TRIM removes leading and trailing spaces, leaving 'AB C', whose length is 4; the space inside the text is kept. FUNCTION LENGTH(WS-X) alone would return 10, the declared size, because a PIC X field has no notion of a shorter actual content.
What does WS-B contain after the UNSTRING?
01 WS-IN PIC X(20) VALUE 'RED,GREEN,BLUE'.
01 WS-A PIC X(4).
01 WS-B PIC X(4).
01 WS-C PIC X(4).
...
UNSTRING WS-IN DELIMITED BY ','
INTO WS-A WS-B WS-C
END-UNSTRING- 'GREEN'
- 'REEN'
- 'GREE'
- Spaces, because the value is too long to fit
UNSTRING moves each piece like an alphanumeric MOVE, so 'GREEN' is left-aligned and truncated on the right to fit 4 characters. No error or overflow is raised for this: ON OVERFLOW concerns running out of receiving fields, not a piece that is too long, so field sizes must be checked by design.
What is WS-CNT after the INSPECT?
01 WS-S PIC X(6) VALUE 'BANANA'.
01 WS-CNT PIC 99 VALUE 0.
...
INSPECT WS-S TALLYING WS-CNT FOR ALL 'ANA'- 2
- 1
- 0
- 3
INSPECT scans left to right and, after a match, continues after the matched characters, so matches never overlap: 'ANA' at positions 2-4 is counted, and the scan resumes at position 5 where only 'NA' remains. Note also that TALLYING adds to the counter, so it must be initialised (here VALUE 0) before each INSPECT.
File handling5
Which file ORGANIZATION lets a program read a record directly by the value of a key field such as a customer number?
- ORGANIZATION IS LINE SEQUENTIAL
- ORGANIZATION IS INDEXED
- ORGANIZATION IS SEQUENTIAL
- ORGANIZATION IS RELATIVE with a RECORD KEY clause
An indexed file keeps an index on the RECORD KEY field, so a random READ can fetch the record whose key you moved into that field. A relative file is also accessed directly, but by record number (RELATIVE KEY), not by a data key, and it has no RECORD KEY clause.
A program must read records from a SEQUENTIAL file and change some of them in place with REWRITE. In which mode must the file be opened?
- OPEN INPUT
- OPEN OUTPUT
- OPEN EXTEND
- OPEN I-O
REWRITE needs a file opened I-O, because the program both reads and updates it; for a sequential file the REWRITE replaces the record returned by the last successful READ. OPEN OUTPUT is the dangerous trap: it creates the file anew and the existing records are lost.
What does OPEN EXTEND do for an existing sequential file?
- Positions the file after its last record, so new WRITEs are added at the end
- Clears the file and starts writing from the first record
- Opens the file for reading and writing at the current position
- Enlarges the record length so longer records can be written
EXTEND keeps all existing records and appends whatever is written after the open, which is how log and history files are usually built. Programmers who use OPEN OUTPUT for this by mistake wipe the file on every run.
The file CUST-FILE is described by an FD whose record is CUST-REC. Which pair of statements is written correctly?
- READ CUST-REC and WRITE CUST-FILE
- READ CUST-REC and WRITE CUST-REC
- READ CUST-FILE and WRITE CUST-REC
- READ CUST-FILE and WRITE CUST-FILE
COBOL reads a file but writes a record: READ names the file from the SELECT/FD, while WRITE (and REWRITE) names the record description. Mixing them up is a classic beginner compile error, easy to remember as 'read a file, write a record'.
An indexed file is opened with ACCESS MODE IS DYNAMIC. What happens after this START succeeds?
MOVE 'M' TO CUST-NAME-KEY
START CUST-FILE KEY IS NOT LESS THAN CUST-NAME-KEY
INVALID KEY DISPLAY 'NOTHING FROM M ON'
END-START- The first record with a key of 'M' or higher is read into the record area
- The file is only positioned there; a following READ ... NEXT returns that record
- All records with keys below 'M' are skipped and deleted from the file
- Nothing, because START is allowed only with ACCESS MODE IS RANDOM
START sets the file position (the key of reference) but transfers no data; you still need READ NEXT to get records from that point on. It works with SEQUENTIAL or DYNAMIC access, not RANDOM, and the typical bug is to use the record area right after START, expecting it to contain the found record.
File status and errors5
After a sequential READ, the FILE STATUS field contains '10'. What does it mean?
- The end of the file was reached and no record was read
- The record was read successfully and it is the tenth one
- The file was not found
- The program tried to read after the end-of-file condition had already been returned
Status 10 is the at-end condition, the same event that triggers the AT END phrase. Status 00 is a normal success, 35 means the file was not found on OPEN, and 46 is what you get if you keep reading after the 10 was already returned.
A program executes OPEN INPUT on a file that does not exist; the SELECT has no OPTIONAL clause. Which FILE STATUS is returned?
- 10
- 23
- 39
- 35
Status 35 means a non-optional file is not present when it is opened for INPUT, I-O or EXTEND. With SELECT OPTIONAL the open succeeds and the first READ simply hits end of file. 39 is a different problem: the file exists, but its attributes (record length, organization, key) conflict with the program's description.
CUST-FILE is indexed, opened INPUT with ACCESS MODE IS RANDOM, and has no record with key 'C999'. What happens?
MOVE 'C999' TO CUST-ID
READ CUST-FILE
INVALID KEY DISPLAY 'NO CUSTOMER'
NOT INVALID KEY DISPLAY CUST-NAME
END-READ- FILE STATUS is '10' and the program abends
- FILE STATUS is '22' and CUST-NAME of the previous record is displayed
- FILE STATUS is '23' and NO CUSTOMER is displayed
- FILE STATUS is '35' and NO CUSTOMER is displayed
A random read for a key that is not in the file is the invalid key condition 'record not found', status 23, and control goes to the INVALID KEY phrase. 22 is a duplicate key on WRITE, not a missing one; and since no record was read, the record area must not be trusted in that branch.
Where must a USE AFTER STANDARD ERROR PROCEDURE ON CUST-FILE section be written?
- In the FILE SECTION, right after the FD for CUST-FILE
- At the beginning of the PROCEDURE DIVISION, between DECLARATIVES and END DECLARATIVES
- Anywhere in the PROCEDURE DIVISION, as long as it is a separate paragraph
- In the ENVIRONMENT DIVISION, inside the SELECT clause
Declaratives must come first in the PROCEDURE DIVISION, each as a section headed by a USE statement, and the block ends with END DECLARATIVES followed by a normal section header. The runtime calls that section on an I/O error for the file when the statement itself has no applicable INVALID KEY or AT END phrase; you never PERFORM it into existence just by placing it elsewhere.
The first OPEN succeeds. What is in WS-STAT after the second OPEN?
SELECT IN-FILE ASSIGN TO 'in.dat'
ORGANIZATION IS LINE SEQUENTIAL
FILE STATUS IS WS-STAT.
...
OPEN INPUT IN-FILE
OPEN INPUT IN-FILE
DISPLAY WS-STAT- 41
- 42
- 00, because reopening simply rewinds the file
- 35
Opening a file that is already open fails with status 41, and the file stays open in its first mode. The mirror error is 42: CLOSE (or READ/WRITE) on a file that is not open. Without a FILE STATUS clause or declaratives, such errors usually terminate the run.
Subprograms5
A called subprogram executes STOP RUN. What happens?
- Control returns to the statement after the CALL, like GOBACK
- Only the subprogram is removed from memory, the caller continues
- The whole run unit ends, and the calling program never gets control back
- It is a compile error, because STOP RUN is allowed only in a main program
STOP RUN terminates the entire run unit no matter which program executes it. A subprogram should end with GOBACK or EXIT PROGRAM to return to its caller; GOBACK is popular because it works correctly in both main programs and subprograms.
The caller passes WS-QTY (value 10) with CALL 'CALC' USING BY CONTENT WS-QTY. CALC adds 5 to its LINKAGE item. What is WS-QTY in the caller after the call?
- 15
- 5
- Undefined, because BY CONTENT items cannot be changed
- 10
BY CONTENT passes a temporary copy, so the subprogram may modify its parameter but the caller's field stays unchanged. BY REFERENCE, the default, would let the change show up as 15 in the caller; forgetting which one is in effect is a frequent source of 'my value did not come back' bugs.
In a subprogram, where are the parameters listed in PROCEDURE DIVISION USING declared?
- In the LINKAGE SECTION, which describes storage owned by the caller
- In the WORKING-STORAGE SECTION with a VALUE clause for the default
- In the FILE SECTION as a pseudo-file
- Nowhere: parameters are accessed by position as USING-1, USING-2
LINKAGE SECTION items get no storage of their own; at run time they are mapped onto the caller's arguments. Their layouts must match the caller's fields byte for byte, and VALUE clauses there have no effect on the data (other than 88-level condition names).
COUNTER is called three times by the same main program, with no CANCEL in between. What does the third call display?
IDENTIFICATION DIVISION.
PROGRAM-ID. COUNTER.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-CALLS PIC 9(3) VALUE 0.
PROCEDURE DIVISION.
ADD 1 TO WS-CALLS
DISPLAY WS-CALLS
GOBACK.- 001
- 003
- 000
- 002
A subprogram's WORKING-STORAGE stays in its last-used state between calls, so the VALUE 0 applies only on the first call and the counter keeps growing. You get a fresh copy each time only if the program is declared IS INITIAL or the caller CANCELs it before calling again.
WS-PGM PIC X(8) contains 'PAYCALC' and the program executes CALL WS-PGM USING WS-DATA. When is the program PAYCALC located?
- At link time, because the linker reads the VALUE of WS-PGM
- At compile time, if WS-PGM has a VALUE clause
- Never: CALL accepts only a literal program name
- At run time, when the CALL executes: a CALL identifier is always a dynamic call
With CALL identifier the program name is only known when the statement runs, so it must be loaded dynamically. A CALL with a literal can be either static or dynamic depending on the compiler settings (for example IBM's DYNAM/NODYNAM option); people often assume the opposite and wonder why a changed module is not picked up.
Copybooks and compiler directives5
When does a COPY statement take effect?
- At run time, each time execution reaches the COPY statement
- At link time, when modules are bound together
- At compile time: the copybook text is inserted into the source before it is compiled
- At program load time, when the copybook is read from the library
COPY is pure text inclusion done by the compiler, so a change to a copybook has no effect until every program using it is recompiled. For the same reason you cannot name the copybook through a data item whose value is set at run time.
The copybook CUSTREC contains the lines below. Using COBOL 2002 rules (supported by GnuCOBOL), which names are produced by COPY CUSTREC REPLACING LEADING ==CUST== BY ==SUPP==. ?
05 CUST-ID PIC X(6).
05 CUST-NAME PIC X(30).- SUPP-ID and SUPP-NAME
- CUST-ID and CUST-NAME, because REPLACING matches only whole words
- SUPP-ID only, because only the first occurrence is replaced
- SUPPCUST-ID and SUPPCUST-NAME
The LEADING (and TRAILING) phrase, added in COBOL 2002, replaces the matching start of each text word, so the same layout can be copied with different prefixes. Plain REPLACING ==CUST== BY ==SUPP== would match only a word that is exactly CUST, which is the COBOL-85 limitation people still expect.
Why do many shops write record copybooks starting at level 05 instead of including the 01 level?
- Because a copybook may not contain level 01 entries
- Because 05-level items use less memory than 01-level items
- Because the compiler ignores level numbers inside copybooks
- So each program can place the layout under its own 01 group, for example once as an input and once as an output record
Without its own 01, the copybook becomes the subordinate part of whatever group the including program writes just before the COPY. If the copybook does start with 01, putting the COPY under another 01 does not nest it: it begins a separate record, a common level-number mix-up.
In GnuCOBOL, what does the directive >>SOURCE FORMAT IS FREE at the top of a source file do?
- Allows the program to run without a license
- Tells the compiler the following lines are free format, not bound to the fixed column areas
- Frees all WORKING-STORAGE memory when the program ends
- Turns off syntax checking for the rest of the file
Fixed format reserves columns 1-6 for sequence numbers, column 7 for the indicator and limits code to columns 8-72. The directive switches the reference format for the source that follows, which has the same effect as compiling with cobc -free; it is processed at compile time and changes nothing at run time.
What is the scope of a REPLACE statement such as REPLACE ==WS-MAX== BY ==100==. ?
- Only the next sentence of the program
- Only the text of the copybook named in the next COPY statement
- The source text that follows it, including text brought in by COPY, until another REPLACE or REPLACE OFF
- All occurrences of WS-MAX at run time, like a constant
REPLACE works on the source after COPY statements have been processed, from the point where it appears until it is cancelled or replaced. Unlike COPY ... REPLACING, which edits only the copied text, it can affect copybook text and the program's own lines alike, and like COPY it is purely a compile-time text substitution.
Sorting and merging5
Which entry describes the work file used by a SORT statement?
- An FD entry with the SORT clause
- An SD (sort-merge file description) entry
- A WORKING-STORAGE table with OCCURS
- An RD (report description) entry
The sort file is declared with SELECT and described in the FILE SECTION with SD, not FD. It is never opened, read or written directly: SORT and MERGE manage it, and procedures access it only through RELEASE and RETURN.
Inside an INPUT PROCEDURE of a SORT, which statement passes a record to the sort?
- RELEASE
- WRITE
- RETURN
- MOVE ... TO SORT-FILE
RELEASE sort-record hands a record to the sort, and in the OUTPUT PROCEDURE RETURN sort-file retrieves records in sorted order. Using WRITE on the SD record is the usual mistake, since it feels like writing to a file.
What is wrong with this code?
OPEN INPUT IN-FILE
OUTPUT OUT-FILE
SORT SORT-WORK
ON ASCENDING KEY SW-CUST-ID
USING IN-FILE
GIVING OUT-FILE
CLOSE IN-FILE OUT-FILE- ASCENDING KEY must name a field of IN-FILE, not of the SD record
- GIVING requires an OUTPUT PROCEDURE as well
- Nothing, this is the required pattern for USING/GIVING
- The USING and GIVING files must not be open when SORT runs: SORT opens and closes them itself
With USING and GIVING the SORT statement does the OPEN, READ, WRITE and CLOSE of those files, so they must be closed when it starts; opening them first causes an error at run time. The keys, by contrast, are fields of the SD record, which is correct here.
What does WITH DUPLICATES IN ORDER guarantee in a SORT statement?
- Records with duplicate keys are removed
- The sort fails if two records have the same key
- Records with equal keys come out in the same order in which they went in
- Duplicate keys are sorted by the rest of the record
The phrase makes the sort stable for equal keys. Without it, the order of records with equal keys is not defined by the standard, even if a given sort product happens to keep it; it never removes duplicates, which needs a separate step.
Which statement about MERGE is true?
- Its input files must already be ordered on the merge keys, and it allows an OUTPUT PROCEDURE but not an INPUT PROCEDURE
- It sorts each input file first, so the inputs may be in any order
- It allows an INPUT PROCEDURE but requires GIVING for output
- It can merge only two files at a time
MERGE combines files that are each already in key order, so it reads them directly through USING; there is no INPUT PROCEDURE. If an input is out of order the result is wrong or an error, which is why people sometimes switch to SORT USING several files instead.
Intrinsic functions5
Without a REPOSITORY paragraph, which statement correctly converts WS-NAME to upper case?
- MOVE UPPER-CASE(WS-NAME) TO WS-OUT
- MOVE FUNCTION UPPER-CASE(WS-NAME) TO WS-OUT
- CALL 'UPPER-CASE' USING WS-NAME WS-OUT
- COMPUTE WS-OUT = UPPER(WS-NAME)
Intrinsic functions are referenced with the FUNCTION keyword and can be used where an identifier of their type is allowed. Without that keyword the compiler sees UPPER-CASE as an undeclared data name; only REPOSITORY. FUNCTION ALL INTRINSIC lets you omit it.
What do the first 8 characters of FUNCTION CURRENT-DATE contain?
- The time as HHMMSSss
- The date as YYMMDD followed by two spaces
- The date as YYYYMMDD
- The date as DDMMYYYY
CURRENT-DATE returns 21 characters: YYYYMMDD, then HHMMSS and hundredths, then the offset from UTC as a sign and HHMM. Unlike the old ACCEPT FROM DATE it always has a four-digit year, so a reference modification like (1:8) is a common way to get today's date.
What value does FUNCTION LENGTH(WS-NAME) return?
01 WS-NAME PIC X(20) VALUE 'BOB'.- 3
- 17
- 0
- 20
LENGTH returns the size of the data item in character positions, not the length of its meaningful content, and the trailing spaces are part of the item. To get 3 you need something like FUNCTION LENGTH(FUNCTION TRIM(WS-NAME)).
Which of these strings cannot be converted with FUNCTION NUMVAL and needs FUNCTION NUMVAL-C instead (default currency sign and decimal point)?
- '$1,234.50'
- ' -12.50'
- '12.50-'
- ' 7 '
NUMVAL accepts digits with an optional decimal point, leading or trailing sign (also CR or DB) and surrounding spaces. A currency symbol and comma group separators are only allowed by NUMVAL-C; passing such text to NUMVAL is invalid input, a common bug when parsing amounts from reports or CSV files.
WS-R is PIC S9. What does it contain after this statement?
COMPUTE WS-R = FUNCTION MOD(-7, 3)- -1
- 2
- 1
- -2
MOD is defined as arg1 - arg2 * FUNCTION INTEGER(arg1 / arg2), and INTEGER rounds down to the greatest integer not above the value: INTEGER(-2.33) is -3, so -7 - 3 * (-3) = 2. FUNCTION REM(-7, 3) would give -1, which is the answer people coming from C expect.
Editing and reports5
WS-OUT is PIC ZZZ9. What does it contain after MOVE 42 TO WS-OUT?
- '0042'
- '42 '
- 'ZZ42'
- ' 42'
Z replaces leading zeros with spaces, and the number stays right-aligned on the implied decimal point. The final 9 forces one digit to be printed, so a zero value shows as ' 0' rather than all spaces.
WS-AMT is PIC 9(5)V99 VALUE 1234.50 and WS-OUT is PIC $$$,$$9.99. What is in WS-OUT after MOVE WS-AMT TO WS-OUT?
- '$01,234.50'
- '$ 1,234.50'
- ' $1,234.50'
- '$$$1,234.50'
A floating string of $ signs prints a single $ immediately to the left of the first non-zero digit; the leftmost $ only reserves room for the sign symbol, and unused positions become spaces. The comma is kept because there are significant digits on its left, while leading zeros are never printed in a floating string.
WS-AMT is PIC S999 VALUE +25 and WS-OUT is PIC ZZ9CR. What is in WS-OUT after MOVE WS-AMT TO WS-OUT?
- ' 25CR'
- ' 25 '
- ' 25+ '
- '025DB'
CR (and DB) appear only when the value is negative; for a positive or zero value both positions become spaces. The trap is to read CR as 'always printed', so a -25 would be ' 25CR' and +25 just ' 25' followed by two blanks.
WS-OUT is PIC ***9.99. What does it contain after MOVE 12.5 TO WS-OUT?
- '**12.50'
- ' 12.50'
- '0012.50'
- '***12.5'
The asterisk is check protection: it suppresses leading zeros like Z, but fills them with * so nobody can write digits in front of the amount on a printed cheque. The decimal point still aligns the value, so the fraction is .50, not .5 shifted.
In what format does ACCEPT WS-DATE FROM DATE return the date?
- YYYYMMDD
- DDMMYY
- YYMMDD
- YYDDD (Julian)
Plain FROM DATE gives a six-digit YYMMDD value with a two-digit year, one of the classic Y2K problems. Use ACCEPT ... FROM DATE YYYYMMDD (COBOL 2002, IBM, GnuCOBOL) or FUNCTION CURRENT-DATE to get the century; YYDDD is what FROM DAY returns.
Mainframe environment5
In z/OS JCL, which statement names the program a job step runs?
- //STEP1 DD PGM=PAYROLL
- //PAYJOB JOB PGM=PAYROLL
- //SYSOUT RUN PAYROLL
- //STEP1 EXEC PGM=PAYROLL
JOB starts the job and gives accounting and class information, EXEC starts a step and names the program (or a procedure), and DD statements connect the program's files to data sets. The DD name must match the name in the program's ASSIGN clause, a frequent cause of 'file not found' at run time.
What does DISP=(NEW,CATLG,DELETE) on a DD statement mean?
- Create the data set; catalog it if the step ends normally; delete it if the step abends
- Delete any old version, create a new one, and catalog it in all cases
- Open the data set for update, then catalog and delete it at job end
- Create the data set only if it is already cataloged
The three subparameters are the status at the start, the normal disposition and the abnormal disposition. Using NEW for a data set name that already exists in the catalog makes the job fail, so reruns often need a cleanup step or a different DISP.
A file sorted ascending on the mainframe (EBCDIC) contains keys starting with digits, upper-case and lower-case letters. In which order do they appear?
- Digits, upper case, lower case
- Lower case, upper case, digits
- Upper case, lower case, digits
- Digits, lower case, upper case
In EBCDIC lower-case letters (X'81'...) come before upper-case (X'C1'...) and digits (X'F0'...) come last, while ASCII puts digits first, then upper case, then lower case. Programs and files moved between platforms therefore can produce different sort orders and break logic that assumes key sequence.
No row in CUST has ID equal to WS-ID. What is SQLCODE after this statement?
EXEC SQL
SELECT NAME INTO :WS-NAME
FROM CUST
WHERE ID = :WS-ID
END-EXEC- 0, and WS-NAME is set to spaces
- -100
- +100
- -811
In DB2, SQLCODE 0 is success, +100 means no row was found (also the end of a cursor on FETCH) and negative values are errors. -811 is the opposite case, a singleton SELECT that found more than one row; the host variables, marked by the colon, are not filled when +100 is returned.
What makes a CICS transaction pseudo-conversational?
- It keeps the program in memory while the user types, waiting on EXEC CICS RECEIVE
- It runs as a batch job submitted from the terminal
- It uses DB2 instead of VSAM files
- After sending a screen it ends with EXEC CICS RETURN TRANSID(...) COMMAREA(...), and the next input starts it again with the saved state
Instead of holding storage and locks while a user thinks, the program returns to CICS and names the transaction to run when the user presses a key, passing its state in the COMMAREA (or a container). The trap is to keep data in WORKING-STORAGE between screens: each new task gets a fresh copy.
Modern COBOL5
Which body designed the original COBOL specification in 1959?
- ANSI X3.23
- CODASYL, the Conference on Data Systems Languages
- IBM's System/360 design team
- ISO/IEC JTC 1
COBOL came from the CODASYL committee in 1959, drawing heavily on Grace Hopper's FLOW-MATIC. ANSI standardized it later (COBOL-68, -74, -85), and ISO/IEC took over with COBOL 2002 and 2014; System/360 appeared only in 1964.
Which GnuCOBOL command compiles hello.cob into a standalone executable?
- cobc -x hello.cob
- cobc hello.cob
- cobc -m hello.cob
- cobcrun hello.cob
-x builds an executable with a main entry point. Without it cobc builds a dynamically loadable module by default (the same as -m), which you run with cobcrun hello, not with ./hello; cobcrun never compiles source.
Since COBOL 2002, which character sequence starts a comment that can follow code on the same line?
- //
- --
- *>
- An asterisk in column 7
The floating comment indicator *> turns the rest of the line into a comment, in fixed and free format. An asterisk in column 7 is the older full-line comment of fixed format and cannot be used after code on the same line.
What does the JSON GENERATE statement (IBM Enterprise COBOL 6) do?
- Generates a COBOL copybook from a JSON schema at compile time
- Parses JSON text into a group item
- Sends an HTTP request with a JSON body
- Converts a group data item into JSON text, using data names as the JSON keys
JSON GENERATE builds JSON from the structure and values of a group item into a receiving field and can report the length produced (COUNT IN). The opposite direction, JSON text to data items, is JSON PARSE; neither does any networking.
A GnuCOBOL program calls a C function that expects a char * string: CALL 'greet' USING BY REFERENCE WS-NAME, where WS-NAME is PIC X(20) VALUE 'ANN'. What is the risk?
- None: COBOL adds a terminating NUL to every BY REFERENCE alphanumeric item
- C receives a pointer to 20 bytes padded with spaces and no terminating NUL, so it may read past the field
- C receives the value 'ANN' by value and cannot read it as a pointer
- The call fails at compile time because C functions need BY VALUE
BY REFERENCE passes the address of the field, which in C is a char pointer, but COBOL strings are fixed-length and space-padded without a NUL terminator. Add one yourself, for example by passing a field that ends with X'00' or using a Z'...' literal, and remember the trailing spaces are part of the data.
Common pitfalls5
A mainframe COBOL batch job abends with S0C7. What is the usual cause?
- Arithmetic on a packed or zoned decimal field that contains invalid, non-numeric data
- A file was not found on OPEN
- The program ran out of CPU time
- Division by zero in a floating-point field
S0C7 is a data exception: the hardware found bad digits or sign in a decimal field, typically spaces or garbage left in an uninitialized field or read from a file with a mismatched layout. Checking input with an IF ... IS NUMERIC class test before computing prevents most of them.
WS-A contains 5. What is displayed?
IF WS-A > 10
DISPLAY 'BIG'
MOVE 'Y' TO WS-FLAG.
DISPLAY 'FLAG SET'.- Nothing
- BIG and FLAG SET
- BIG
- FLAG SET
The period after the MOVE ends the whole IF sentence, so DISPLAY 'FLAG SET' runs unconditionally despite the indentation. Use END-IF and avoid periods inside procedure logic; a stray period is one of the most common and hard-to-see COBOL bugs.
What do WS-CODE and WS-QTY contain after INITIALIZE WS-REC?
01 WS-REC.
05 WS-CODE PIC X(3) VALUE 'ABC'.
05 WS-QTY PIC 9(3) VALUE 7.
...
MOVE 'XYZ' TO WS-CODE
MOVE 99 TO WS-QTY
INITIALIZE WS-REC- 'ABC' and 007
- 'XYZ' and 000
- Spaces and 000
- Low-values in both fields
Plain INITIALIZE sets alphanumeric items to spaces and numeric items to zero; it does not restore VALUE clauses, which only set the initial contents when the program starts. COBOL 2002 added INITIALIZE ... TO VALUE for that, but people often assume the plain form already does it.
What is in D-NUM after MOVE SRC TO DST?
01 SRC.
05 S-NUM PIC 9(3) VALUE 42.
01 DST.
05 D-NUM PIC 9(5).
...
MOVE SRC TO DST- 00042
- '042' followed by two spaces
- ' 042'
- Nothing: a compile error, because group sizes differ
A move between group items is an alphanumeric move: bytes are copied from the left and the rest is filled with spaces, with no numeric conversion or alignment. D-NUM now holds invalid numeric data, and using it in arithmetic can abend with S0C7; move the elementary fields instead.
A table has OCCURS 10 TIMES and the program sets an element with subscript 11. With default compiler options (no IBM SSRANGE, no GnuCOBOL -debug or bound checks), what usually happens?
- No check is made: the program writes into the storage after the table, silently corrupting other data
- The table grows to 11 elements automatically
- The subscript wraps around to element 1
- The statement is skipped and a warning is written to SYSOUT
COBOL tables are fixed-size and subscripts are not checked by default for speed, so an out-of-range index overwrites neighbouring fields and the failure shows up far away. Turn on SSRANGE (IBM) or the run-time checks of your compiler (for example cobc -debug in GnuCOBOL) when testing to catch it at the faulty statement.
Как проходить тест
- Выберите темы и уровень — лёгкий уровень проверяет определения и задачи в одно действие, средний — стандартные вычисления, сложный — многошаговые задачи и теорию.
- Отвечайте касанием или с клавиатуры: 1–4 или A–D, Enter — следующий вопрос.
- Читайте объяснения — после ошибки разбор открывается сразу, после верного ответа его можно раскрыть кнопкой «Почему».
- Работайте над ошибками — «Повторить ошибки» в конце теста или режим «Только мои ошибки» потом: ответы запоминаются в этом браузере.
Незавершённый тест сохраняется — после перезагрузки страницы можно продолжить с того же вопроса.
Темы теста
- Program structure 5
- Data division and PICTURE 5
- USAGE and storage 5
- Level numbers 5
- MOVE and data conversion 5
- Arithmetic 5
- Conditions 5
- Loops and PERFORM 5
- Tables 5
- Strings 5
- File handling 5
- File status and errors 5
- Subprograms 5
- Copybooks and compiler directives 5
- Sorting and merging 5
- Intrinsic functions 5
- Editing and reports 5
- Mainframe environment 5
- Modern COBOL 5
- Common pitfalls 5
Другие тесты
Тест по линейной алгебре160 вопросовТест по дифференциальным уравнениям130 вопросовТест по теории вероятностей и статистике130 вопросовТест по SAS100 вопросовТест по языку R100 вопросовТест по LaTeX100 вопросовТест по системам компьютерной алгебры100 вопросовТест по Fortran120 вопросовТест по языку C100 вопросовТест по MATLAB100 вопросовТест по PowerBuilder100 вопросовТест по UNIX100 вопросов
