Quick links: C-Tricks HR Interview Que. Code Snippets C Programs C++ Programs Java Programs PHP Examples

Home » C programming language

Difference between %d and %i format specifier in C programming language.

Format specifier/ conversion characters

In c programming language, there are some set of characters preceded by % character, which define the type of input and output values, know as format specifiers/ conversion characters.

For example - if you want to read and print single character using scanf and printf function, %c is used.

Sponsored Links

Consider the following statements

char gender;
printf("Gender is: %c\n",gender);

Here %c is using in both statements scanf and printf, while reading values from the user, %c in scanf define that single character is going to be read, similarly %c in printf defines that only single character will be printed.

Difference between %d and %i format specifier?

%d and %i both are used to read and print integer values, still they have differences.

%d - Specifies signed decimal integer

%i - Specifies integer

%d and %i as output specifiers

Both specifiers are same if they are using as output specifiers, printf function will print the same value either %d or %i is used.

Consider the following example

#include <stdio.h>

int main()
	int a=6734;
	printf("value of \"a\" using %%d is= %d\n",a);
	printf("value of \"a\" using %%i is= %i\n",a);
	return 0;
        value of "a" using %d is= 6734
        value of "a" using %i is= 6734

%d and %i as Input specifiers

Both specifiers are different if they are using as input specifiers, scanf function will act differently based on %d and %i.

%d as input specifier

%d takes integer value as signed decimal integer i.e. it takes negative values along with positive values but values should be decimal.

%i as input specifier

%i takes integer value as integer value with decimal, hexadecimal or octal type.

To give value in hexadecimal format - value should be provided by preceding "0x" and value in octal format - value should be provided by preceding "0".

Consider the following example

#include <stdio.h>

int main()
	int a=0;
	int b=0;
	printf("Enter value of a: ");

	printf("Enter value of b: ");
	printf("a=%d, b=%d\n",a,b);
	return 0;
        Enter value of a: 2550
        Enter value of b: 0x2550
        a=2550, b=9552

In this example the entered value of a is 2550 (through %d format specifier) and the entered value of b is 0x2550 (through %i format specifier). Since 0x2550 is given to b which is scanning value through %i so it would be 9552 (which is the decimal value of 0x2550).


Solved programs

Sponsored Links

Most viewed pages

Featured posts
C Tips and Tricks