What will the following code output? char str1[] = "world"; char str2[] =…
20242024
What will the following code output?
char str1[] = "world";
char str2[] = "hello";
if(strcmp(str1, str2) > 0)
printf("str1 is greater");
else
printf("str2 is greater");
- A.
str1 is greater
- B.
str2 is greater
- C.
Equal strings
- D.
Compilation error
Attempted by 93 students.
Show answer & explanation
Correct answer: A
The strcmp() function compares two strings lexicographically, character by character, starting from the first position.
It compares the ASCII values of the characters at each position until it finds a difference or reaches the end of one string.
In this case, the first characters are 'w' from str1 and 'h' from str2.
Since 'w' has a higher ASCII value than 'h', the function returns a positive number.
The condition strcmp(str1, str2) > 0 evaluates to true, so the if block executes and prints "str1 is greater".