Free programming examples and instructions

C program to compare length of two string using 'strcmp()' function

Code: C program to compare the length of two string using strcmp() function

by Krishna viswambharan

Posted on 27 Sep 2017 Category: C Views: 614

Edited on 30 Oct 2017

C program to study 'strcmp()' function

In the last article, we have seen the use of the strlen() function. Now we will see how to compare two strings using the ‘strcmp()’ string function. This string function is defined in the <string.h> header file

The syntax is given as:

int strcmp(const char *string1, const char *string2 );

The strcmp() function compares two strings and returns 0 if both strings are identical. Character by character comparison is performed here. This comparison repeats until the corresponding characters of two strings are different or a null character '\0' is reached.

#include <stdio.h>
#include <conio.h>
#include <string.h>
void main()
    char a[50],b[50];
    printf(“enter the first string :”);
    gets(a);  //read string 1

    printf(“enter the second string :”);
    gets(b);  //read string 2

    if(strcmp(a,b)==0)   //compare strings
           printf(“\tEntered strings are equal”);
           printf(“\tEntered strings are not equal”);

Above program run successfully and output obtained is given below.


Leave a Comment: