Why does this program written in C not print a value of 5 when comparing an input and some arrays?

Viewed 52
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <math.h>

// Points assigned to each letter of the alphabet
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 };
char ALPHABET[] = { 'a' , 'b', 'c', 'd', 'e', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };

int main(void) {
    string word1 = "dog";
    int score;
    int tile;
    int points;
    int index;
    int finish = strlen(word1);

    for (tile = 0, index = 0, score = 0; tile == finish; index++) {
        if (word1[tile] == ALPHABET[index]) {
            points = index;
            score = score + POINTS[points];
            tile++;
            index = -1;
        }
    }
    printf("%i\n", score);
}

This program prints a value of 0 instead of what I think should be 5 based on letter scores? Please give me some insight as to how I can accomplish this. Should I not be using an if statement inside a for loop?

2 Answers

Keep in mind that you are using zero based indexing.

Your for loop is using this:

tile == finish

It should be:

tile < finish

The length of “dog” is 3 so the index positions are 0 to 2.

This is at least part of your problems with the code.


As others have said, your loop needs a nested loop that iterates all of your alphabet letters. Once you find the match you can break out of that inner loop.


Also, you have:

'd', 2
'g', 4
'o', 3

Which totals 9. That is based on your code having two e characters.


The other issue is you reset index back to -1 so you are restarting at the beginning.

In summary:

  • Take on board the principle of zero based indexing for the bounds of your loop.
  • Use a nested for loop.
  • break out of the inner loop once you found the match.

The for loop test is incorrect: tile == finish is false at the first iteration of the loop, hence a score of 0.

Note that you should use two nested loops instead of hacking the loop index as coded:

#include <cs50.h>
#include <stdio.h>
#include <string.h>

// Points assigned to each letter of the alphabet
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 };
char ALPHABET[] = { 'a' , 'b', 'c', 'd', 'e', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };

int main(void) {
    string word1 = "dog";
    int score;
    int tile;
    int index;
    int len = strlen(word1);

    score = 0;
    for (tile = 0; tile < len; tile++) {
        for (index = 0; index < 26; index++) {
            if (word1[tile] == ALPHABET[index]) {
                score = score + POINTS[index];
                break;
            }
        }
    }
    printf("%i\n", score);
    return 0;
}
Related