1

I finished the Initials (more comfortable) problem, but when trying to detect initials, I'd like to avoid negative indeces.

Here's what I used for the detection of initials, if it's not a space at first index.

if (i == 0 || name[i-1] == 32)
        {
            printf("%c", toupper(name[i]));
        }

Could it be an issue already, if i==0 and I use a condition refering to index [-1]? Would it be safer to split it up like this?:

if (i == 0)
        {
            printf("%c", toupper(name[i]));
        }
else if (name[i-1] == 32)
        {
            printf("%c", toupper(name[i]));
        }

If I were to allow the access of a negative index. What exactly happens and how can this cause issues?

Thanks

1 Answer 1

1

Have you tried?

if (i == 0 || name[i] == 32)
{
    printf("%c", toupper(name[i + 1]));
}

In the most comfortable edition we assume that the user enters the name correctly and that the space is not the last place, it is not necessary to check the limits of the array, for now should suffice with this code.

EDIT: I was thinking less comfortable, you're right. We can consume the spaces in a while loop, in addition to checking the limits

if (i == 0 || name[i] == ' ')
    while(i == ' ') && (i < n))
        i++
    {
        printf("%c", toupper(name[i]));
    }

inside a for loop. Something similar can be done when i! = 0

7
  • But isn't that the addition of the more comfortable version to regard sloppy input, since the specifications say: "But the user’s input might be sloppy, in which case there might be one or more spaces at the start and/or end of the user’s input or even multiple spaces in a row."
    – Julian
    Commented May 28, 2017 at 16:59
  • you are right with this
    – MARS
    Commented May 28, 2017 at 18:33
  • Thanks, I've skipped the spaces before already using this bit: if (name[i] == 32) { }. Now, I was mainly wondering about actually accessing the negative index. Will it wrap around somehow? Is it always 0?
    – Julian
    Commented May 28, 2017 at 18:42
  • We do not have to worry about the negative indexes since automatically the arrays start at zero, unless we make alo as name [i - 1] and i is precisely zero, if so, we can impose a new condition if (i - 1)> = 0
    – MARS
    Commented May 28, 2017 at 18:51
  • Yes, but if you would actually use an unset [-1] index (which seems to be NULL or dec 0, right?), is this actually usable or an issue?
    – Julian
    Commented May 28, 2017 at 19:02

You must log in to answer this question.

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