Reputation: 31
/--- search.cpp ----------------------------------------------------- Program to read a 3 X 3 matrix of integers mat and an integer item, and search mat to see if it contains item. --------------------------------------------------------------------/
So in this activity we made a program to search a if a number is contained in a 3x3 array.
If I put in 1 2 3 4 5 6 7 8 9
as the elements of the array,
the only number it finds is 9
#include <iostream>
using namespace std;
const int SIZE = 3; // Set matrix size
//typedef int Matrix[SIZE][SIZE]; // Define data type Matrix
bool matrixSearch(int mat[SIZE][SIZE], int n, int item);
int main()
{
// Enter the matrix
int mat[SIZE][SIZE];
cout << "Enter the elements of the " << SIZE << " X " << SIZE
<< " matrix rowwise:\n";
for (int i = 0; i < SIZE; i++)
for (int j = 0; j < SIZE; j++)
cin >> mat[i][j];
// Search mat for various items
int itemToFind;
char response;
do
{
cout << "Enter integer to search for: ";
cin >> itemToFind;
if (matrixSearch(mat, SIZE, itemToFind))
cout << "item found\n";
else
cout << "item not found\n";
cout << "\nMore items to search for (Y or N)? ";
cin >> response;
}
while (response == 'Y' || response == 'y');
}
bool matrixSearch(int mat[SIZE][SIZE], int n, int item) {
bool found;
int col, row;
for (row = 0; row <n; row++)
for (col = 0; col < n; col++)
if (mat[row][col] == item) {
found = true;
}
else
found = false;
return found;
}
Upvotes: 0
Views: 310
Reputation: 1881
Because, the loop is not breaking, once the item is found
. The loop continues to search for the item and changes found
to be false
again, unless it's the last item.
bool matrixSearch(int mat[SIZE][SIZE], int n, int item) {
bool found = false; //initialize here
int col, row;
for (row = 0; row < n && !found; row++)
for (col = 0; col < n; col++)
if (mat[row][col] == item) {
found = true; // once found, break the loop
break;
}
return found;
}
Upvotes: 0
Reputation: 9331
You set found
to false if an item is not a match:
for (col = 0; col < n; col++)
if (mat[row][col] == item) // if match, set found = true
found = true;
else
found = false; // otherwise false
So suppose you are searching for item = 4
and the array is 1 2 3 4 5 6 7 8 9
. It will find 4
correctly and set found to true
. But then the next element will be 5
and since it is not a match, found
will be set to false
.
To fix simply return from your function when the item is a match:
bool matrixSearch(int mat[SIZE][SIZE], int n, int item)
{
int col, row;
for (row = 0; row <n; row++) {
for (col = 0; col < n; col++) {
if (mat[row][col] == item)
return true; //end function and return true
}
}
return false; //we got here, that means item was not found, return false
}
Upvotes: 1