What is the difference between %d and %i

difference between %d and %i

What are %d and %i

Format specifiers are used in C programming for letting the compiler understand , the nature of the data that the programmer is working upon.

%d and %i are two such format specifiers which are used for working with integer data type.

Although both of them can be used for printing an integer value, but there is a slight difference between them, when they are used for accepting a value through scanf.

Difference in the use of %d and %i

Both %d and %i are used when we are working with integer data type, they both behave similarly while printing a integer value, but when they are used with scanf, for accepting a integer value, there is a slight difference in their property

  • While accepting a integer value %d simple takes the base of the value as 10(decimal).
  • But, if we use %i while accepting the integer value, it takes the base(decimal, octal, hexadecimal) of the value, depending upon the value entered.
    • For Example,
    • If we enter 21, it will return 21 as decimal
    • If we enter 021, it will take it as octal and will return 17
    • And, if we enter 0x21, it will take it as hexa-decimal and will return 33

Use of %d

Run
#include <stdio.h>
int main()
{
    int a, b, c;

     printf("Enter a value in decimal format:");
     scanf("%d", &b);

     printf("Enter Enter a value in octal format: ");
     scanf("%d", &b);

     printf("Enter Enter a value in hexadecimal format: ");
     scanf("%d", &c);

     printf("Enter a = %d, b = %d, c = %d", a, b, c);

      return 0;
}

Output

Enter a value in decimal format:1792
Enter Enter a value in octal format: 01792
Enter Enter a value in hexadecimal format: 0x1792
Enter a = 32767, b = 1792, c = 0

Use of %i

Run
#include <stdio.h> 

int main()
{
    int a, b, c;

     printf("Enter a value in decimal format:");
     scanf("%i", &b);

     printf("Enter a value in octal format: ");
     scanf("%i", &b);

     printf("Enter a value in hexadecimal format: ");
     scanf("%i", &c);

     printf("a = %i, b = %i, c = %i", a, b, c);

      return 0;
}

Output

Enter a value in decimal format:21
Enter a value in octal format: 021
Enter a value in hexadecimal format: 0x21
a = 32764, b = 17, c = 33 

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription