I am always getting the value of each letter I enter as 1 whereas I should get the values as described in the code. Please help find the error in my code.
#include <stdio.h>
#include <ctype.h>
char c;
char num (char c);
int main () {
int sum;
printf("Enter a word:");
c=0;
while (c=getchar() != '\n') {
c=toupper(c);
sum+=c;
}
printf("Scrabble value : %d",sum);
return(0);
}
char num (char c) {
if (c=='A'||c=='E'||c=='I'||c=='L'||c=='N'||c=='O'||c=='R'||c=='S'||c=='T'||c=='U') c=1;
if (c=='D'||c=='G') c=2;
if (c=='B'||c=='C'||c=='M'||c=='P') c=3;
if (c=='F'||c=='H'||c=='V'||c=='W'||c=='Y') c=4;
if (c=='K') c=5;
if (c=='J'||c=='X') c=8;
if (c=='Q'||c=='Z') c=10;
return(c);
}
In short, this will work for you (call num; fixed getchar call in while; initialized sum to 0; no error handling):
#include <stdio.h>
#include <ctype.h>
char c;
char num (char c);
int main () {
int sum = 0;
printf("Enter a word:");
c=0;
while ((c=getchar()) != '\n') {
c=toupper(c);
sum+=num(c);
}
printf("Scrabble value : %d",sum);
return(0);
}
char num (char c) {
if (c=='A'||c=='E'||c=='I'||c=='L'||c=='N'||c=='O'||c=='R'||c=='S'||c=='T'||c=='U') c=1;
if (c=='D'||c=='G') c=2;
if (c=='B'||c=='C'||c=='M'||c=='P') c=3;
if (c=='F'||c=='H'||c=='V'||c=='W'||c=='Y') c=4;
if (c=='K') c=5;
if (c=='J'||c=='X') c=8;
if (c=='Q'||c=='Z') c=10;
return(c);
}