Dynamic Output in C

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.141
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!

About This Blog

There is something for everyone. !! A tech blog on various topics. Let it be devops, programming etc; we have it all covered here in layman terms :)

Total Pageviews

Back to TOP