I am learning two dimensional arrays in C++. I am trying to write a function that will search for an item in the array and if it is found it will return the location of the item.
I have started with a function just to search the array for the item:
bool search (int x[][3], int num_rows, int item)
{ for (int i = 0; i < num_rows; ++i)
{ if (x[i][j] == item) return true;}
return false;
}
But I am not sure how to revise the function so that it will do what it is supposed to. My first thought is to change the bool function to something else but will double allow me to send back the location? And how to I even get it to write the location? (using i and j)??
thank you for your help!
There are a bunch of ways to do this. You could create a struct that holds a position in the array. Then you could return the struct. Or you could pass the array as a refrenence, then just fill the array with the I and j values.
I would add 2 more arguments to the list for the function.
Pass in 2 int references and use them as the loop variables in the function (i and j).
Return from the function when the element is found, as you do now. i and j would have the correct values for the location of the matching element - when the function returns true.
ie:
1 2 3 4 5 6 7 8
bool search (int x[][3], int num_rows, int item, int& i, int& j)
{
for ( i = 0; i < num_rows; ++i)// do not declare i here. Passed i to be used here
// you need another for loop here (over j)
{ if (x[i][j] == item) returntrue;}
returnfalse;
}