Write a program that reads two strings CH1 and CH2, compares them lexicographically and displays the result without using strcmp:
Example:
Enter the first string : ABC
Enter the second string: abc
"ABC" precedes "abc"
Difficulty level

Video recording
This exercise is mostly suitable for students
//Solution 1
#include<stdio.h>
#include<string.h>
#include<conio.h>
#define SIZE 50
void main()
{
char CH1[SIZE], CH2[SIZE];
int i, j;
printf("Enter the first string : ");
scanf("%s", CH1);
printf("Enter the second string : ");
scanf("%s", CH2);
for (i = 0; CH1[i] != '\0'; i++)
{
if (CH1[i] < CH2[i])
break;
if (CH2[i] < CH1[i])
break;
}
// CH1[i]=='\0' and CH2[i]=='\0' or CH2[i]==!!!!
// break
if (CH1[i] == '\0' && CH2[i] == '\0')
printf("\"%s\" is equal to \"%s\"\n", CH1, CH2);
else
if (CH1[i] == '\0' && CH2[i] != '\0')
printf("\"%s\" precedes \"%s\"\n", CH1, CH2);
else
if (CH1[i] < CH2[i])
printf("\"%s\" precedes \"%s\"\n", CH1, CH2);
else
if (CH2[i] < CH1[i])
printf("\"%s\" precedes \"%s\"\n", CH2, CH1);
getch();
}
//Solution 2
#include<stdio.h>
#include<string.h>
#include<conio.h>
#define SIZE 50
void main()
{
char CH1[SIZE], CH2[SIZE];
int i, j;
printf("Enter the first string : ");
scanf("%s", CH1);
printf("Enter the second string : ");
scanf("%s", CH2);
for (i = 0; CH1[i] == CH2[i] && CH1[i] != '\0' && CH1[2] != '\0'; i++)
;
if (CH1[i] == CH2[i])
printf("\"%s\" is equal to \"%s\"\n", CH1, CH2);
else
if (CH1[i] < CH2[i])
printf("\"%s\" precedes \"%s\"\n", CH1, CH2);
else
printf("\"%s\" precedes \"%s\"\n", CH2, CH1);
getch();
}
Back to the list of exercises
Looking for a more challenging exercise, try this one !!
