I am trying to create a program that computes the value of a word by summing the values of its letters.
These are the letters and their corresponding value:
- 1 Point: A, E, I, L, N, O, R, S, T, U
- 2 Points: D, G
- 3 Points: B, C, M, P
- 4 Points: F, H, V, W, Y
- 5 Points: K
- 8 Points: J, X
- 10 Points: Q, Z
Here's the program:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch; int sum=0;
printf("Enter a word: ");
while ((ch=getchar())!='\n') {
toupper(ch);
if (ch== 'A' || ch== 'E' || ch== 'I' || ch== 'L' || ch== 'N' || ch== 'O' || ch== 'R' || ch== 'S' || ch== 'T' || ch== 'U')
sum+=1;
else if (ch== 'D' || ch== 'G')
sum+=2;
else if (ch=='B' || ch== 'C' || ch== 'M' || ch== 'P')
sum+=3;
else if (ch=='F' || ch== 'H' || ch== 'V' || ch== 'W' || ch== 'Y')
sum+=4;
else if (ch=='K')
sum+=5;
else if (ch=='J' || ch== 'X')
sum+=8;
else if (ch=='Q' || ch== 'Z')
sum+=10;
}
printf("\nScrabble value: %d",sum);
return 0;
}
When I run the program it prints "Scrabble value: 0". Seems like the program is skipping the while loop entirely, maybe I am not using getchar properly, but I can't figure out what's wrong.
getchar()returnsint, and might returnEOFrather than an actual character. I/O is tricky.