This function tests whether the counter array passed in has an element smaller than the specified value:
bool has_element_less_than(int value, int counter[N][N])
{
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (counter[i][j] < value)
return true;
}
}
return false;
}
You use it:
if (has_element_less_than(10000, counter))
do_something();
You could deal with variable dimension arrays in C99 by passing N as a parameter to the function. It assumes you have the C99 header <stdbool.h>
available and included.
Is this what you're after? You mention 'While' so it isn't clear whether you need to use a while
loop — if you do, I think this does the job:
int i = 0;
while (i < N)
{
int j = 0;
while (j < N)
{
if (counter[i][j] < 10000)
{
counter[i][j] = do_something(i, j, counter[i][j]);
}
j++;
}
i++;
}
Or, more colloquially but using for
loops:
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (counter[i][j] < 10000)
{
counter[i][j] = do_something(i, j, counter[i][j]);
}
}
}
Note that this code is using C99; you can declare i
and j
outside the loops and it becomes C89 code. Also, if for any reason you need i
or j
(or, more likely, both) after the loop, you need to declare the variables outside the loop.
The second solution with for
loops is more idiomatic C; the for
loop is very good for this job and is what you should plan to use, not least because it packages all the loop controls on a single line, unlike the while
loop solution which has the initialize code on one line (outside the loop), the condition on another, and the reinitialization on yet a third line.