0

Does anyone know of an easy way in C to check if a an element is NOT in a given array?

I think it would be fairly easy to determine if an element IS in an array by looping through it and seeing if an element is equal to the element I’m looking for.

But how do you determine if it’s NOT in there? For example, say I were using a nested loop… setting the condition if [i] != [j] don’t tell me if the element in [i] is nowhere in [j]…it just says that they’re not currently equal on that current iteration.

I believe Python has a function that lets you search If something is In or Not In a List or other collection. But does C?

1 Answer 1

0

No, C does not have such a function. The only way to check is to search the entire array. Most efficient is to just run a for loop or while loop and check every element. If a match is found, set a flag and break out of the loop. If not found, the loop ends on it's own and you can process a "not found" code block afterwards.

pseudocode:

int found = 0;
for( i = 0;i < array_size; i++)
{
    if( array[i] == target)  // edit: had the wrong "=" operator before changing it.  my bad. 
    { 
        found = 1;
        break;
    }
}

if (found)
{
    printf("There's a match. \n");    
}
else
{
    printf("No match. \n");
}

You might want to turn it into a function if it's something that's reused.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

4
  • Thanks! That's helpful. Feb 17, 2023 at 21:37
  • And just to confirm, in your pseudocode, setting int found to 0 and then updating it to 1 if found is a way fo creating an error message, correct? Feb 17, 2023 at 21:39
  • not really, it's a way to record if the item is found in the array or not. What you do with that flag after it's set is up to you. You could then use the flag to process an error if appropriate, instead of a print statement. (Note: 0 is ALWAYS interpreted as false and any non-zero as true.) You could change the code slightly and count how many times something appears in an array too. (Just delete the break statement.)
    – Cliff B
    Feb 17, 2023 at 22:28
  • Gotcha. Thank you Feb 20, 2023 at 19:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .