2

I was hoping you might be able to help me improve the design of my code. I've solved the initials problem, and it passes check50 on both normal and hacker edition (the hacker edition was incidental), but I don't feel the code is very concise, as there is an element of duplication in the code, but I don't really know where to go from here to improve the design. Here is an excerpt from my code:

...

for (int i = 0, n = strlen(name); i < n; i++) // loop over string one character at a time
{
    if (name[i] == ' ') // if character is a space
    {
        if (name[i+1] >= 'a' && name[i+1] <= 'z') // if next letter letter is a-z
        {
            printf("%c", name[i+1] - ('a' - 'A')); // capitalize and print it
        }

...

...

    else if (i == 0) // at the first character (index 0) (as long as it is not a space)
    {
        if (name[i] >= 'a' && name[i] <= 'z') // if that first letter is a-z
        {
            printf("%c", name[i] - ('a' - 'A')); // capitalize it
        }

As you can see from the excerpt, there are two parts that look the same except on part is [i] and the other is [i+1].

Is there a way of simplifying this?

0

Sometimes I've figured that functions can't make your code lighter, then sometimes the solution is to do more than one thing at a time. Below is my solution in pseudo-code, with comments.

name = GetString();

// Print first character in uppercase
print(first char in upper-case)

// Then print each character after a space, in uppercase
for (char in name)
{
    if (current char is ' ')
    {
        print(next char in upper-case)
    }
}
| improve this answer | |
  • I agree that using a function such as toupper would potentially lighten my code so I can print in upper case, but your first line doesn't have any element of error correction in it, so if the character is a space it wouldn't return the intended result. I understand that this isn't required for the standard edition of pset2, but as I had it in my code already, it seems that I would be taking a step backwards? Unless of course I have missed an element of logic you intended? – A.Logan Oct 15 '16 at 10:27
  • You're not missing anything. Running my code with input like " abc xyz" outputs " A X", a large flaw which I did not realize was there. I'll fix my original code, edit this answer and then see how it compares again. – Martin Kleiven Oct 15 '16 at 10:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .