Format Specifiers
Part of the Fundamentals section of Coddy's C journey — lesson 32 of 63.
The printf() function in C allows for more precise control over the output format using format specifiers. Here are some advanced format specifiers:
%dor%i: Integer%u: Unsigned integer%f: Float or double
%eor%E: Scientific notation%gor%G: Use %f or %e, whichever is shorter%xor%X: Hexadecimal
%o: Octal%c: Character%s: String
%p: Pointer address
You can also control the width and precision of the output:
%5d: Integer with width 5%7.2f: Float with width 7 and 2 decimal places%-10s: Left-aligned string with width 10
Example:
printf("%10.2f\n", 3.14159); // Outputs: 3.14printf("%.3f\n", 3.14159); // Outputs: 3.142printf("%+d\n", 42); // Outputs: +42printf("%x\n", 255); // Outputs: ffChallenge
EasyWrite a C program that demonstrates the use of various format specifiers. Your program should:
- Declare an integer
numwith value 255 - Declare a float
piwith value 3.14159 - Declare a character
letterwith value 'A' - Print
numas a decimal, hexadecimal, and octal number - Print
piwith 2 decimal places - Print
letteras a character and its ASCII value
Use appropriate format specifiers for each output.
Cheat sheet
The printf() function uses format specifiers for precise output control:
%dor%i: Integer%u: Unsigned integer%f: Float or double%eor%E: Scientific notation%gor%G: Use %f or %e, whichever is shorter%xor%X: Hexadecimal%o: Octal%c: Character%s: String%p: Pointer address
Width and precision control:
%5d: Integer with width 5%7.2f: Float with width 7 and 2 decimal places%-10s: Left-aligned string with width 10
printf("%10.2f\n", 3.14159); // Outputs: 3.14
printf("%.3f\n", 3.14159); // Outputs: 3.142
printf("%+d\n", 42); // Outputs: +42
printf("%x\n", 255); // Outputs: ffTry it yourself
#include <stdio.h>
int main() {
int num = 255;
float pi = 3.14159;
char letter = 'A';
// Your code here
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
3Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge