CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

The value of a word in Scrabble

To answer our Scrabble questions, we'll develop two simple helper functions:

#include <stdbool.h>
#include <string.h>
#include <ctype.h>

//  ENSURE THAT A WORD CONTAINS ONLY LOWERCASE CHARACTERS
bool valid_word(char word[])
{
    int i = 0;

//  IF NOT A LOWERCASE CHARACTER, THE FUNCTION RETURNS false
    while(word[i] != '\0') {
	if( ! islower( word[i] )) {   //  if not islower ...
            return false;
        }
        i = i+1;
    }
//  WE'VE REACHED THE END OF THE WORD - IT'S ALL LOWERCASE
    return true;
}

//  CALCULATE THE SCRABBLE VALUE OF ANY WORD
int calc_value(char word[])
{
//  AN ARRAY TO PROVIDE THE VALUE OF EACH LETTER, FROM 'a' TO 'z'  
    int values[] = {  1, 3, 3, 2, 1, 4, 2, 4, 1, 8, 5, 1, 3, 1,  
                      1, 3, 10, 1, 1, 1, 1, 4, 4, 8, 4, 10 };
    int total    = 0;
    int i        = 0;

//  TRAVERSE THE WORD DETERMINING THE VALUE OF EACH LETTER
    while(word[i] != '\0') {
        total   = total + values[ word[i] - 'a' ];
        i = i+1;
    }
    return total;
}

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

 


CITS2002 Systems Programming, Lecture 8, p10, 17th August 2021.