0

I have to write program to find all indexes, where given element occurs. I' ve written this function:

int find(const int* tab, int size, int to_find)
{
  if (size<1 || tab==NULL) return -2;
  int i, counter = 0;
  for (i=0;i<size;i++)
  {
    if (to_find==*(tab + i)) return i;
  }
  return 0;
}

This function only returns first occurence of element, but I want to it returns every element. How can I do this?

3
  • 1
    "How can I do this?" start by not returning after the 1st element has been found? Commented Jan 1, 2020 at 12:42
  • Use a second array, where use store the indexes found? Commented Jan 1, 2020 at 12:42
  • 1
    Think about what the results are logically. You need to represent multiple locations of an array. How do you want it to look? A list or array of indices? The simplest thing to do is to use an array and you'll need to indicate how many elements (matches) are in the array. Commented Jan 1, 2020 at 12:43

2 Answers 2

2

Your find() function as it stands is fine. Aside that it should not return 0 to indicate that no values have been found, as 0 is a valid index.

To have it not just only find the 1st occurrence of matching elements, modify it in a way that you can tell it where to start its search and call it repetitively to let the caller decide what to do with the hit(s).

Sign up to request clarification or add additional context in comments.

Comments

1

A function can only return one value and then the control shifts to the statement following the function call. In order to get all the required values, a separate array can be used. Another way could be to modify the function to check for one value at a time. A loop can be used to call the function in each iteration.

Comments

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.