# Thread: Problem with nested loops in functions

1. ## Problem with nested loops in functions

I am absolutely stumped on what I am doing wrong here. Essentially I have a function that takes a two dimensional array of chars and tries to determine if there are five "x" chars in a row. Here is the function:

Code:
```int wincheck1 ( char b[][COLS] )
{
int i, j, WIN;

for( i=0; i < ROWS; i++ ){
if(WIN == 1)
break;
else{
for ( j=1; j < (COLS-4); j++ ){

if( b[i][j] != b[i][j+1] != b[i][j+2] != b[i][j+3] != b[i][j+4] != 'x' ){
WIN=0;
}
else{
WIN=1;
break;
}
}
}
}

return WIN;

}```
It appears that this code always returns 0 even when I set up the array with 5 or more x chars in a row. I have done all kinds of tinkering with this code, but it always returns zero or goes into an infinite loop, never doing what I would like. Please help.

EDIT: ignore the fact that rows start at zero and columns start at 1. That's just the way that I set up the array.

EDIT: I originally tried to put a return statement after WIN=1 in place of using break statements, but that was giving me the same headaches.

2. Could I see the code that calls this function too, please. I am not a fan of multidimensional arrays by the way... And one doesn't have to be a calculus professor to just do the math and make it single dimensional, but that is just me being picky...

And at first glance of your code, it doesn't always go into the second for loop. Which is probably where you are having issues, right?

Code:
```int wincheck1 ( char b[][COLS] )
{
int i, j, WIN;

for( i=0; i < ROWS; i++ ){
if(WIN == 1)
break;
else{
for ( j=1; j < (COLS-4); j++ ){

if( b[i][j] != b[i][j+1] != b[i][j+2] != b[i][j+3] != b[i][j+4] != 'x' ){
WIN=0;
}
else{
WIN=1;
break;
}
}
}
}

return WIN;

}```
WIN's value is by default "undefined."

3. Originally Posted by countchocula
if( b[i][j] != b[i][j+1] != b[i][j+2] != b[i][j+3] != b[i][j+4] != 'x' )[/code]
That will not do anything close to what you want!
You'd need to seperate each expression, comparing each element with 'x', and &&ing the results together to make that work.
Or better yet, make it into another loop.

4. Originally Posted by iMalc
That will not do anything close to what you want!
You'd need to seperate each expression, comparing each element with 'x', and &&ing the results together to make that work.
Or better yet, make it into another loop.

Haha brilliant! I was worried about that section. I will try it out and get back to you.

EDIT:

Wow it worked. I can't believe I overlooked that portion of code. it seems so obvious now. Thanks!

5. I don't think that particular section was ever reached by your code before anyway. Initialize your WIN to zero and just remove all the red bits of code. They are redundant anyway.

6. That is precisely what I did and it has worked brilliantly. Thank you for your help.