If the array is an actual 2D array, if you know how to check if a number exists in a 1D array, you can use the exact same code to determine if a value exists in a regular 2D array.
The trick is to write the code using pointers to the start and ending elements of the array. The reason why is that a 2D array stores its data in contiguous memory, no different than a 1D array.
Here is an example of the same search function working for both 1-dimensional and 2-dimensional arrays:
#include<iostream>
bool exists(int *start, int *end, int value)
{
while (start != end)
{
if ( value == *start )
return true;
++start;
}
return false;
}
int main()
{
int a[3] = {4,5,6};
bool found = exists(a, a + 3, 5);
if ( found )
std::cout << "The number 5 was found\n";
else
std::cout << "The number 5 was not found\n";
// now a 2d array
int a2[3][4] = {{1,2,3,4},{7,8,9,10},{2,43,2,0}};
found = exists(&a2[0], &a2[2][4], 43);
if ( found )
std::cout << "The number 43 was found\n";
else
std::cout << "The number 43 was not found\n";
found = exists(&a2[0][0], &a2[2][4], 11);
if ( found )
std::cout << "The number 11 was found\n";
else
std::cout << "The number 11 was not found\n";
// Let's try a 3D array for fun
int a3[2][3][4] = {{{1,2,3,4},{7,8,9,10},{2,43,2,0}},
{{6,9,1,56},{4,8,2,10},{2,43,2,87}}};
found = exists(&a3[0][0][0], &a3[1][2][4], 56);
if ( found )
std::cout << "The number 56 was found\n";
else
std::cout << "The number 56 was not found\n";
}
Output:
The number 5 was found
The number 43 was found
The number 11 was not found
The number 56 was found
Surprisingly, the same function worked for 1-dimensional, 2-dimensional arrays, and even 3 dimensional arrays, all due to the data being stored in contiguous memory.
The address of the starting element, and the address of one past the ending element in the array are provided to the function, thus the function knows where to start and where to end the search.