I have just learnt C++ for a very short time, and in an assignment I am trying to find a particular target in a 2-dimensional array as follows:
bool simsearch(int array[22][22], int target, int n){
bool result = 0;
for (int a = 1; a < n + 1; a++){
for (int b = 1; b < n + 1; b++){
if (array[a][b] == target)
result = 1;
break;
}
}
return result;
}
and use it like:
if(simsearch(substitute, 6, size) == 0){
cout << "**Warning**" << '\n';
}
But, the warning output is always there even if the target is in the array. What is the underlying problem in the code?
Thanks!
Indices of arrays start from 0 and if an array has n elements then the highest index is n-1.
Rewrite the function the following way
bool simsearch( const int array[22][22], int target, int n )
{
bool found = false;
for ( int i = 0; i < n && !found; i++ )
{
for ( int j = 0; j < n && !found; j++ )
{
if ( array[i][j] == target ) found = true;
}
}
return found;
}
Or
bool simsearch( const int array[22][22], int target, int n )
{
bool found = false;
for ( int i = 0; i < n && !found; i++ )
{
int j = 0;
while ( j < n && array[i][j] != target ) j++;
found = j != n;
}
return found;
}
I hope that the argument for n is always equal to 22.:)
Another approach is the following
template <typename T, size_t M, size_t N>
bool simsearch( const T ( &a )[M][N], const T &value )
{
bool found = false;
for ( size_t i = 0; i < M && !found; i++ )
{
size_t j = 0;
while ( j < N && !( a[i][j] == value ) ) ++j;
found = j != N;
}
return found;
}
bool simsearch(int array[22][22], int target, int n){
bool result = 0;
for (int a = 0; a < n ; a++){
for (int b = 0; b < n; b++){
if (array[a][b] == target){
result = 1;
break;
}
}
if(result) break;
}
return result;
}
This should work. Use brackets and conditions properly
There are two things to notice over here:-
for (int a = 1; a < n + 1; a++)
If n represents size here ( which seems from call to this function) then this you need to change. Array of size 10 must be indexed from 0 to 9.
Second thing rather than returning integer
return result;
you can return true OR false.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.