Print integer in C

Written by

Namrata Jangid

Printing integers in C:

Syntax for printing integers in C:

 
printf(“%d”, variableName);

printf(“%i”, variableName);

We can use both %d and %i in the printf() function to print integers. Both give the same output.

The code snippet below shows how we can print integers using %d and %i :

 
#include <stdio.h>

int  main()

{

int  num1 = 10;

int  num2 = 5;

printf("num1: %d \n", num1);

printf("num2: %i \n", num2);

return  0;

}

The code snippet gives the following output:

 
num1: 10

num2: 5

As we can observe from the output, printing integers using printf() function can be done using either %d or %i.

However, %d and %i behave differently while inputting integers using the scanf() function.

We will understand how they work differently using the below code snippet:

 
#include <stdio.h>
int  main()

{

int  num1, num2;

printf("Enter num1:");

scanf("%d", & amp; num1); // reading num1 using %d

printf("Enter num2:");

scanf("%i", & amp; num2); //reading num2 using %i

printf("num1: %d \n", num1);

printf("num2: %d \n", num2);

return  0;

}

The code snippet has the following input and output:

 
Enter num1: 010

Enter num2: 010

num1: 10

num2: 8

  • We have created two integer variable num1 and num2
  • We input num1 using %d and num2 using %i
  • When we enter 010 for num1 it ignores the first 0 and treats it as decimal 10 as we are using %d. Therefore, %d treats all numbers as decimal numbers.
  • When we enter 010 for num2 it sees the leading 0 and parses it as octal 010 as we are using %i. %i does not treat all numbers as decimal numbers.
  • However, since we are printing both num1 and num2 using %d, which means decimal, we get the output as 8 for 010 stored in num2 as 010 is the decimal equivalent of octal number 010.

Print integer in C