C Programming - Input / Output - Discussion

3. 

Will the following program work?

#include<stdio.h>

int main()
{
    int n=5;
    printf("n=%*d\n", n, n);
    return 0;
}

[A]. Yes
[B]. No

Answer: Option A

Explanation:

It prints n=    5

Bambi said: (Feb 18, 2011)  
What is the significance of '*' in this ?

Vivek said: (Jul 21, 2011)  
How it works? Please explain.

Madhusudan said: (Jul 26, 2011)  
'*' will provide 4 spaces in between 'n=' and 5.

Rozario Selvanathan said: (Dec 1, 2011)  
Anyone please make it clear...

Veena said: (Feb 7, 2012)  
I thought here two n's are not required. Please any one can explain.

Lakshmidevi said: (Feb 11, 2012)  
Using * means it skips one variable, so only one n value is taken and another n value is ignored.

Nandhu said: (Jun 10, 2012)  
Please anybody can explain this.

Medha said: (Oct 3, 2012)  
One n is ignored with 4 space because of '*'and another n value is taken.

Nitesh Khatri said: (Oct 18, 2012)  
#include<stdio.h>

int main()
{
int n=5,l=9;
printf("n=%*d\n", n, l);
return 0;
}

What @Medha said is correct, '*' will ignore the first variable and will print the value of l
Try to run this program, all confusion will be cleared.

Sunitha said: (Dec 6, 2012)  
Here in printf("n=%*d\n", n, n);

("%*d",n,n) tells the compiler to skip the first n value.

Thus second n value gets printed.

Shashank said: (Apr 7, 2013)  
* means it specifies the width and gives those no.of spaces.

According to Nitesh's code whatever value you give to n, those many spaces are appended.

Vijeth said: (Aug 22, 2013)  
It is right justified to n. , if you use "%-*d" then it will be left justified. n can be any variable.

Ronak said: (Apr 22, 2014)  
#include<stdio.h>

int main()
{
int n=5,l=9;
printf("n=%*d\n", n, l);
return 0;
}

What vijeth said is correct, '*' will ignore the first variable and will print the value of l.
Try to run this program, all confusion will be cleared.

Ullesh Chavadi said: (Jun 24, 2014)  
#include<stdio.h>

int main()
{
int n=5,l=900,k=0;
printf("n=%*d\n", n, k,l);
return 0;
}

What about this?

Pg Srinu said: (Jul 7, 2014)  
I think exactly * will ignore first variable then k l printed.

Crystal said: (Dec 26, 2014)  
@All.

Try these:

int main()
{
int i=10,j=20,k=30,l=40;
printf("%*d",i);//prints garbage
printf("%*d",i,j,k,l);//prints 2nd integer
printf("%*d",k);//garbage
}

Dipikamore said: (Feb 17, 2017)  
@Ullesh.

#include<stdio.h>

int main()
{
int n=5,l=900,k=0;
printf("n=%*d\n", n, k,l);
return 0;
}

In this program, * will be replaced by the value of n & then next variable here is k will print. For l to print no access specifier. So it will not print anything.

Hero said: (Aug 19, 2017)  
Can anyone explain how many spaces were there in the answer?

Loper said: (Aug 30, 2017)  
* means 4 spaces.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.