A puzzle and a logic behind - C and C++ programming

Hi Friends.

Today I am going to ask you the puzzle in 'C' programming. Of course I am going to explain the logic behind the puzzle.

I doubt that most of them know the answer or partial answer to the puzzle. But friends it gives me immense pleasure to share my knowledge with you all.

This question was asked by my professor. I have enhanced the question a bit and puzzling you.

Let get into the puzzle. Look at the picture below.

You have to update the if condition, so the program prints "Hello World" and numbers should Swap as
shown in the picture (I achieved this with one warning. You have to think on this, because it is a hint too).

One more hint friends, you can see the post "Swap in a single statement" in this blog.

So guys I hope some of them already figured out the answer or at least a part of answer. If you not yet don't worry let walk into the remaining post.

Explanation:

Whenever I think about IF condition in 'C' language, I always remember one small small thing about IF. This is the reason behind this puzzle.

Are you thinking what it is. Okay! I don't make you wait. It is IF condition executes the ELSE loop only when the condition or expression returns the value "ZERO" (0). Other than ZERO, IF statement returns TRUE.

And one more important thing is if statement executes all expressions in case of AND operation until it encounters FALSE (T && T && F && anything leads to FALSE). In case of OR operation if statement executes until it encounters TRUE (F || F|| T || anything leads to TRUE).

Note - Here FALSE means ZERO. TRUE means other than ZERO.

So, I have updated the IF condition with an EXPRESSION other than LOGICAL EXPRESSION.

Following are the two answers to the puzzle.

1. if(printf("Hello ",a=(a+b)-(b=a)))
2. if((printf("Hello ")) && (a=(a+b)-(b=a)))

You can use either of these.

In the first answer, it prints "Hello " and swap the values. The IF condition is not leading to ZERO. So the TRUE block will be executed.

In the second answer, it prints "Hello ". The first condition is TRUE (because not zero) and evaluates the second condition where it swaps the values and evaluates the TRUE block of IF statement.

Please comment if you have any questions or do you know any other way of achieving this puzzle.

Hope you enjoyed this article. Will meet in the next article. Karthik Byggari

Author & Editor

Computer Science graduate, Techie, Founder of logicallyproven, Love to Share and Read About pprogramming related things. 