0

Suppose that I have an array

 bool string[N]={false};

After doing some operations all the elements of the array string become true. And I want to check this condition in an if statement like so:-

pseudo code--

if(all the elements of string are same or equal)
 then do this

How do I achieve this?I am not supposed to use counters like

for(int i=0;i<N;i++)   //or something else like this 
LihO
  • 41,190
  • 11
  • 99
  • 167
chanzerre
  • 2,409
  • 5
  • 20
  • 28

4 Answers4

5

PP just needed to alter his code a tiny bit, the answer he was alluding to was:-

if (memcmp (&string [0], &string [1], sizeof string [0] * (N - 1)) == 0)
{
  /* all elements the same */
}

The N-1 stops overrunning the end of the buffer.

The memcmp compares string [0] with string [1], then string [1] with string [2], then string [2] with string [3] and so on up to string [n-2] and string [n-1].

Skizz
  • 69,698
  • 10
  • 71
  • 108
0

If you can use pointers, then it could be something like this:

bool first = string[0];
bool* current = string + 1;
bool* end = string + N;

bool allEqual = true;

while (current < end)
{
    if (*current != first)
    {
        allEqal = false;
        break;  // No need to loop more
    }

    ++current;
}

if (allEqual)
    std::cout << "All elements are " << std::boolalpha << first << '\n';
else
    std::cout << "First not-equal is at index " << (current - string) / sizeof(string[0]) << '\n';

Really not that much different than using an index, since the pointer current acts as a kind of index.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

"I am not supposed to use counters like for(int i=0;i<N;i++)" ~> you still need to write a loop that examines all elements, you just need to avoid using temporary int variables for indexing.

Here's one of the possible solutions based on pointer arithmetic:
int elementsAreEqual(int* first, int size) {
    int* current = first;
    int* last = first + size - 1;
    while (1) {
        if (*current != *first)
            return 0;
        if (current == last)
            break;
        current++;
    }
    return 1;
}
used as:
const int N = 5;
int values[] = {0,0,0,0,0};

if (elementsAreEqual(values, N))
    printf("Elements are equal.\n");
else
    printf("Elements are not equal.\n");
LihO
  • 41,190
  • 11
  • 99
  • 167
0

If you want to check it with only one if, and no loop, you can try the following:

bool string[N] = {false};

if ((0 == memcmp(&string[0], &string[1], sizeof(string[0]) * (sizeof(string) - 1))) {
   //equal
}

Because the two memory areas overlap, offset by one, then each pair in the array are compared.

jbr
  • 6,198
  • 3
  • 30
  • 42