algorithms

%d and %i format specifiers – C

What is a format specifier:
It basically tells us what type of data we are dealing with, while reading(scanf()) or writing (printf()). It is a sequence starting with a % sign.

While reading integers, we can go for %d or %i. %d assumes base 10 and %i auto detects it. To be more specific, %d specifies signed decimal integer while %i specifies integer. When we say %i auto detects the base, it can take integer value as decimal, hexadecimal or octal.

Here is an example:

#include 

int main()
{
    int x, y, z;

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

    printf("Enter value in octal format:(preceed number with 0) ");
    scanf("%i", &y);

    printf("Enter value in hexadecimal format: (Preceed number with 0x) ");
    scanf("%i", &z);

    printf("Decimal = %i, Octal = %i, Hex = %i", x, y, z);

    return 0;
}

Output:

Enter value in decimal format:20
Enter value in octal format:(preceed number with 0) 020
Enter value in hexadecimal format: (Preceed number with 0x) 0x20
Decimal = 20, Octal = 16, Hex = 32

Note: 
%d and %i behave similar with printf()

Let me Know What you Think!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s