C program to compare two strings

This program will ask for two different strings from the users. We will be using the string function strcmp() here to conclude the result on the by comparing the different strings entered by the user. You need to have a priori knowledge of the following topics to understand this example in more detail.

Now see the code below.

Code:

#include<stdio.h>
#include<string.h>
int main()
{
	int i;
	char n1[100], n2[100];
	puts("Enter first string");
	gets(n1);
	puts("Enter second string");
	gets(n2);
	i=strcmp(n2, n1);
	if(i == 0)
	{
		puts("Both strings are same.");
	}
	else
	puts("The strings are different");
}

Output:

Enter first string
Program
Enter second string
program
The strings are different

In the above program, the values of the strings are different. As C language is the case sensitive language the strings “Program” and “program” are different. So with the function strcmp() the difference is tracked and the result is printed. strcmp() function will compare the strings character by character until there is a mismatch in the string.

SHARE C program to compare two strings

You may also like...

Leave a Reply

Your email address will not be published.

Share