C++ Lab 2 (Assign value to a letter in a word)
This program request input from the user using the command line, after input is typed the program loops through each character in the word and assigns value using an array, in this case, POINTS.
After that, the program adds all the values omitting non-letters. This program can be useful for a scrabble game.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
int main(void)
{
//declarations
string playerOneWord; //Variable to store input from user
int wordlength; //How long the string is
char letter; //Store each letter of the word inputed by user
int value; //ASCII value of the character
int accumulatedPoints = 0; //Total points earn for the inputed word
int letterPoints; //Points earned inputed letter
//constants
int POINTS[] = {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};
const int INVALID_CHARACTER = 0;
const int GET_CHAR_VALUE_TO_ZERO = 97;
const int ARRAY_POINTS_START = 0;
const int ARRAY_POINTS_END = 25;
//get user input
playerOneWord = get_string("Player 1: ");
//calculation
wordlength = strlen(playerOneWord);
for (int i = 0; i < wordlength; i++)
{
letter = tolower(playerOneWord[i]); //will change each character in the word to lowercase
value = letter - GET_CHAR_VALUE_TO_ZERO;
if (value < ARRAY_POINTS_START || value > ARRAY_POINTS_END)
{
accumulatedPoints = accumulatedPoints + INVALID_CHARACTER;
printf("%c = %i => zero value character\n", letter, value);
}
else
{
letterPoints = POINTS[value];
printf("%c = %i => %i\n", letter, value, letterPoints);
accumulatedPoints = accumulatedPoints + letterPoints;
}
}
//output
printf("%s\n", playerOneWord);
printf("%i\n", accumulatedPoints);
}