C Program to Compare Two Strings Using strcmp

cprogramming-Logo
C Programming Examples
C String Programs
C Loop Programs
C Function Programs
C Array Programs
C Integer Number Programs
C File I/O Programs

This C program is used to compare two strings by using strcmp() function.

strcmp() function compares two strings lexicographically, and it's declared in stdio.h.

Case 1: when the strings are equal, it returns zero.
Case 2: when the strings are unequal, it returns the difference between ascii values of the characters that differ.
a) When string1 is greater than string2, it returns positive value.
b) When string1 is lesser than string2, it returns negative value.

Syntax:
int strcmp (const char *s1, const char *s2);
Program:
#include<stdio.h>
#include<string.h>

int main()
{
    char a[100], b[100];    
    printf("Enter the first string\n");    
    gets(a);    

    printf("Enter the second string\n");    
    gets(b);
    
    if( strcmp(a,b) == 0 )
        printf("Entered strings are equal.\n");
    else
        printf("Entered strings are not equal.\n");
        return 0;
}
Program Output:

compare-strings-c

Explanation:

This program is used to compare whether two given strings are equal or not using a predefined function strcmp(). So first of all, you have to include the stdio header file using the "include" preceding # which tells that the header file needs to be process before compilation, hence named preprocessor directive. Also, you have to include the string.h header file. The string.h header classifies one variable type, one macro, and various functions to manipulate arrays of characters within your program.

Then you have to define the main() function and it has been declared as an int as it is going to return an integer type value at the end of the program. The inside the main() function, you have to take two character arrays name as a[] and b[] having 100 consecutive memory location in both. You have to use the printf() function to display a message - "Enter the first string" to the screen.

The statement gets(a); will fetch a set of characters the form of a string and store them in the array a[]. Similarly, the second string will also get fetched from the keyboard and stored in character array b[]. Now the next is the 'if' statement which will check the condition whether the values of the array a[] is and the values of array b[] after using strcmp() function gives the result as 0 or not. If yes, then the printf() will display "Entered strings are equal" otherwise display "Entered strings are not equal." The strcmp() returns the following:

  • when Return value < 0, indicates that str1 is less than str2.
  • when Return value > 0, indicates that str2 is less than str1.
  • when Return value = 0, indicates that str1 is equal to str2.

And lastly the return 0; statement is used to return an integer type value back to main().


Scroll Back to Top