C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Compare two strings using pointers

C Program: Compare two strings using pointers

C

#include <stdio.h>

 

int main() {

    char str1[100], str2[100];

    char *ptr1, *ptr2;

    int flag = 0;

 

    // Input two strings

    printf("Enter first string: ");

    fgets(str1, sizeof(str1), stdin);

    printf("Enter second string: ");

    fgets(str2, sizeof(str2), stdin);

 

    // Initialize pointers

    ptr1 = str1;

    ptr2 = str2;

 

    // Compare character by character

    while (*ptr1 != '\0' && *ptr2 != '\0') {

        if (*ptr1 != *ptr2) {

            flag = 1;

            break;

        }

        ptr1++;

        ptr2++;

    }

 

    // If lengths differ

    if (*ptr1 != *ptr2) {

        flag = 1;

    }

 

    // Display result

    if (flag == 0)

        printf("Strings are equal.\n");

    else

        printf("Strings are not equal.\n");

 

    return 0;

}

Output

 
OUTPUT 1 :
Enter first string: Hello
Enter second string: Hello
Strings are equal.

OUTPUT 2 :
Enter first string: ITDeveloper
Enter second string: ITDevelopers
Strings are not equal.


Explanation

  • The program uses two pointers (ptr1 and ptr2) to traverse both strings.
  • Each character is compared one by one.
  • If a mismatch is found or the lengths differ, flag is set.
  • Finally, the program prints whether the strings are equal or not.