Skip to main content

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)

All Computer Programming chapter 7 questions →