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");

Answer: A. str1 is greaterThe strcmp() function compares two strings lexicographically, character by character, starting from the first position. It compares the ASCII values of the…

  1. A.

    str1 is greater

  2. B.

    str2 is greater

  3. C.

    Equal strings

  4. D.

    Compilation error

Attempted by 129 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".

Explore the full course: C Language

Loading lesson…