Introduction
Scrabble is a popular word game that involves forming words on a board using lettered tiles. Each tile has a point value, and the goal is to create words that accumulate the highest score. In this guide, we’ll learn how to calculate the score of a Scrabble word using the C programming language.
Objective
The objective of this program is to calculate the score of a given Scrabble word based on the individual letter values. Each letter in the Scrabble game has a different point value. The program will take a word as input, and it will return the total score based on the points assigned to each letter in that word.
Program Code
#include #include // Function to calculate the Scrabble score of a word int calculateScrabbleScore(char word[]) { int score = 0; int i = 0; char letter; // Define the point values for each letter int letterPoints[] = {1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 3, 2, 4, 1, 4, 1, 8, 4, 10, 1, 1, 3, 10}; // Iterate through each letter in the word while ((letter = word[i++]) != '\0') { // Convert to uppercase to handle case-insensitivity letter = toupper(letter); // Check if the letter is a valid letter if (letter >= 'A' && letter <= 'Z') { // Calculate the score for the letter score += letterPoints[letter - 'A']; } } return score; } int main() { char word[100]; // Input the word from the user printf("Enter a Scrabble word: "); fgets(word, sizeof(word), stdin); // Calculate the score of the word int score = calculateScrabbleScore(word); // Output the result printf("The Scrabble score for the word \"%s\" is: %d\n", word, score); return 0; }
Program Explanation
This program consists of several parts:
- Header Files: The program includes the
stdio.h
header for input/output functions andctype.h
for converting characters to uppercase. - Letter Points Array: An array is defined to store the point values for each letter in the English alphabet. The values are based on Scrabble’s scoring rules.
- calculateScrabbleScore Function: This function takes the input word, iterates over each character, converts it to uppercase, and adds its corresponding point value to the total score. It returns the total score of the word.
- Main Function: The
main()
function prompts the user to input a word, calls thecalculateScrabbleScore()
function to calculate the score, and displays the result.
How to Run the Program
Follow these steps to run the program:
- Open a text editor and copy the program code into a new file.
- Save the file with a .c extension (e.g.,
scrabble_score.c
). - Open a terminal or command prompt.
- Navigate to the directory where the file is saved.
- Compile the program using the following command:
gcc scrabble_score.c -o scrabble_score
- Run the program by typing:
./scrabble_score
- Enter a word when prompted, and the program will display the Scrabble score.