Dynamic Output in C

Dynamic output

consider the following program

 

 

#include<stdio.h>
int main()
{
long double a=3.14159265;
printf(“Value of pi=%.4Lf”,a);
return(1);
}

the output of the program will be

 

Value of pi=3.1416

wouldn’t it be nice if we allow the user to choose how the precession of the answer would be??
that is the output should be like this

 

Enter precision
6
The value of pi precised to 6 decimal number is 3.141593

Well in that case the program will be like this

 

#include<stdio.h>
int main()
{
long double a=3.14159265;
int pre;
printf(“Enter precision\n”);
scanf(“%d”,&pre);
printf(“The value of pi precised to %d decimal number is %.*Lf”,pre,pre,a);
return(1);
}

see the difference,it is upto the user to decide how the output will be.The value of pi will be rounded off to fit the precision .Such an output is called dynamic output.

This is the part of the program which is important

 

printf(“The value of pi precised to %d decimal number is %.*Lf”,pre,pre,a);

you can create a dynamic output by just specifing * before control string and specifying the variable having precesion in the arguments list.As you can see i have specified pre twice because one to print the The value of pi precesiced to__ and the other to suggest the compiler to fill the * with the value of pre.

This fact can not only be used to specify the precision of the decimal number but also for various other things.Some of them are

1.Printing first n characters of the given string

consider

printf(“The Output is %.*s”,pre,str);

suppose the string variable str has a string of “adithya” and the value of int datatype variable pre is 3 then the output will

 

The Output is adi

2.Justification
consider

 

printf(“The Output is %*.*f.Bye!”,just,pre,num);

suppose num(float)=1983.78
pre(int datatype variable)=2
just(int datatype variable)=25

then the output will be in the form of right justification i.e,

 

The Output is 1983.78.Bye!

suppose you want the output to be left justified then either you can specify ‘-*.*f’ or give a negative value to the variable ‘just’
suppose for the above example just=-25 then the output will be

 

Code:

The Output is 1983.78 .Bye!


You may also like

Find out what I am doing by following me on Twitter... Tweet This Post!

Here’s what they said...

  1. Rag

    - Aug 9th, 08

    gud work adi!
    and u have extreme C skills!!!!!!!
    its gud tht i got to know this site. keep posting articles which help me in my placements. thk u.

Leave a Reply

Comment on the next level:

- Enter your info on the left

- Create an avatar with Gravatar!