C Program to Compare Two Strings Through User-Defined Function

Strings are another good feature of C. They provide a great way to store characters, not in really, in actual C Program stores the ASCII Values of characters that’s why there is no any non-numeric data-type in C. All in hidden, access and manipulate through numeric values. In other words, Strings are arrays of characters.  

There are many functions for strings and to compare two strings there is also strcmp(str1,str2); function. Which if the two strings are equal gives the value 0(zero) and otherwise return the ASCII value difference between first non-matching characters.

Lets do it with some trick to eliminate the variables and shorten the size of the program.

Lets Do It with the User-define Program ►►




void main()


char str1[20],char str2[20];

int i=0;

printf(“Enter the first String\n”);


printf(“Enter the second String\n”);



while(str1[i]!=NULL || str2[i]!=NULL)


                              if(str1[i]==str2[i])    ;



                              goto sos;





printf(“Strings are Same\n”);



sos :

printf(“Strings are Not Same\n”);



And we are done !!

What I do is first initialize the two strings using char data-type. Then simply enter them from keyboard using scanf statement. Look carefully the scanf(“%[^\n]s”,str1); statement. In this I use the [^\n] between the %s, it is to make scanf accept the multi-word string. That means you can enter as Ushaib Usmani in the string.

Then I conditioned while statement while(str1!=NULL || str2!=NULL). The OR operaotr ( || ) make sure to terminate the while statement only when both strings came to end. That make sure that every character of both strings will compare. 

Then if the strings are same the if statement do nothing and if strings are not same else part will be execute and the goto keyword take the control to the statements after the sos : and then program will exit.

Did you notice the numbers 1,2 (exit(1); , exit(2) in the parentheses of exit. These make abnormal exit. This is for know that from where the program is exit. You can know after the program is exit, go to the Compile option >> Information. You will find it there.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s