Displaying a message when a certain array element is present in C

This program displays certain messages when some of the elements are 'y' or if all of the elements are 'n'.

My question is about this line: someElements |= array[i] == 'y'.
I understand that it can be written in this way: someElements = someElements | array[i] == 'y'.

I’m just asking for an explanation why does it work?

#include <stdio.h>

int main()
{
    
    char array[3] = { 0 };

    int i;
    for (i = 0; i < 3; i++) {
        do {
        printf("\nElement No.%d [y/n]: ", i + 1);
        scanf(" %c", &array[i]);
            if (array[i] != 'y' && array[i] != 'n') {
            printf("Must be a lowercase 'y' or 'n'\n");
            } 
        } while (array[i] != 'y' && array[i] != 'n');
    }

    int someElements = 0;
    
    for (i = 0; i < 3; i++) {
        someElements |= array[i] == 'y';
    }
    if (someElements) {
        printf("\nSOME of the elements = y.\n");
    }
    else{
         printf("\nNONE of the elements = y.\n");
    }

    return 0;
}

Code link

>Solution :

The result of array[i] == 'y' is a boolean true or false. It can be implicitly converted to the int value 1 or 0 (respectively).

Then it’s easy to create a bitwise OR table for the possible combinations of someElements | array[i] == 'y':

someElements array[i] == 'y' someElements | array[i] == 'y'
0 0 0
0 1 1
1 0 1
1 1 1

So if any of the values are 1 then the result will be 1.

From this follows that if any of the characters in the array is equal to 'y' then the end result of someElements after the loop will be 1. Which then can be implicitly converted back to a boolean true in the following if condition.

Leave a Reply