In this program, we are going to share a C program to accepts two strings and compare. If you are a beginner and want to start learning the C programming, then keep your close attention in this tutorial as I am going to share a C program to compare two strings with the output.
We have designed this program for beginners for learning purpose. Copy below c program and execute it with c compiler to see the output of the program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
#include <stdio.h> void main() { int count1 = 0, count2 = 0, flag = 0, i; char string1[10], string2[10]; printf("Enter a string:"); gets(string1); printf("Enter another string:"); gets(string2); while (string1[count1] != '\0') count1++; while (string2[count2] != '\0') count2++; i = 0; while ((i < count1) && (i < count2)) { if (string1[i] == string2[i]) { i++; continue; } if (string1[i] < string2[i]) { flag = -1; break; } if (string1[i] > string2[i]) { flag = 1; break; } } 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); } |
Enter a string: hello
Enter another string: world
String1 is less than string2
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.