Finding Which String Is Greater


Explanation

In C language, strings can be compared with each other using the strcmp() function. This function compares two strings alphabetically and returns a value based on the comparison result.

In this program, the user enters two strings. The strcmp() function compares both strings. If the first string is greater than the second string, it displays that the first string is greater; otherwise, it displays that the second string is greater.

How It Works?

  • Step 1: Declare two character arrays str1 and str2 to store strings.
  • Step 2: Accept the first string and second string from the user.
  • Step 3: Compare both strings using the strcmp() function.
  • Step 4: Store the comparison result in integer variable k.
  • Step 5: If k > 0, then the first string is greater.
  • Step 6: Otherwise, the second string is greater.

Example Program


#include <stdio.h>
#include <conio.h>
#include <string.h>

main()
{

    char str1[20], str2[20];

    int k;

    clrscr();

    printf("Enter First String : ");

    scanf("%s", str1);

    printf("\nEnter Second String : ");

    scanf("%s", str2);

    k = strcmp(str1, str2);

    if(k > 0)
    {

        printf("\nFirst String is greater");

    }

    else
    {

        printf("\nSecond String is greater");

    }

    getch();

}

Output

Enter First String : Apple

Enter Second String : Mango

Second String is greater

Practice Exercises

Task 1: Write a C program to accept two strings from the user and check which string is smaller or greater using the strcmp() function.

Goal: Learn how to compare two strings using the strcmp() function and understand the comparison result.

💡 Hint: Declare two character arrays to store strings. Use strcmp() to compare both strings. If the returned value is less than 0, the first string is smaller; otherwise, the second string is smaller.
💡 Show Solution

#include <stdio.h>
#include <conio.h>
#include <string.h>

main()
{

    char str1[20], str2[20];

    int k;

    clrscr();

    printf("Enter First String : ");

    scanf("%s", str1);

    printf("\nEnter Second String : ");

    scanf("%s", str2);

    k = strcmp(str1, str2);

    if(k < 0)
    {

        printf("\nFirst String is Smaller");

    }

    else
    {

        printf("\nSecond String is Smaller");

    }

    getch();

}

Output
Enter First String : Apple

Enter Second String : Mango

First String is Smaller
Explanation: The program accepts two strings and compares them using the strcmp() function. If the return value is less than 0, the first string comes before the second string alphabetically. Otherwise, the second string is smaller.