MainframeMaster
MainframeMaster

COBOL Tutorial

Progress0 of 0 lessons

COBOL TALLYING

TALLYING is a clause used with INSPECT, STRING, and UNSTRING statements to count occurrences of characters, strings, or patterns in data. TALLYING counts how many times specified characters appear and stores the count in a numeric variable. It's useful for data validation, parsing, and analyzing string content.

Using TALLYING with INSPECT

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
WORKING-STORAGE SECTION. 01 INPUT-FIELD PIC X(50). 01 CHAR-COUNT PIC 9(4) VALUE 0. 01 SPACE-COUNT PIC 9(4) VALUE 0. PROCEDURE DIVISION. COUNT-CHARACTERS. MOVE 'HELLO WORLD' TO INPUT-FIELD *> Count all characters INSPECT INPUT-FIELD TALLYING CHAR-COUNT FOR CHARACTERS *> CHAR-COUNT = 11 *> Count specific character MOVE 0 TO SPACE-COUNT INSPECT INPUT-FIELD TALLYING SPACE-COUNT FOR ALL ' ' *> SPACE-COUNT = 1 DISPLAY 'Total characters: ' CHAR-COUNT DISPLAY 'Spaces: ' SPACE-COUNT STOP RUN.

Counting Multiple Characters

cobol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
WORKING-STORAGE SECTION. 01 TEXT-FIELD PIC X(100). 01 A-COUNT PIC 9(4) VALUE 0. 01 E-COUNT PIC 9(4) VALUE 0. PROCEDURE DIVISION. COUNT-MULTIPLE. MOVE 'COBOL PROGRAMMING' TO TEXT-FIELD *> Count multiple characters INSPECT TEXT-FIELD TALLYING A-COUNT FOR ALL 'A' E-COUNT FOR ALL 'E' DISPLAY 'A count: ' A-COUNT DISPLAY 'E count: ' E-COUNT STOP RUN.

Best Practices

  • Always initialize counters to zero
  • Use meaningful counter names
  • Check counts after TALLYING operations

Test Your Knowledge

1. What does TALLYING do?

  • Adds numbers
  • Counts occurrences of characters or patterns
  • Sorts data
  • Formats output

2. What must you do before using TALLYING?

  • Open a file
  • Initialize the counter to zero
  • Define a string
  • Nothing special

3. Which statement uses TALLYING?

  • MOVE
  • INSPECT
  • PERFORM
  • IF

Related Concepts

Related Pages