Scrabble Score in Cobol: Complete Solution & Deep Dive Guide

Tabs labeled

Mastering String Manipulation in Cobol: The Complete Scrabble Score Guide

Calculating a Scrabble score in Cobol involves iterating through an input word, character by character. Each character is then evaluated against predefined letter values using conditional logic, such as an EVALUATE statement, to accumulate a total score. This process effectively demonstrates string manipulation and conditional processing in Cobol.

You’ve probably heard the whispers: Cobol is a relic, a language of the past, confined to dusty mainframes processing monotonous batch jobs. Many developers, especially those fluent in Python or JavaScript, might see a task like parsing a word and calculating a score as trivial in their language of choice, but potentially a nightmare of verbosity and arcane syntax in Cobol. This perception creates a barrier, making even fundamental string manipulation seem like an insurmountable challenge.

But what if we told you that the very logic that powers global finance, insurance, and logistics systems can be elegantly applied to a fun, familiar problem? This guide shatters that misconception. We will walk you through building a complete Scrabble score calculator from scratch in Cobol. You won't just get a solution; you'll gain a deep understanding of core Cobol principles like data structures, iterative processing with PERFORM VARYING, powerful conditional logic with EVALUATE, and character manipulation using INSPECT. This isn't just about solving a puzzle; it's about unlocking the true potential of a language that remains a cornerstone of modern enterprise computing.


What is the Scrabble Score Challenge?

The objective is straightforward and based on the classic board game, Scrabble. Your program must accept a word as input and calculate its total score based on a fixed value assigned to each letter of the alphabet. The challenge lies not in the complexity of the math, which is simple addition, but in efficiently processing the input string and mapping each character to its correct score.

This task is a perfect case study for learning string handling in a structured, procedural language like Cobol. It forces you to think about data representation, looping, and conditional logic in a very deliberate way.

The Official Letter Values

For this challenge, as defined in the kodikra.com learning curriculum, we will use the standard English letter values. Your program must correctly implement the following scoring table:

Letter(s) Value
A, E, I, O, U, L, N, R, S, T 1
D, G 2
B, C, M, P 3
F, H, V, W, Y 4
K 5
J, X 8
Q, Z 10

An important rule is that the scoring should be case-insensitive. The word "Cobol" should yield the same score as "cobol" or "COBOL". This adds a small but crucial data normalization step to our program logic.


Why Use Cobol for This Task?

At first glance, using Cobol for a Scrabble scorer might seem like using a sledgehammer to crack a nut. Modern languages offer built-in dictionaries or hash maps that could solve this in a few lines. However, choosing Cobol for this kodikra module is a deliberate educational strategy that provides significant benefits.

  • Mastering Fundamentals: Cobol forces you to manage memory and data structures explicitly. You can't just declare a dynamic dictionary. This builds a strong foundation in understanding how data is structured and processed at a lower level.
  • Real-World Analogy: In the real world of mainframe applications, Cobol programs constantly parse, validate, and transform data fields from files and databases. A program might read a product code, parse its components, and look up values in a data table. Our Scrabble scorer perfectly mimics this common workflow.
  • Understanding Verbosity as Clarity: Cobol's "verbose" nature is often a feature, not a bug. The code is self-documenting. A well-written Cobol program can be understood by a business analyst, which is invaluable in enterprise environments. This exercise teaches you to write that kind of clear, maintainable code.
  • Learning Powerful Verbs: You will become intimately familiar with powerful Cobol verbs like INSPECT, EVALUATE, and PERFORM VARYING, which are the bread and butter of daily Cobol programming.

By solving this problem, you are not just learning to score a word game; you are learning the techniques required to process financial transactions, validate insurance claims, or manage logistics data on systems that demand absolute precision and reliability.


How to Structure the Cobol Program: The Complete Solution

A Cobol program is highly structured, divided into four main parts called DIVISIONS. Each division serves a distinct purpose, creating a clear and organized source file. We will build our program, `scrabble.cbl`, following this mandatory structure.

The Four Divisions of a Cobol Program

  1. IDENTIFICATION DIVISION: The metadata section. It names the program and can include author, date, and other comments.
  2. ENVIRONMENT DIVISION: Describes the computer environment where the program will be compiled and run. For our simple case, it's minimal.
  3. DATA DIVISION: This is where all the magic starts. We declare every single variable, constant, and file structure the program will use. Memory is explicitly defined here.
  4. PROCEDURE DIVISION: Contains the executable code—the logic, loops, and calculations that perform the work.

The Full Cobol Code

Here is the complete, well-commented source code for our Scrabble Score calculator. We will dissect it piece by piece in the following sections.


       IDENTIFICATION DIVISION.
       PROGRAM-ID. ScrabbleScore.
       AUTHOR. Kodikra.
      * This program calculates the Scrabble score for a given word.
      * It demonstrates string iteration, data normalization, and
      * the EVALUATE statement in COBOL.

       ENVIRONMENT DIVISION.
       CONFIGURATION SECTION.
       SOURCE-COMPUTER. GnuCOBOL.
       OBJECT-COMPUTER. GnuCOBOL.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
      * Input and processing variables
       01 WS-INPUT-WORD           PIC X(50) VALUE SPACES.
       01 WS-UPPER-WORD           PIC X(50).
       01 WS-WORD-LENGTH          PIC 99    VALUE 0.
       01 WS-INDEX                PIC 99.

      * Score calculation variables
       01 WS-TOTAL-SCORE          PIC 9(4)  VALUE 0.
       01 WS-LETTER-SCORE         PIC 99    VALUE 0.
       01 WS-CURRENT-CHAR         PIC X.

      * Constants for character conversion
       78 LOWERCASE               VALUE "abcdefghijklmnopqrstuvwxyz".
       78 UPPERCASE               VALUE "ABCDEFGHIJKLMNOPQRSTUVWXYZ".

       PROCEDURE DIVISION.
       MAIN-LOGIC.
      * Accept the word from the user (or system input)
           DISPLAY "Enter a word to score (max 50 chars): "
               WITH NO ADVANCING.
           ACCEPT WS-INPUT-WORD.

      * Handle empty input gracefully
           IF WS-INPUT-WORD = SPACES
               MOVE 0 TO WS-TOTAL-SCORE
               PERFORM DISPLAY-RESULT
               PERFORM END-PROGRAM
           END-IF.

      * Normalize the input to uppercase for consistent scoring
           MOVE WS-INPUT-WORD TO WS-UPPER-WORD.
           INSPECT WS-UPPER-WORD CONVERTING LOWERCASE TO UPPERCASE.

      * Calculate the effective length of the word (ignoring trailing spaces)
           INSPECT FUNCTION REVERSE(WS-UPPER-WORD)
               TALLYING WS-WORD-LENGTH FOR LEADING SPACES.
           COMPUTE WS-WORD-LENGTH = LENGTH OF WS-UPPER-WORD - WS-WORD-LENGTH.

      * Main loop to iterate through each character of the word
           PERFORM VARYING WS-INDEX FROM 1 BY 1
               UNTIL WS-INDEX > WS-WORD-LENGTH

      * Isolate the current character
               MOVE WS-UPPER-WORD(WS-INDEX : 1) TO WS-CURRENT-CHAR

      * Calculate the score for the current character
               PERFORM CALCULATE-LETTER-SCORE

      * Add the letter's score to the total
               ADD WS-LETTER-SCORE TO WS-TOTAL-SCORE
           END-PERFORM.

      * Display the final result
           PERFORM DISPLAY-RESULT.

      * End the program
           PERFORM END-PROGRAM.

       CALCULATE-LETTER-SCORE.
      * This paragraph uses the EVALUATE statement, which is similar
      * to a switch/case structure in other languages. It's highly
      * readable for multi-way branching.
           MOVE 0 TO WS-LETTER-SCORE.
           EVALUATE WS-CURRENT-CHAR
               WHEN 'A'
               WHEN 'E'
               WHEN 'I'
               WHEN 'O'
               WHEN 'U'
               WHEN 'L'
               WHEN 'N'
               WHEN 'R'
               WHEN 'S'
               WHEN 'T'
                   MOVE 1 TO WS-LETTER-SCORE
               WHEN 'D'
               WHEN 'G'
                   MOVE 2 TO WS-LETTER-SCORE
               WHEN 'B'
               WHEN 'C'
               WHEN 'M'
               WHEN 'P'
                   MOVE 3 TO WS-LETTER-SCORE
               WHEN 'F'
               WHEN 'H'
               WHEN 'V'
               WHEN 'W'
               WHEN 'Y'
                   MOVE 4 TO WS-LETTER-SCORE
               WHEN 'K'
                   MOVE 5 TO WS-LETTER-SCORE
               WHEN 'J'
               WHEN 'X'
                   MOVE 8 TO WS-LETTER-SCORE
               WHEN 'Q'
               WHEN 'Z'
                   MOVE 10 TO WS-LETTER-SCORE
      * If the character is not a letter, its score is 0
               WHEN OTHER
                   MOVE 0 TO WS-LETTER-SCORE
           END-EVALUATE.

       DISPLAY-RESULT.
           DISPLAY "Input word: " WS-INPUT-WORD.
           DISPLAY "Calculated Score: " WS-TOTAL-SCORE.

       END-PROGRAM.
           STOP RUN.

Where the Logic Happens: A Deep Dive into the Code

Let's break down the PROCEDURE DIVISION, which contains the core logic of our program. We'll follow the flow of execution step-by-step.

Program Logic Flow Diagram

This diagram illustrates the high-level workflow of our Scrabble score calculator.

    ● Start
    │
    ▼
  ┌──────────────────┐
  │ Accept Input Word│
  └─────────┬────────┘
            │
            ▼
    ◆  Input Empty?  ◆
   ╱         ╲
 Yes          No
  │            │
  ▼            ▼
[Set Score=0]  ┌───────────────────┐
  │            │ Normalize to UPPERCASE │
  │            └──────────┬──────────┘
  │                       │
  │                       ▼
  │            ┌───────────────────┐
  │            │ Calculate Word Length │
  │            └──────────┬──────────┘
  │                       │
  │                       ▼
  │            ╭─── Loop Characters ────╮
  │            │  (PERFORM VARYING)    │
  │            │   - Get Character     │
  │            │   - Evaluate Score    │
  │            │   - Add to Total      │
  │            ╰──────────┬────────────╯
  │                       │
  └────────────┬──────────┘
               ▼
        ┌──────────────┐
        │ Display Result │
        └───────┬──────┘
                │
                ▼
            ● End

Step 1: Data Declaration in WORKING-STORAGE

Before any logic runs, we must define our variables. The PIC (Picture) clause is crucial here. It defines the type and size of a variable.

  • PIC X(50): Defines an alphanumeric string of 50 characters.
  • PIC 99 or PIC 9(2): Defines a two-digit numeric field.
  • PIC 9(4): Defines a four-digit numeric field for the total score.
  • VALUE SPACES initializes a string with spaces, while VALUE 0 initializes a numeric field with zero.
  • 78 Level Number: This special level number is used to define constants. We use it for our LOWERCASE and UPPERCASE character sets for the INSPECT ... CONVERTING verb.

Step 2: Input and Normalization

The program begins execution in the MAIN-LOGIC paragraph.


           DISPLAY "Enter a word to score (max 50 chars): "
               WITH NO ADVANCING.
           ACCEPT WS-INPUT-WORD.

The ACCEPT verb reads input from the console and stores it in WS-INPUT-WORD. We then immediately handle the case of empty input.


           MOVE WS-INPUT-WORD TO WS-UPPER-WORD.
           INSPECT WS-UPPER-WORD CONVERTING LOWERCASE TO UPPERCASE.

This is a key step. We copy the input to a new variable, WS-UPPER-WORD. Then, the powerful INSPECT verb is used. The CONVERTING clause iterates through the string and replaces any character found in our LOWERCASE constant with the corresponding character from our UPPERCASE constant. This makes our subsequent scoring logic much simpler, as we only need to check for uppercase letters.

Step 3: Calculating the True Word Length

When a user enters a word, the ACCEPT verb might fill the rest of the 50-character buffer with spaces. We need to score only the actual letters. This code snippet is a clever way to find the true length:


           INSPECT FUNCTION REVERSE(WS-UPPER-WORD)
               TALLYING WS-WORD-LENGTH FOR LEADING SPACES.
           COMPUTE WS-WORD-LENGTH = LENGTH OF WS-UPPER-WORD - WS-WORD-LENGTH.

It works by first reversing the string (e.g., "HELLO " becomes " OLLEH"). It then uses INSPECT again, this time to TALLY (count) the number of leading spaces. In our example, this would be 3. Finally, we subtract this count from the total length of the variable (50) to get the actual length of the word (50 - 45 = 5 for "HELLO").

Step 4: The Main Processing Loop

This is the heart of the program. We use a PERFORM VARYING loop, which is Cobol's equivalent of a `for` loop.


           PERFORM VARYING WS-INDEX FROM 1 BY 1
               UNTIL WS-INDEX > WS-WORD-LENGTH

               ... loop body ...

           END-PERFORM.

This loop initializes WS-INDEX to 1, increments it by 1 on each iteration, and continues until it is greater than the calculated WS-WORD-LENGTH. Cobol uses 1-based indexing for strings, not 0-based like many modern languages.

Step 5: Character Evaluation with EVALUATE

Inside the loop, we first isolate the character at the current index:


               MOVE WS-UPPER-WORD(WS-INDEX : 1) TO WS-CURRENT-CHAR

This is Cobol's substring syntax: variable(start-position : length). We then call our scoring paragraph, CALCULATE-LETTER-SCORE.

The EVALUATE statement is a clean and readable alternative to a long chain of IF/ELSE IF statements. It compares the value of WS-CURRENT-CHAR against a series of WHEN clauses.


           EVALUATE WS-CURRENT-CHAR
               WHEN 'A'
               WHEN 'E'
               ...
                   MOVE 1 TO WS-LETTER-SCORE
               WHEN 'D'
               WHEN 'G'
                   MOVE 2 TO WS-LETTER-SCORE
               ...
               WHEN OTHER
                   MOVE 0 TO WS-LETTER-SCORE
           END-EVALUATE.

The logic is crystal clear. If the character matches any of the `WHEN` conditions, the corresponding action is taken. The `WHEN OTHER` clause acts as a default case, assigning a score of 0 to any non-alphabetic characters (like hyphens, numbers, or spaces), making our program robust.

Detailed `EVALUATE` Logic Flow

This diagram shows how the decision-making process works inside the `CALCULATE-LETTER-SCORE` paragraph for each character.

    ● Get Current Character (e.g., 'B')
    │
    ▼
  ┌──────────────────┐
  │ EVALUATE WS-CURRENT-CHAR │
  └─────────┬────────┘
            ├─ WHEN 'A', 'E', 'I'... ⟶ [Set Score = 1]
            │
            ├─ WHEN 'D', 'G'...      ⟶ [Set Score = 2]
            │
            ├─ WHEN 'B', 'C', 'M'... ⟶ [Set Score = 3]  ✔ Match!
            │
            ├─ WHEN 'F', 'H', 'V'... ⟶ [Skip]
            │
            ├─ ... (and so on) ...
            │
            └─ WHEN OTHER            ⟶ [Set Score = 0]
            │
            ▼
    ● Return Letter Score (3)

Step 6: Displaying the Result and Ending the Program

After the loop completes, WS-TOTAL-SCORE holds the final value. We call a dedicated paragraph to display the output neatly.


       DISPLAY-RESULT.
           DISPLAY "Input word: " WS-INPUT-WORD.
           DISPLAY "Calculated Score: " WS-TOTAL-SCORE.

Finally, STOP RUN terminates the program execution.


How to Compile and Run the Program

You can compile and run this code using GnuCOBOL (formerly OpenCOBOL), a free and open-source Cobol compiler available for most operating systems.

1. Save the code in a file named `scrabble.cbl`.

2. Open your terminal or command prompt and navigate to the directory where you saved the file.

3. Compile the program using the following command:


cobc -x -free scrabble.cbl
  • -x creates an executable file.
  • -free allows for more modern, free-form coding style, though our code adheres to traditional column boundaries for maximum compatibility.

4. Run the executable:


./scrabble

The program will then prompt you to enter a word, and it will display the calculated score.


Alternative Approaches and Considerations

While the EVALUATE statement is highly readable and perfect for this scenario, a seasoned Cobol developer might consider other approaches, especially if the scoring rules were more complex or dynamic.

Table-Based Lookup with SEARCH

A more advanced method involves defining the letter values in a table (an array in Cobol terminology) within the DATA DIVISION and then using the SEARCH verb to find the letter and retrieve its score.

Pros:

  • Scalability: If the scoring rules changed or you needed to add different languages, you would only need to update the table data, not the procedural logic.
  • Data-Driven: This approach separates the data (letter values) from the logic (the lookup process), which is a core principle of good software design.

Cons:

  • Increased Complexity: Setting up a table with indexes and using the SEARCH or SEARCH ALL (for binary search on a sorted table) verb requires more initial setup and a deeper understanding of Cobol data structures.
  • Potential Over-engineering: For a fixed and simple rule set like Scrabble's, this approach might be considered over-engineering.

This alternative demonstrates the flexibility of Cobol. For your journey through the kodikra Cobol learning path, mastering the `EVALUATE` statement first is the ideal step before tackling advanced table handling.


Frequently Asked Questions (FAQ)

How do you handle both lowercase and uppercase letters in Cobol?
The most effective way is to normalize the input string to one case (either upper or lower) before processing. The INSPECT ... CONVERTING statement is the idiomatic Cobol tool for this job, replacing characters from one set with corresponding characters from another.
What exactly is the EVALUATE statement in Cobol?
The EVALUATE statement is a powerful control structure that functions like a switch or case statement in languages like C++, Java, or JavaScript. It provides a clean and highly readable way to handle multi-way branching based on the value of a variable, avoiding complex nested IF statements.
Why is the WORKING-STORAGE SECTION so important?
In Cobol, all variables and data structures must be explicitly declared before they can be used. The WORKING-STORAGE SECTION is the part of the DATA DIVISION where you define all the variables your program will need during its execution. This strict declaration forces developers to think carefully about data types and memory allocation, which contributes to Cobol's reliability.
Can this program handle empty or non-alphabetic input?
Yes. Our code includes a check for empty input (IF WS-INPUT-WORD = SPACES) and gracefully sets the score to 0. Additionally, the EVALUATE statement's WHEN OTHER clause ensures that any character that is not a letter (e.g., numbers, punctuation, symbols) is assigned a score of 0, making the calculation robust against invalid characters.
What does PIC stand for in Cobol?
PIC is short for PICTURE. The PICTURE clause is used in data declarations to define the type and format of a data item. For example, PIC X(10) defines a 10-character alphanumeric string, while PIC 9(5)V99 defines a numeric field with 5 digits before the implied decimal point and 2 digits after.
How is string indexing different in Cobol?
Cobol uses 1-based indexing, meaning the first character of a string is at position 1, not 0. The syntax for accessing a substring, known as "reference modification," is variable-name(start-position : length). For example, MY-STRING(1 : 3) would retrieve the first three characters of MY-STRING.
Is Cobol still a relevant language to learn?
Absolutely. Billions of lines of Cobol code still run on mainframe systems that power core functions of the global economy, including banking, insurance, government services, and logistics. There is a high demand for developers who can maintain and modernize these critical systems, making Cobol a valuable and stable career skill.

Conclusion: More Than Just a Score

You have successfully built a fully functional Scrabble score calculator in Cobol. In doing so, you've moved beyond theoretical knowledge and applied core concepts to a practical problem. You've seen how Cobol's structured nature, explicit data declaration, and powerful processing verbs come together to create code that is not only functional but also robust and remarkably clear.

The techniques you've practiced here—normalizing data with INSPECT, iterating with PERFORM VARYING, and making complex decisions with EVALUATE—are not just for games. They are the very building blocks used in high-stakes enterprise applications that run the world. By mastering these fundamentals, you are well on your way to becoming a proficient Cobol developer.

Ready to tackle the next challenge and continue your journey? Explore the complete Cobol 4 learning roadmap on kodikra.com to see what lies ahead. For more in-depth tutorials and guides, be sure to visit our comprehensive Cobol language resource center.

Disclaimer: The code in this article was tested using GnuCOBOL 3.1.2. While the core concepts are universal across Cobol compilers, specific syntax for environment setup or compiler directives may vary slightly on mainframe platforms like IBM Enterprise COBOL for z/OS.


Published by Kodikra — Your trusted Cobol learning resource.