Thursday, 16 March 2017

C Program to Compare two Strings without using strcmp() function

C program to compare two strings without using strcmp() function is given below. Approach is simple, fist we will input the both strings and then we traverse both strings simultaneously character by character if every character of both the strings are equal till the end then strings are equal  otherwise not.

Program:
#include <stdio.h>
#include <string.h>
#define MAX 100
int main()
{
       char string1[100],string2[100];
       int i,count1,count2,j,flag;

       printf("\nEnter the string 1: ");
       scanf("%s",string1);
       printf("\nEnter the string 2: ");
       scanf("%s",string2);

    
       i=0;
       while(string1[i]!='\0' && string2[i]!='\0')
       {
             if(string1[i]==string2[i])
             {
                     flag=0;
                     i++;
                     continue;
             }
             else if(string1[i]>string2[i])
             {
                     flag=1;
                     break;
             }
             else
             {
                     flag=-1;
                     break;
             }
             
    }

    if(flag==0)
    {
           printf("\nStrings are equal");
           printf("\n");
    }
    else if(flag==1)
    {
           printf("\nString 1 is greater than string 2");
           printf("\n");
    }
    else if(flag==-1)
    {
           printf("\nString 2 is greater than string 1");
           printf("\n");
    }
    return 0;
} 


OUTPUT:

 


EmoticonEmoticon