C Format Specifier

Programming languages or concepts
0

C Format Specifier:


    The format specifiers are used in C for input and output purposes. Using this concept the compiler can understand that what type of data is in a variable during taking input using the scanf() function and printing using printf() function. Here is a list of format specifiers.
    The Format specifier is a string used in the formatted input and output functions. The format string determines the format of the input and output. The format string always starts with a '%' character.

The commonly used format specifiers in printf() function are:

 

Format specifier

 

Description

%u

                It is used to print the unsigned integer value where the unsigned integer means that the variable can hold only positive value.

%d or %i

It is used to print the signed integer value where signed integer means that the variable can hold both positive and negative values.

%x

                a hexadecimal (base 16) integer

%o

It is used to print the octal unsigned integer where octal integer value always starts with a 0 value.

%X

It is used to print the hexadecimal unsigned integer, but %X prints the alphabetical characters in uppercase such as A, B, C, etc.

%hi

short (signed)

%hu

short (unsigned)

%Lf

long double

%n

prints nothing

%i

a decimal integer (detects the base automatically)

%p

an address (or pointer)

%e

a floating point number in scientific notation

 

Let's understand the format specifiers in detail through an example.


%d:

we are printing the integer value of b and c by using the %d specifier.

int main()
{
  int a=60;
  int b=10;
  printf("Value of b is:%d", b);
  printf("\nValue of c is:%d",c);

    return 0;
}

%u:

we are displaying the value of b and c by using an unsigned format specifier, i.e., %u. The value of b is positive, so %u specifier prints the exact value of b, but it does not print the value of c as c contains the negative value.

int main()
{
  int a=20;
  int b= -80;
  printf("Value of b is:%u", b);
  printf("\nValue of c is:%u",c);

    return 0;
}

%x and %X:

y contains the hexadecimal value 'A'. We display the hexadecimal value of y in two formats. We use %x and %X to print the hexadecimal value where %x displays the value in small letters, i.e., 'a' and %X displays the value in a capital letter

int main()
{
  int y=0xA;
  printf("Hexadecimal value of y is: %x", y);
  printf("\nHexadecimal value of y is: %X",y);
  printf("\nInteger value of y is: %d",y);
    return 0;
}


%f:

The above code prints the floating value of y.

int main()
{
  float y=22.7;
  printf("Floating point value of y is: %f", y);
  return 0;
}


Post a Comment

0Comments

Post a Comment (0)
close