Thursday, 29 June 2017

Can we display "Hello World" without using a semicolon in C ?

Well the answer is YES!. But to understand this we need to cover some basics of ‘function’.
Don’t worry I am not going to explain the basics of function. As I assume you know it. I am sure you are also familiar with the term “return” which is frequently used inside the function. We also know that every function must return a value. This statement is the key to solve this puzzle. Yes you heard it right. Having said that, Lets understand what kind of values are returned by most frequently used functions? For example, printf()

Whenever we use printf() function, what we expect is the Output display on the screen. We hardly care about what kind of value does it returns. Let’s check it out.

main()
{
int valueReturned = 0;
valueReturned = printf(“Welcome to Programming!”);
printf(“\n %d”, valueReturned);

}

What do you think will be the output? “Welcome to Programming!” is going to be displayed on the screen for sure. But I am interested in the value of the variable named, valueReturned. If you run this program in any C compiler it would show the output as given below
                      Welcome to Programming!
                      23
Well, This 23 is nothing but the length of the string enclosed within the double quotes which we usually see on the screen. Which means, something like printf(“%d”, printf(“Hello World”)); will give an output like “Hello World11”. Further, to enhance your learning, you should check the output for the statements like
printf(“%d”, printf(“\n Hello World”)); printf(“%d”, printf(“\t Hello World”)); etc. to understand whether '\n' counts as 0, 1 or 2 characters?

Now if you have understood this, we are half done. Next thing which we need to understand to solve this puzzle is the conditional statement “if()”. Relax! I am not going to start talking about the basic functionality of the “if” keyword here. I assume you guys know this. What I wanted to discuss here is, in the if() section, Some people think that, if you pass 1 and 0 it is evaluated as True and false respectively. In fact, Any Non Zero value passed inside any conditional statement evaluates to true in C language. For example, you must have seen the example of infinite loop in most of the text books is written as “while(1){}”.

We are done with theory part of the puzzle, now it’s time to write the code.

main()
{
    if(printf(“Hello World”))
       {
       }
}

If you run this program, It will not throw any compilation error and will display the text
Hello World” on your screen.




No comments:

Post a Comment