C Program to Compare Two Strings
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100];
// Getting strings from the user
printf("Enter the first string: ");
gets(str1);
printf("Enter the second string: ");
gets(str2);
// Compare the strings
int result = strcmp(str1, str2);
// Check the result of comparison
if (result == 0) {
printf("The strings are identical.\n");
} else {
printf("The strings are different.\n");
}
return 0;
}
Explanation:
Header Files:
#include <stdio.h>
: This is needed for input/output functions likeprintf()
andgets()
.#include <string.h>
: This library includes thestrcmp()
function, which is used to compare two strings.
Main Function:
- Two character arrays
str1
andstr2
are defined to store the strings entered by the user. The size of these arrays is set to 100 characters, but you can adjust this as needed. - The
gets()
function is used to take user input for both strings. - The
strcmp()
function compares the two strings. If both strings are identical, it returns0
. If they differ, it returns a non-zero value (positive or negative based on lexicographical comparison).
- Two character arrays
Comparison Logic:
- If the result of
strcmp()
is0
, the strings are considered identical, and the program prints that they are identical. - Otherwise, the program prints that the strings are different.
- If the result of
Program Output
Input:
Enter the first string: hello
Enter the second string: hello
Output:
The strings are identical.
Sample 2:
Input:
Enter the first string: apple
Enter the second string: banana
Output:
The strings are different.
Sample 3:
Input:
Enter the first string: C programming
Enter the second string: C Programming
Output:
The strings are different.
Explanation of Inputs and Outputs:
- In Sample 1, both strings “hello” are exactly the same, so the output is “The strings are identical.”
- In Sample 2, “apple” and “banana” are different, so the output is “The strings are different.”
- In Sample 3, the two strings differ in case sensitivity (“C programming” vs. “C Programming”), hence the output shows that they are different.
Last updated on