• edited by
1,537 views
5 5 votes

Consider the following program, what will be the output?

#include<stdio.h>

void main()
{

    int a;
    a = printf("2>5") > printf("2<5") ? printf("2")!=printf("20")?printf("GA"):printf("2022"):10?2!=2>5?!2?40:!2!=3?50:60:70:80;
    printf("%d",a);

}

Options:

  1. 50
  2. 60
  3. 70
  4. None of These

Answer: b. 50

3 Answers

Best answer
10 10 votes

So this is a question on nested ternary operator, grouping method is used to solve:

First check the number of question mark is equal to the number of colons in the given statement, the statement is valid only if they are equal, otherwise the statement is invalid.Here in the given statement “printf("2>5") > printf("2<5") ? printf("2")!=printf("20")?printf("GA"):printf("2022"):10?2!=2>5?!2?40:!2!=3?50:60:70:80” there are 6 each, hence the statement is a valid one.

Step 1: Start from left of the statement, match the first colon symbol you come across with its nearest question mark to its left as shown in the reference below: 

and do the same for the rest of the colon symbols in the statement.

Step 2: Consider the first sub-statement “printf("2>5") > printf("2<5")”, divide the statement according the matched colon to the question mark present in the considered sub-statement.

printf function returns the number of characters printed, so here both the printf will return 3 as there are 3 characters and also “2>52<5” gets printed.

similarly the next part of the statement is considered and solved as shown below:

So, a  is evaluated to 50.

Option A is the right answer.

• selected by
0 0 votes

Ans : 2>5 2<5 50 

Explanation : a =50 

use the brackets to each ternary operator to see how they will be evaluated.

Position:
Show:

Related questions

1 1 vote
1 1 answer
642
642 views
Rajender gill asked Dec 27, 2022
642 views
int fun(int arr[]); int fun(int arr ); Both the statements are same??? HELP
0 0 votes
0 0 answers
1.7k
1.7k views
Pranavpurkar asked Sep 27, 2022
1,717 views
Consider a string is stored in a word addressable memory where each word is of 4 Bytes. If the string starts at 100 and ends at 104 then which of the following can be the...
0 0 votes
0 0 answers
1.3k
1.3k views
Pranavpurkar asked Sep 27, 2022
1,280 views
Which of the following is/are true regarding the following code snippet?1:int *p;2:p = &q; A)*p gives faster retrieval of information than q.B)The size of p is same as si...
1 1 vote
3 answers 3 answers
1.8k
1.8k views
Sunnidhya Roy asked Dec 14, 2022
1,847 views
Given the following piece of code :Main(){Int child = fork();Int c = 5;if (child == 5){C + = 5;}Else{Child = fork();C + = 5;}}What are the different values of the variabl...