1

I've been working in a program in order to complete Project Euler's problem 17 and I tried to do it in C. Problem:

If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

I wrote a function that puts all the numbers between 1 and 1000 in words and into an array with 1001 elements (the last is NULL for iteration). But I'm having trouble when I try to count the number of chars in every element of the string, because I don't know how to do it. Can someone give me a little help?

1
  • You only need one string, not 1000. You add its length to the running total. Commented Feb 6, 2016 at 23:51

2 Answers 2

6

You could do it like this:

int char_count = 0;

char **p = array;

while (*p) {
    char_count += strlen(*p);
    ++p;
}

Note that strlen() will count spaces too.

If you don't want spaces or special characters counted, you could write your own length function such as:

int string_length (const char *str) {
    int len = 0;

    while(*str) {
        /* Count only lower-case letters a-z. */
        if (*str >= 'a' && *str <= 'z') ++len;
        ++str;
    }

    return len;
}
Sign up to request clarification or add additional context in comments.

Comments

2

Assuming your array is called array...

int count = 0, i;

for (i = 1; i <= 1000; ++i) {
    count += strlen(array[i]);
}

1 Comment

Perhaps you should be using elements 0 to 999 instead of 1 to 1000. Otherwise element 0 is undefined, and anyone trying to maintain your program is going to encounter an unexpected bug if they try to access it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.