2.4printf, return values and format specifiers
The idea
printf turns values into text using format specifiers, and it returns how many characters it printed.
Think of it like this: A mail-merge: the format string is the letter, each % is a blank, and the arguments fill the blanks in order.
Why it exists
Exam output must be exact: newlines, spaces and widths all count.
How it works
- Read the format string left to right.
- Each % takes the next argument and prints it in that style.
- Everything else (including \n and spaces) is copied as it is.
- The return value is the total number of characters written.
Worked example: printf("%c %d", 65, 'A')
%c prints the character with code 65: A. %d prints the integer value of 'A', which is 65. Output: A 65.
Now play with it
- →Run the printf in action program and compare each output line with its format string.
- →Edit a format and re-run to test your prediction.
| Specifier | Prints | Example | Output |
|---|---|---|---|
| %d %i | int in decimal | printf("%d", -5) | -5 |
| %u | unsigned int | printf("%u", -1) | 4294967295 |
| %ld | long | printf("%ld", 1L << 40) | 1099511627776 |
| %c | one character (from its code) | printf("%c", 65) | A |
| %s | string up to the terminator | printf("%s", "GATE") | GATE |
| %f %.2f | double, 6 or 2 decimals | printf("%.2f", 3.14159) | 3.14 |
| %x | hexadecimal | printf("%x", 255) | ff |
| %5d %-5d %05d | width, left-justify, zero pad | printf("%5d|%-5d|%05d", 42, 42, 42) | 42|42 |00042 |
| %% | a percent sign | printf("100%%") | 100% |
printf returns the number of characters it printed. A format that does not match its argument (for example %d with a double) is undefined behaviour.
1#include <stdio.h>2int main() {3 int n = printf("hello\n");4 printf("%d\n", n);5 printf("[%5d][%-5d][%05d]\n", 42, 42, 42);6 printf("%c %d %x %5.2f\n", 65, 'A', 255, 3.14159);7 printf("%s|%.2s\n", "GATE", "GATE");8 return 0;9}
The gold line is the statement about to run.
Call stack (top first)
Output
Check yourself
What does printf("%d", printf("ab")) print?
Exam notes (the dense version)
%d int, %u unsigned, %ld long, %c char, %s string, %f double (6 decimals), %x hex, %% a percent sign. printf returns the number of characters printed. printf("%d", x) with a missing or mismatched argument is undefined behaviour. Output questions often depend on exactly where \n appears.
Previous year questions: Control Flow & Output (10)
PYQs are grouped by topic, so this is the full set for Control Flow & Output; try the ones that match this subtopic. Open all 10 on the topic page.