Conversion Specifications

Conversion Specifications

Published by: Nuru

Published date: 21 Jun 2021

Conversion Specifications Photo

Conversion Specifications

  • Displaying the value of program variables in the screen is a little more complicated than displaying only a message.
  • Conversion Specification helps to display the value of program variables in screen in C programming.
  • For example, if we have to display the value of an integer variable x in the screen, we can write as follows:

                                  printf("The value of x is %d", x);

  • Assume that value at variable x is 15 then the above statements display as:

The value of x is 15.

  • In the above statement, %d is called the conversion specification used for the value of integer variable to be printed at that position.

Conversion Specifications

The % Format Specifiers

 

Format Usual Variable type Display
%c char single character
%d (%i) int signed integer
%e (%E) float or double exponential format
%f float or double signed decimal
%g (%G) float or double use %f or %e as required
%o int unsigned octal value
%p pointer address stored in pointer
%s array of char sequence of characters(string)
%u int unsigned decimal
%x (%X) int unsigned hex value

A program to display value with format specifier

/*program */
#include
int main()
{
int x=10;
float f=3.56;
char ch=‘X’;
printf("Decimal NO x =%d",x);
printf("\n Octal No x = %o",x);
printf("\nHex NO x= %X",x);
printf("\nFloat No f= %G",f);
printf("\nFloat NO f =%f",f);
printf("\nFloat No f =%E",f);
printf("\nSingle Char ch = %c“,ch);
printf("\nString : %s","C-Program");
return 0;
}

Output

Decimal NO x = 10
Octal No x = 12
Hex NO x = A
Float No f = 3.56
Float NO f = 3.560000
Float No f = 3.560000E+000
Single Char ch = X
String: C-Program
--------------------------------

Bonus Topic:

Displaying strings in screen

The two most frequently used ways to display text strings is to use C's library functions printf() and puts().

  • The printf() Function

The printf() function, part of the standard C library, is perhaps the most versatile way for a program to display data on-screen.

  • Printing a text message on-screen is simple. Call the printf() function, passing the desired message enclosed in double quotation marks. For example,

printf("An error has occurred!");

Displays: An error has occurred!

  • Similarly, puts() functions can also be used to display string in screen as:

                                puts(“An error has occurred!”);

  • printf() function is used to display the values of variables, constants with formatting, but puts only prints text string in screen.