Pages

This blog is under construction

Friday, January 8, 2021

C Program for Scrabble

Scrabble is a word game that many of you may have played. Two or more players can play it. Players make words using letter tiles available with them and those already on the board. Each word has a score based on the value of each letter and the squares covered by the word. In this problem you have to write a program that reads a word and calculates the score of the word using the letter values. Use the following values for the letters.

Value Letters with value

1 All vowels, N, T, L, R, S

2 D, G

3 B, C, M, P

4 F, H, V, W, Y

5 K

8 J, X

10 Q, Z

Your program should work for both lower case and upper case letters in the input word. If the input  contains any non-alphabetic characters then the program should print "Illegal input". Hint: You can use one of the standard library functions to convert all lower case letters to upper case.

If input is Quiz then the program should print 22. If the input is What is the program should print Illegal input since the input contains a space which is not alphabetic.

Solution:

#include <stdio.h>

#include <ctype.h>

#include <stdlib.h>

/*The program does not check if the input word is a legal English word */

int letterValue(char c) {

  switch (c) {

    case 'A':case 'E':case 'I':case 'O':case 'U':case 'N':case 'T':case 'L':

    case 'R':case 'S': {return 1;}

    case 'D':case 'G': {return 2;}

    case 'B':case 'C':case 'M':case 'P': {return 3;}

    case 'F':case 'H':case 'V':case 'W':case 'Y': {return 4;}

    case 'K': {return 5;}

    case 'J':case 'X': {return 8;}

    case 'Q':case 'Z': {return 10;}

    default: {printf("Illegal input\n"); exit(0);}

  }

}

int main(void) {

  char s[50];

  int len=0, score=0;

  char c;

  printf("Give the word (<50 chars) then ENTER = ");

  c=getchar();

  while (!iscntrl(c) && c!=EOF && len<51) {

    s[len++]=c;

    c=getchar();

  }

  for (int i=0; i<len; i++)

    score+=letterValue(toupper(s[i]));

  if (len<1) {printf("Null input\n"); return 0;}

  printf("Score for ");

  for (int i=0; i<len; i++) putchar(s[i]);

  printf(" is %d\n", score);

  return 0;

}

Output:

Give the word (<50 chars) then ENTER = Quiz

Score for Quiz is 22


Press any key to continue . . .

No comments:

Post a Comment