Array search bug

Hi,

I'm having a bug that's driving me crazy, been trying to fix it for hours...

My program asks for numbers and places them in a 2D array.
Then it asks for a number and performs a search, after which it prints position for said number within the 2D array.

Search function has a bug that adds 1 to expected row position. "Fixed" it by substracting 1 to "row" variable, but it is ovb not acceptable.

Currently feeling kind of dumb about this, help will be 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
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
#include <iostream>
using namespace std;

#define R 3
#define C 2

typedef int matrix[R][C];

void input(matrix m){
int i, j;
i = j = 0;
	
	for(i = 0; i< R; i++){
		for(j = 0; j < C; j++){ 
			cout << "Row " << i << " Column " << j << ": ";
			cin >> m[i][j];
		}
	}
}

void search(int x, matrix m, int& row, int& column){
int r, c;
bool OK;

OK = false;
r = 0;

	while((!OK) && (r < R))
	{
	c = 0;
		while((!OK) && (c < C))
		{
			if(m[r][c] == x)
				OK = true;
			else
				c++;
		}
	r++;	
	}

	column = c;
	row = r-1;  //LOL
}

void shows(matrix m){
int i, j;
i = j = 0;

	for(i = 0; i < R; i++){
		for(j= 0; j < C; j++){
			cout << "Row " << i << " Column " << j << ": " << m[i][j] << endl;   
			
		}
	}
}

int main(){
	matrix mat;
	int number;
	int row;
	int column;
		
	input(mat);
				
	cout << "Which number are you looking for?: ";
	cin >> number;
	search(number, mat, row, column);
	cout << endl << "Row " << row << " Column: " << column;

	fflush stdin;
	getchar();
	return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
while (!OK && /*...*/){
    //...
    while (!OK && /*...*/){
        //...
    }
    if (OK)
        break;
    r++;
}

Breaking out of nested loops is one of those gray areas where goto is sort of acceptable, although I would personally go with
1
2
3
4
5
6
7
for (int i = 0; i < R*C; i++){
    int row = i / C;
    int column = i % C;
    //...
    if (/*...*/)
        break;
}
Topic archived. No new replies allowed.