Write a function
int findLast(string words[], int numWords, string target)
that returns the index of the last occurence of target in words or -1 if there is no occurrence.

Remember: you can compare string objects using ==, these are NOT C-strings !

Here is my solution:

int findLast(string words[], int numWords, string target) 
{
    for(int i = 0; i >= numWords; i--)
    {
        if(words[i] == target)
        {
            return i;
        }
    }
    return -1;
}

Right now, MyProgrammingLab is not accepting this answer. Is there anything I need to add or change in this function? Any help would be appreciated.

Recommended Answers

All 4 Replies

At line 3: for(int i = 0; i >= numWords; i--) // how does this make any sense?
I assume what you are wanting to do is to iterate from the the last word index to the first word index.
ie. from numWords-1 to 0
So rewrite line 3 to reflect that logic.

Is this what you meant?

int findLast(string words[], int numWords, string target) 
{
    for(int i = 0; numWords-1 <= 0; i--)
    {
        if(words[i] == target)
        {
            return i;
        }
    }
    return -1;
}

Something like for (int i = numWords-1; i >= 0; --i)

You wrote for(int i = 0; numWords-1 <= 0; i--) - with this code, the only iteration that would occur is if numWords is 1. Any other positive value for numWords results in your loop doing nothing.
eg: Assume numWords = 5. When would (5 - 1) ever be less than or equal to zero?

This is what you should use: for (i = numwords-1; i >= 0; i--) {...}

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.