Write a C Program to Compare Two Strings without using strcmp function. There are multiple ways to compare two string in C programming. However, we will discuss three different approaches: using For Loop, While Loop, and Functions in C Programming.
C Program to Compare Two Strings without using strcmp
This program allows the user to enter two string values or two-character array. Next, this compare strings program will use For Loop to iterate every character present in that string and compares individual characters. I suggest you refer to strcmp function.
/* C program to Compare Two Strings without using strcmp() */ #include <stdio.h> #include <string.h> int main() { char Str1[100], Str2[100]; int result, i; printf("\n Please Enter the First String : "); gets(Str1); printf("\n Please Enter the Second String : "); gets(Str2); for(i = 0; Str1[i] == Str2[i] && Str1[i] == '\0'; i++); if(Str1[i] < Str2[i]) { printf("\n str1 is Less than str2"); } else if(Str1[i] > Str2[i]) { printf("\n str2 is Less than str1"); } else { printf("\n str1 is Equal to str2"); } return 0; }

Let me insert two different strings

two more different strings

Program to Compare Two Strings Using While Loop
This program is the same as above, but this time we are using a While loop. We replaced the For Loop in the above example with While Loop. I suggest you refer to While Loop to understand the C Programming loop Iteration.
/* C program to Compare Two Strings without using library function */ #include <stdio.h> #include <string.h> int main() { char Str1[100], Str2[100]; int result, i; i = 0; printf("\n Please Enter the First String : "); gets(Str1); printf("\n Please Enter the Second String : "); gets(Str2); while(Str1[i] == Str2[i] && Str1[i] == '\0') i++; if(Str1[i] < Str2[i]) { printf("\n str1 is Less than str2"); } else if(Str1[i] > Str2[i]) { printf("\n str2 is Less than str1"); } else { printf("\n str1 is Equal to str2"); } return 0; }

Program to Compare Two Strings Using Functions
This C program is the same as the above example. However, this time, we are using the Functions concept to separate the logic from the main program.
As you can see, we created a function compare_strings to compare the strings. Next, we are calling that function inside our main function.
/* C program to Compare Two Strings without using library function */ #include <stdio.h> #include <string.h> int Compare_Strings(char *Str1, char *Str2); int main() { char Str1[100], Str2[100]; int result; printf("\n Please Enter the First String : "); gets(Str1); printf("\n Please Enter the Second String : "); gets(Str2); result = Compare_Strings(Str1, Str2); if(result < 0) { printf("\n str1 is Less than str2"); } else if(result > 0) { printf("\n str2 is Less than str1"); } else { printf("\n str1 is Equal to str2"); } return 0; } int Compare_Strings(char *Str1, char *Str2) { int i = 0; while(Str1[i] == Str2[i]) { if(Str1[i] == '\0' && Str2[i] == '\0') break; i++; } return Str1[i] - Str2[i]; }
