C Programming - Library Functions - Discussion

1. 

What will be the output of the program?

#include<stdio.h>

int main()
{
    int i;
    i = printf("How r u\n");
    i = printf("%d\n", i);
    printf("%d\n", i);
    return 0;
}

[A]. How r u
7
2
[B]. How r u
8
2
[C]. How r u
1
1
[D]. Error: cannot assign printf to variable

Answer: Option B

Explanation:

In the program, printf() returns the number of charecters printed on the console

i = printf("How r u\n"); This line prints "How r u" with a new line character and returns the length of string printed then assign it to variable i.
So i = 8 (length of '\n' is 1).

i = printf("%d\n", i); In the previous step the value of i is 8. So it prints "8" with a new line character and returns the length of string printed then assign it to variable i. So i = 2 (length of '\n' is 1).

printf("%d\n", i); In the previous step the value of i is 2. So it prints "2".


Archana said: (Mar 17, 2011)  
In the above question the string "How are u" length is 7 only.

How are you saying it is 8 ?

Chintoo said: (Jun 8, 2011)  
'/n' at the end of the statement....

Balamithra said: (Jul 6, 2011)  
Hey how did you get 2?

Jyoti said: (Sep 13, 2011)  
Since len(8)+len(\n)=1+1=2

Sonu said: (Oct 9, 2011)  
Please explain me in detail that how to count string length?

Safi said: (Dec 31, 2011)  
Here there are three printf functions so o/p will be different three terms.
lets start.....

i = printf("How r u\n");
will give directly How r u
store at integer variable i but due to i is an integer data type of thus ..it store as integer will be in no. of character along with \n character .
Therefor result of 2nd printf function will print "8".

Now 3rd printf function will print as "2" by calculating len(8)+len(\n)=1+1=2

Here len(8)=taking previously i=8 and len(\n) containing in 2nd printf function.

Think you got it.

Apexa said: (May 19, 2014)  
Hey please me in details I'm confuse. How count the string length?

Asha said: (Aug 14, 2014)  
Why we are declaring i=printf ?

Arun said: (Nov 5, 2014)  
In 32 bit Linux platform.

The got output as:

How are you
11
3

Venkataramana said: (Oct 5, 2015)  
Sir I got output in dos box output:

How are you?

12.
3.

Bhargavi said: (Jan 17, 2016)  
It is not executing only.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.