Ad space (banner)
๐Ÿ”งC Lessons
Lesson 22 / 68

Searching an Array (Looping with strcmp)

This lesson covers searching for a string in an array in C using strcmp, so you can check whether a target value is present. It's for anyone searching "C strcmp usage."

C has no mechanism for comparing strings directly with ==, so you compare them with the strcmp() function. strcmp() has a slightly unusual convention: it returns 0 when the strings match.

The example checks every element of the array in a for loop, updating a variable named found to 1 when the condition strcmp(fruits[i], "orange") == 0 is true. Using strcmp() instead of == is a characteristically C detail.

A common early mistake is using == to compare strings. Comparing with == compares a pointer's address, not the string's content, producing an unintended result.

In real projects, this search is used constantly to check whether a specific product ID or username is present in a list.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)