problem computing if statements in 2d array

hey guys am having a problem using if statements in my nested loop....am searching for an element(x) in my 2d array if the element is found a coordinate position (i,j) should be outputted...if element is not found output "-1" but my code outputs "-1" even when the element is there please help am desperate need to get this done so i can finish matrix operations......thanx in advance

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
  #include <iostream>
#include <vector>
#include <fstream>
#include <cmath>

using namespace std;
int matrix(vector<int>&data,int x)
{
    int d=0;
    ifstream infile("input.txt");
    //////////////////////////////////infiling
    int arr[20][20];
    infile>>x;
    while(!infile.eof())
    {
        while(infile>>d)
        {
            data.push_back(d);
        }
    }

    ///////////////////////////////////store in a 2d array
    int counter=0;
    int asize=sqrt(data.size());
    for(int i=0; i<asize; i++)
    {
        for(int j=0; j<asize; j++)
        {
            arr[i][j]=data.at(counter);
            counter++;
        }
    }
   
    ///////////////////////////////////finding the position
    int row=0;
    int col=0;
    int i=0,j=0;

    for(int i=0; i<asize; i++)
    {
        for(int j=0; j<asize; j++)
        {
            if(arr[i][j]==x)
            {
                cout<<i++<<"  "<<j++<<endl;
                break;

            }
            else
            {
                cout<<"-1"<<endl;
                break;

            }

        }
        if(arr[i][j]!=x)

        break;


    }
    return 0;

}


int main()
{
    vector<int>data;
    int x=0;
    int flag=0;

    flag=matrix(data,x);

    return 0;
}
The problem is at lines 51-52, you're displaying -1 on the first non-match, then breaking out of both loops.

This really makes more sense written as a function.
1
2
3
4
5
6
7
bool Find (<matrix<int> &arr, int asize)
{   for (int i=0; i<asize; i++)
        for (int j=0; j<asize; j++)
            if (arr[i][j]==x)
                 return true;     // found match    
    return false;  // No match
}


Topic archived. No new replies allowed.