The format specifiers in C are used in formatted strings to represent the type of data to be printed. Different data types have different format specifiers. %d is one such format specifier used for the int data type.
In this article, we will discuss the %d format specifier in the C programming language.
%d in C
“%d” is a format specifier in C programming which act as a placeholder for an integer argument in a formatted input and output statement. “%d” is mainly used with the printf() and scanf() functions, which are used for basic output and input in C.
Syntax
printf("%d", int_argument);
scanf("%d", addressof_int_argument);
Aside from printf() and scanf(), %d can be used in other input and output function that uses a formatted string such as fscanf(), sscanf(), fprintf(), sprintf(), etc.
Examples of %d in C
Example 1: Using %d in printf()
C
#include <stdio.h>
int main()
{
int quan = 10;
int price = 20;
printf ( "Price of %d notebooks is %d" , quan,
quan * price);
return 0;
}
|
Output
Price of 10 notebooks is 200
In the above example, firstly we take two integer variables to store data and then print them using %d format specifier. In printf() function we have written a string in which we use %d two times and corresponding to their variable names. For the first %d format specifier, we write ‘quan’ to display the value of ‘quan’ variable and for the second %d format specifier we have written an expression “quan*price” which multiplies quan and price and that result is displayed in place of second %d format specifier.
Example 2: Using %d in scanf()
C
#include <stdio.h>
int main()
{
int num1, num2;
printf ( "Enter first number: " );
scanf ( "%d" , &num1);
printf ( "Enter second number: " );
scanf ( "%d" , &num2);
printf ( "num1 + num2 = %d" , num1 + num2);
return 0;
}
|
Input
Enter First Number: 65
Enter Second Number: 48
Output
num1 + num2 = 113
In this example, Firstly we declared two variables ‘num1’ and ‘num2’ then we print a string “Enter first number:” using printf() function after that we use scanf() function to take input from the user. Inside scanf() function we used “%d” format specifier to take integer input from the user which is stored in the ‘num1’ variable. In scanf() %d is not used to display the integer as in printf() function. Similarly, we take the second input from a user and store it in the ‘num2’ variable and then print the sum of num1 and num2 using %d format specifier in C.
Other Format Specifiers for Integers
%d is not the only format specifier in C to represent integers. To be precise, %d is used to represent a signed decimal integer. Other integer types such as unsigned int, long int, etc. have their own format specifiers.
- %ld: Long int
- %lld: Long long int
- %hd: short int
Note: While %d represents decimal integers, %i is another format specifier used to represent integers of any base system. For more info, refer to this article – Difference between %d and %i format specifier in C language