Wrong output with matrix program

Hello, I am having trouble with this program not working properly. When I set the matrix to size 1 it works properly but when its greater than 1 it does not give me the correct output. Help will be much appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
  int main()
{
    bool found;
    int mat[100][100],
    item,
    n;
    cout<<"Enter n value to determine size of matrix: ";
    cin>>n;
    cout<<"Enter positive numerical values for Matrix:\n";
    for(int row = 0; row<n;row++)
        for(int col=0;col<n;col++)
            cin>>mat[row][col];
    cout<<"Enter search item: ";
    cin>>item;
    for(int row = 0; row < n; row++)
        for(int col = 0; col < n; col++)
            if(mat[row][col]==item)
                found = true;
            else
                found = false;
    if(found==true)
        cout<<"item found\n";
    else
        cout<<"item not found\n";
}
Your code searches EVERY cell in the matrix, and sets found to true or false EVERY time. So found will be true or false depending on the LAST cell.

What happens if the value you're looking for isn't the last to be checked?
How would I go about it not setting found to true or false only depending on the last value?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
    int row = 0, col = 0;
    bool found = false;
    for (row = 0; row < n; row++) {
        for (col = 0; col < n; col++)
            if (mat[row][col] == item) {
                found = true;
                break;
            }
        if (found) break;
    }
    if (found)
        cout << "item found at " << row << ", " << col << "\n";
    else
        cout << "item not found\n";

Topic archived. No new replies allowed.