Complementary task for topic: 5
M Nemeth · 2023-08-29 15:21:04.620218'
Simple strings: Comparison
Simple strings: Comparison
Write a C program that uses scanf() to read two strings from the user and then compares them to check if they are equal or not. Display an appropriate message based on the comparison result. You should compare the strings character by character.
Hint: Strings are closed with '\0' character (End-of-String) and it is a char array. You can compare till any of the strings reaches the end. Watch out, if the strings are the same, the end of strings must be at the same place! E.g.: "Apple" and Apple tree" are not the same strings!
Solution
#include
int main() {
char str1[100], str2[100];
int i = 0, areEqual = 1;
printf("Enter the first string: ");
scanf("%99s", str1); // Read the first string
printf("Enter the second string: ");
scanf("%99s", str2); // Read the second string
// Compare the strings character by character
while (str1[i] != '\0' || str2[i] != '\0') {
if (str1[i] != str2[i]) {
areEqual = 0;
break;
}
i++;
}
if(str1[i]!=str2[i]) //i is set to the end of the shorther string!
areEqual=0;
// Display the result
if (areEqual) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
return 0;
}
Explanation
Explanation: The program uses a char array str to store the input string. The user is prompted to enter a string using printf(). The string is read using scanf() with the %[^\n] format specifier, allowing the input to include spaces. The length of the string is calculated by iterating through the characters in the str array until the null terminator (\0) is encountered.