This is C program which accepts two strings & compare them.
This program accepts two strings as input and compares them.
1. Take two strings as input.
2. Compare the two strings and display the result whether both are equal, or first string is greater than the second or the first string is less than the second string
Here is source code of the C program to accepts two strings & compare them. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
int count1 = 0, count2 = 0, flag = 0, i;
char string1, string2;
printf("Enter a string:");
printf("Enter another string:");
/* Count the number of characters in string1 */
while (string1[count1] != '\0')
/* Count the number of characters in string2 */
while (string2[count2] != '\0')
i = 0;
while ((i < count1) && (i < count2))
if (string1[i] == string2[i])
if (string1[i] < string2[i])
flag = -1;
if (string1[i] > string2[i])
flag = 1;
if (flag == 0)
printf("Both strings are equal \n");
if (flag == 1)
printf("String1 is greater than string2 \n", string1, string2);
if (flag == -1)
printf("String1 is less than string2 \n", string1, string2);
1. Take two strings as input and store them in the arrays string1 and string2 respectively.
2. Count the number of characters in both the arrays and store the result in the variables count1 and count2.
3. Compare each character of the strings. If both the strings are equal then assign variable flag to zero or if string1 is greater than string2 then assign 1 to variable flag and break or if string1 is lesser than string2 then assign -1 to variable flag and break.
4. Print the output according to value of variable flag.
Enter a string: hello Enter another string: world String1 is less than string2 Enter a string:object Enter another string:class String1 is greater than string2 Enter a string:object Enter another string:object Both strings are equal
Sanfoundry Global Education & Learning Series – 1000 C Programs.