Sunday, April 05, 2009

Utility of printf() function & how it is used.

In the previous blogs we have learnt about the basic part of programming and we will move further with the different programming syntaxes and logical part of the programming. So, now let’s start with the printf() and scanf() functions.
printf() function is used to print any value or character or variable value on the screen.
Syntax of printf() function is as follows:
printf(“<format string>”, <list of variables>);


<format string> could be,
%f for printing real or float values
%d for printing integer values
%c for printing character values


Some of the examples of printf() functions are as follows,
printf(“%d”, i);         /* used to print integer value, where i is an integer type variable */
printf(“%f”, avg);         /* used to print float value, where avg is an float type variable */
printf(“%c”, k);         /* used to print character value, where k is an character type variable */
printf(“%d %f %c”, i, avg, k);      /* used to print different types of values at once */
printf(“Simple interest = Rs %.2f, \nwhere Principle = Rs %.2f, Rate = %d percent and Time = %d yr”, si, p, r, t);  /* used to print values along with a given statement, to make the output user friendly */
The output of the last statement is as follows:
Simple interest = Rs 10.00
where Principle =Rs 100.00, Rate = 5 percent and Time = 2 yr

The utility of ‘\n’ in printf() function is to take the cursor of the output to the next line or new line, where printing in new line is required, there before ‘\n’ is to be used.
And the utility of .2 within %f is to display the output up to 2 decimal figures. Generally float type variable itself shows 4 decimal places but while printing any currency value 2 decimal figures is appropriate, so .2 is to be placed in between %f to make the output up to 2 decimal figures.

No comments:

Post a Comment

Please give your valuable comments or queries if you fell its helpful or if you like the contents of the site. Thanks...