# Thread: too many for loops?

1. ## too many for loops?

So I'm working on a "simple" sudoku solving program in C++ and i ended up having a 6-nested loop in the array and I keep hitting a STATUS_ACCESS_VIOLATION. i'm wondering if i have too many loops and the program just crashes? ill explain the code as best I can if you would like me to, but its hopefully not too confusing...

Code:
```for ( int c = 0; c < 9; c++ )
{
if ( !complete[c] )
{
for ( int r = 0; r < 9; r++ )
{
if ( board[r][c][0] == '_' )
{ //if the square is still undefined
length = strlen(board[r][c]); //find the length of the char array

bool instring = false;
int index = 0;

for ( int col = 0; col < 9; col++ )
{
for ( int ro = 0; ro < 9; ro++ )
{
if ( counter[ro][col] != '_' )
{
cout<<true;
//see if the char in counter is in the string
for ( int g = 1; g < length; g++ )
{
if ( board[r][c][g] == counter[ro][col] )
{
index = g;
while ( index < length )
{
board[r][c][index] = board[r][c][index+1];
index++;
}
}
}
}
}
}
}
}
}
}```

2. Nesting of loops doesn't cause access violations. The problem will be a logic error in the loops (eg falling off the end of an array, molesting a pointer, the rookie mistake of believing that a pointer is an array, forgetting to zero terminate strings). You need to check all array indices to make sure they are of arrays (not just pointers) and are in bounds.

Generally, deeply nested loops are considered a bad idea, because they are harder to understand and therefore harder to get right. That doesn't mean errors are because of nesting loops: it means that you've made an error, and are having trouble finding it in your nested loop structure.

It is often considered a better idea to put particular loops into functions that achieve some well-defined effect. Then name the functions so the name describes the effect. Then, instead of nested loops, have functions calling functions. If the inner functions are well named, the logic of the calling function (loop calling the inner function) is easier to understand, so problems are easier to localise to one function.

The loops will still exist, but by putting each loop into its own function, each loop will be easier to understand. IF you have designed and named the functions in a way that aids comprehension.

3. Agree with grumpy.Your code results STATUS_ACCESS_VIOLATION probably because of the arrays you have.In a line you go out of bounds ,that's my guess

4. When you post some code like this, always attach variable declarations so that we can know what the stuff means. If this is the actual code, correct your braces (3 in the same column), because they are confusing and probably not doing what you want.