C

C Format Specifier – The Most Detailed

In C, a format specifier is a String that begins with the ‘%’ symbol and specifies the type of data that is being printed with printf() or read with scanf() ().
As an example: The%d in the following statement is a format specifier that indicates that the variable num’s data type is int.

printf("%d", num);

Specifier of Format

SPECIFIER DESCRIPTION
%c It is used for unsigned character
%s It is used for strings
%d It is used for signed integer, which means it can hold positive as well as negative integers.
%f It is used for floating point values such as 16.5, 19.67 etc.
%Lf long double
%hi signed short
%hu unsigned short
%i a decimal integer (detects the base automatically)
%o Used for octal numbers
%x Used for hexadecimal integer
%p an address (or pointer)
%u int unsigned decimal
%e a floating point number in scientific notation. It is also known as Mantissa or Exponent.
%E same as %e

Character format specifier%c as an example

#include <stdio.h>
int main() {
  char ch = 'A';
  char ch2 = 'r';
  printf("Lower case character: %c",ch);
  printf("\nUpper case character: %c",ch2);
  return 0;
}

%s is an example of a string format specifier.

#include <stdio.h>
int main() {
  char str[20];
  printf("Enter a String: ");
  scanf("%s", str);
  printf("User Entered: %s", str);
  return 0;
}

Specify the integer format%d

Here, we take the user’s input and display the same number as output. Because the user is being asked to enter an integer number, the %d specifier is being used. When printing the input number, the same%d specifier is used.

#include <stdio.h>
int main() {
  int number;
  printf("Enter a Number: ");
  //%d format specifier for integer
  scanf("%d", &number);
  printf("Number entered by user: %d", number);
  return 0;
}

Float format specifier%f

We are using the %f format specifier to print the number value with decimal points.

#include <stdio.h>
int main() {
  float number =15.55;
  printf("%f",number);
  return 0;
}

Output:

15.550000

Specify the octal format%o

To convert a decimal value to an octal value, we use the octal format specifier%o. We simply used the format specifier%o in the following example to print the octal equivalent value of the given decimal number.

#include <stdio.h>
int main() {
  int num = 45;
  printf("Octal equivalent of int %d is: %o", num, num);
  return 0;
}

Specifier of hexadecimal format%x

This is similar to the previous example. In this example, format specifier%x is used to print the hexadecimal value of a given decimal number.

#include <stdio.h>
int main() {
  int num = 45;
  printf("Hexadecimal equivalent of int %d is: %x", num, num);
  return 0;
}

 

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button