I'm making this program, it should count points for each letter just like on the scrabble game, but in my code it is skipping almost all of the letters that are located after b on the string for whatever reason.
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main (void)
{
char letters[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
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};
string word1 = "banana";
int w1p = 0;
for (int i = 0; i < strlen(word1); i++)
{
int n = 0;
printf("%c" ,word1[i]);
do
{
if (word1[i] == letters[n])
{
w1p = POINTS[n] + w1p;
n++;
printf("%c" ,word1[i]);
}
else
{
n++;
}
}
while (n > 26);
}
printf("%i" ,w1p);
}
The string syntax is from the cs50 library, as I started learning C now, I'm taking some shortcuts until I get some experience.
I tried to make it run the loop again until it finished the alphabet, but it doesn't seem to work, If someone could help me I would be very grateful.
Testing out your code it quickly became evident that the issue resided in the "do/while" loop testing criteria.
The best thing to be said about "do/while" loops is that they can be tricky to use. The way the loop is set up, the code inside the "do/while" loop will be executed once, the value of "n" will be incremented from "0" to "1", and then the "while" test will be checked. Since "1" is not greater than "26" the loop is exited. So that is why only the "a" character is is being picked up and three points are being accumulated.
Changing the test to "while (n < 26)" seemed to resolve the issue. Alternatively, an inner "for" loop could also have been used as noted in the following refactored code.
FYI, I do not have the CS50 package on my system, so I substituted a conventional method of initializing the "word1" character array. Following was the terminal output from testing both the correction to the "do/while" loop and the refactoring to utilize an inner "for" loop.
Try that out. Also, it probably would be wise to dig into some more "C" tutorials, especially as it pertains to "for" loops and "do/while" loops.