retagged by
294 views
3 votes
3 votes

What will be the output of the following lines of code?

int i = 0;
int j = 0;
char *s = "ceded";
while (s[i] != '\0') {
    j = j + s[i] - 'b';
    i = i + 1;
}
printf("%d %d\n", i, j);
  1. $5\; 11$
  2. $4\; 16$
  3. $5\; 16$
  4. $4 \;11$
retagged by

2 Answers

0 votes
0 votes
Here S is a pointer which points to a starting character of the string  located in the read only section of the static memory. In the condition expression of the while loop s[0]!=’\0’ is true so it goes inside the while loop and j =0+s[0]-’b’ is evaluated. s[0] is ‘c’ and ‘c’-’b’ is 1 since its an expression so it gets promoted to its ascii value and the difference between these ascii value is 1.So j=1 and i also gets incremented by 1. In the next iteration, s[1]!=’\0’ is true so j=1+s[1]-’b’ is evaluated which gives j=1+’e’-’b’ which changes j value to 1+3=4 and i also gets incremented by 1 which evaluates to 2. In the next iteration s[2]!=’\0’ is true and new value of j becomes 6 in a similar way and i also gets incremented by 1 which evaluates it to 3. In the next iteration s[3]!=’\0’ which means that new value of j becomes 9 and i also becomes 4. In the next iteration s[4]!=’\0’ is true new value of j becomes 11 and i also gets incremented to 5. In the next iteration when while loop condition is checked it now becomes false and when printf statement is  executed i=5 and j=11 is printed.
0 votes
0 votes

Answer : A

In the given code:

The variable i counts the number of characters in the string until the null terminator \0.

The variable j accumulates the ASCII differences between the characters in the string and the character 'b'.

The string "ceded" has 5 characters, so i becomes 5.

For each character in the string, the ASCII value of the character is subtracted by the ASCII value of 'b' and added to j, hence j becomes 11.

Therefore, the output will be "5 11".

Answer:

Related questions