matrix margins

Hello, I have to write a program which go through a matrix and look for filled cells with letters, and then count its neighbours. The problem is that each cell has 8 neighbours, and if I am at the last column, then the neighbours will be at the first column, so for the rows. I am not really sure how it's done.. I tried using % but it didnt work.
I would be really thankfull if someone could help me with that.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  void checkNeighbours(char gameBoard[][Max_Width_Size],char newBoard[][Max_Width_Size],int i, int j,int height,int width)
{
	int countNeighbours = 0;
	for(int k = i-1; k <= i+1; k++ )
	{
		for(int l = j-1; l <= j+1; l++ )
		{
			k = (k+i) % height;
			l = (l+j) % width;

				if(gameBoard[k][l] != '-' )
					countNeighbours += 1;
		}

	}
	if(countNeighbours - 1  < 2 || countNeighbours - 1  > 3 )
		newBoard[i][j] = '-';
}
The question isn't one of adjusting your math, but of whether or not you should try to access a column (or row). You're going to have to use some ifs.

For example,

1
2
3
4
5
if (k > 0)
{
  // then I can count stuff in row (k-1)
}
...

Good luck!
Topic archived. No new replies allowed.