elements of an array

Hi all,

I'm working with a two dimensional array.
I have a condition:

"if all elements in a sequence are all 2
then end"

but when I write a for loop for an array the condition only test if any of the elements is equal to 2, not if all of them are 2.

How do I rewrite the loop and the condition to apply to all elements not only one?

example:

1
2
3
4
5
6
7
8
for(int i = col1; i <= col1 + 6; i++)
   {
      if(array[row1][i] == 2)
         {
            // some code
            break;    
         }
   }


Cheers.
I think you can do something like the following, if I'm not mistaken.

1
2
3
4
5
6
7
8
9
10
11
bool allElementsAre(int value, int array[], int size)
{
    for(int i = 0; i < size; i++)
    {
        if(array[i] != value)
        {
            return false;
        }
    }
    return true;
}


then you can just call it in your code anytime like

1
2
3
4
5
6
7
8
9
if(allElementsAre( 2, array[row1], col1 + 6))
{
    // all elements are the same value
    // do something
}
else
{
    // do something else
}


if you don't want to use a function I think you can also do it this way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
bool elementsAreSame = true;
for(int i = col1; i <= col1 + 6; i++)
   {
      if(array[row1][i] != 2)
         {
            // some code
            elementsAreSame = false;
            break;    
         }
   }

if(elementsAreSame)
   {
      // do something
   }
else
   {
     // do something else
   }



Edit:

Oops, that doesn't seem to work. :P

There fixed it.
Last edited on
If you want to check each item is 2...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
bool b = false;
unsigned int x = 0, y = 0;
while(array[x++][y] == 2)
{
    if(x == x_size)
    {
         x = 0;
         y++;
    }
    if(y == y_size)
    {
         b = true;
         break; // End loop
    }
}
if(b) // The array is all 2s
     dostuff();
Last edited on
Late response...

Cheers guys. I got it now.

I needed to use a nested for loop (inner and outer loop) to capture all the elements.

Matt
Topic archived. No new replies allowed.