Hello World!

Tuesday, August 31, 2010

It is a very commonplace question for technical interviews that tests your proficiency in C. The problem is quite well-known and so is its solution. The objective is to print two string literals say "Hello" and "World" using two printf statements where one printf should be a part of an if block and the other a part of its matching else. The most common solution is

if(!printf("Hello "))
{}
else printf("World");

Being aware that printf returns the number of characters printed on screen (in case of Hello, it is 5) which we negate using the logical operator ! to make the entire expression as 0 implying false and thus the else part is executed.

Now what if, you were restricted to use any of the logical operators for achieving the same job. Well, here's a solution. The most undermined comma (,) operator plays an interesting role in doing the job:

if(printf("Hello") , NULL) //we can even write 0 instead of NULL
{}
else printf("World");
Note in C, the comma operator has an interesting semantic. All expressions separated by comma's are evaluated from left-to-right however the value of the entire expression is the right-most expression. i.e a= (5+2,3+5,6*4); then a gets the value 24, though all the previous expressions are evaluted. Now using this feature, the if condition part is well explained.

If someone can come up with a more compact and cryptic solution to this, do post it here.

4 comments:

Anonymous said...

Hello Tanmoy,
Another solution can be to use goto statement.
if(printf("Hello"))
{goto L1;}
L1:else
{printf("World");}

Anonymous said...

hey rajdeep that's a tricky one. Hmm, this would work.

Anonymous said...

Rajdeep the simplest using relational operator would be

if(printf("Hello")<0)
else printf("World");

Anonymous said...

Win Exciting and Cool Prizes Everyday @ www.2vin.com, Everyone can win by answering simple questions.Earn points for referring your friends and exchange your points for cool gifts.

  © Blogger templates Newspaper by Ourblogtemplates.com 2008

Back to TOP