Format specifiers, employed alongside the printf() function, inform the compiler about the data type stored in a variable.
Essentially, they act as a placeholder for the variable’s value.
A format specifier begins with a percentage sign %, succeeded by a character.
For instance, when printing the value of an integer variable, enclose the format specifier %d within double quotes ( “” ) within the printf() function.
int myNum = 15; printf(“%d”, myNum); // Outputs 15 |
For printing different types, utilize %c for char and %f for float:
// Create variables int myNum = 15; // Integer (whole number) float myFloatNum = 5.99; // Floating point number char myLetter = ‘D’; // Character // Print variables printf(“%d\n”, myNum); printf(“%f\n”, myFloatNum); printf(“%c\n”, myLetter); |
To incorporate both text and a variable into a printf() function, ensure they are divided by a comma within the parentheses.
int myNum = 15; printf(“My favorite number is: %d”, myNum); |
int myNum = 15; char myLetter = ‘D’; printf(“My number is %d and my letter is %c”, myNum, myLetter); |
You will learn more about Data Types in a later chapter. |