C – strcmp( ) function – Compare Strings

Strcmp() in C programming language is used to compare two strings. If both the strings are equal then it gives the result as zero but if not then it gives the numeric difference between the first non matching characters in the strings. Syntax of C strcmp() function is–


String1 and string2 may be string variables or string constants. Examples of c strcmp() function are –


This function is mainly used to compare whether the strings are equal or not. The value of the mismatch is rarely important. For example, the statement –


Will return the value of -9 which is numeric difference between ASCII “i” and ASCII “r”. That is, “i” minus “r” in ASCII code is -9. If the value is negative, string1 is alphabetically above string2.

C Program to check if the two strings are equal or not

/* Sample C program for the strcmp function*/

void main()
     char nm[20],nm2[20];
     puts("Enter a string - ");
     puts("Enter another string to know if both the strings are equal");
           printf("Both the strings are equal");
         printf("Strings are not equal");

Enter first string – hello
Enter second string – world
Case 2
First string – hello
second string – hello

Output –
String are not equal
Case 2 – Both strings are equal

yashan has written 69 articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>