Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading