by Dinesh Thakur Category: Function and Pointer

There are several format Specifiers available in printf. The format specifier used varies depending on the data type used for printing. The given below are some of the format Specifiers used with printf in C program.

For integer data type the format specifier used with printf is %d or %i

For float data type the format specifier used with printf is %f

For double data type the format specifier used with printf is %lf

For char data type the format specifier used with printf is %c

For string data type the format specifier used with printf is %s

Apart from this the other format Specifiers used with printf are

For displaying a number in scientific notation %e is used with printf.

To get the output in next line the new line character n is used with printf.

To get a % sign in output the used symbol along with printf is %%.

Thus format Specifiers are used based on data type and are used to get the output in desired format

Illustrates the application of printf () with different data types.

#include <stdio.h>

void main()

{

   int m = 10, n = 5;

   float f = 45.8;

   double F = 45.8;

   double D = 678.98765;

   char ch = 'A';

   clrscr();

   printf("%d\n", m); //Displays the value of m on monitor.

   printf("%d, %d\n",m,n); /*Displays values separated by a comma*/

   printf("%lf\n",D); //Displays value of D.

   printf("%d\t%d\n",m,n); /*Displays values separated by spaces.*/

   printf("%d,\t%f,\t%c\n",m, F, ch);

   /*Displays values of m,F,ch separated by a comma and few spaces.*/

   printf("m = %d\nf = %f\tch = %c\n",m, f, ch);

}

What are the Format Specifiers used with printf

The comments given along the code in the program are meant to help the readers in understanding the output. The output displayed depends on the default settings of the computer. No field width or precision is specified by the user in the above program; however, these have been discussed below. Notice that for outputs of different types of data, different code letters (also called conversion characters) are required after the symbol% in the formatting string. For integers, the conversion character is d (i.e., the code is %d); for floating point numbers, the code is %f; for double numbers, the code is %lf; and for character values, the code is %c. If a real number is declared as float, it may get truncated resulting in an approximate value. (This can be observed in the value 45.8 which is stored after being declared as a float and then as a double. Compare the output in both cases.)



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.



Search Content







Popular Article