Adsense 728 * 15

Search

Custom Search

C Program to Compare Two Strings Using strcmp() Function

Write a c program to compare two strings using strcmp() function. In this tutorial, we are going to write a c code which take two strings as an input and compare it with inbuilt strcmp() function.

The strcmp() function compares two strings lexicographically.

i) When both the strings are equal,  then it returns zero.

ii) When first string is lexicographically greater than second string, it returns positive value.

iii) When first string is lexicographically lesser than second string, it returns negative value.

C program to check whether two strings are anagrams of each other

C program to find length of a string without using strlen


C Program to Compare Two Strings Using strcmp() Function


C Program to Compare Two Strings Using strcmp() Function


In this programming question, Let's first take two input strings from a user and then use the inbuilt strcmp() function to compare two strings.


#include <stdio.h>

int main(void) {
    
   char str1[100], str2[100];
 
   printf("Enter a first string\n");
   gets(str1);
 
   printf("Enter a second string\n");
   gets(str2);
 
   // If string is equal it returns zero
   if( strcmp(str1, str2) == 0 ) {
      printf("Both strings are equal.\n");
   
   } else if( strcmp(str1, str2) < 0) {
      printf("Str1 is lexicographically smaller than str2 \n");
      
   } else {
         printf("Str1 is lexicographically greater than str2 \n");
   }
      
    return 0;
}


Output:

Enter a first string
c

Enter a second string
programming

Str1 is lexicographically smaller than str2


Programming questions on strings

C program to check whether a number is palindrome or not

Java programming questions

No comments:

Post a Comment