- 2073 Shrawan · 4 marks
Compare two strings with function
Short answer
The compare() function iterates while characters match and string not ended, returns difference of current characters (0 if equal). main() reads strings, calls compare, and prints 'equal' if returned 0 else 'not equal'.
Write a C program to read two strings in main and compare them using userdefined function. Display appropriate message from main.
Logic. The function compare() moves along both strings while the characters are equal and the first string has not ended. When it stops, the difference between the two current characters is returned: 0 means equal, a positive value means the first string is greater, and a negative value means smaller (like strcmp). main() reads the strings and displays the message.
#include <stdio.h>
/* returns 0 if equal, positive if a > b, negative if a < b */
int compare(char a[], char b[])
{
int i = 0;
while (a[i] != '\0' && a[i] == b[i])
i++;
return a[i] - b[i];
}
int main(void)
{
char s1[50], s2[50];
printf("Enter first string: ");
scanf("%49s", s1);
printf("Enter second string: ");
scanf("%49s", s2);
int r = compare(s1, s2);
if (r == 0)
printf("Strings are equal\n");
else
printf("Strings are not equal\n");
return 0;
}
Sample run
Input: nepal nepali
Enter first string: Enter second string: Strings are not equal
"nepal" and "nepali" differ at the end ('\0' against 'i'), so the strings are not equal.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Significance of main() function · Computer Programming, chapter 6
- Read records until end; show nth record · Computer Programming, chapter 10 · asked 2×
- Pass student array; display passed students · Computer Programming, chapter 7
- Function definition; sum of two numbers · Computer Programming, chapter 6
- GOTO types; sum of series program · Computer Programming, chapter 11
- Sort array using a function · Computer Programming, chapter 7
- Join two strings with dynamic constructor · Object Oriented Programming, chapter 4
- Compare TSI write/read modes · Telecommunications, chapter 4
- Steam main with two insulation layers: overall coefficients · Fundamental of Thermodynamics & Heat Transfer, chapter 7
- C program: sum of two 8-bit BCD numbers · Embedded System, chapter 9