← 🔀 Control Flow & Output
Subtopic 4 of 4

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

  1. Read the format string left to right.
  2. Each % takes the next argument and prints it in that style.
  3. Everything else (including \n and spaces) is copied as it is.
  4. 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.
SpecifierPrintsExampleOutput
%d %iint in decimalprintf("%d", -5)-5
%uunsigned intprintf("%u", -1)4294967295
%ldlongprintf("%ld", 1L << 40)1099511627776
%cone character (from its code)printf("%c", 65)A
%sstring up to the terminatorprintf("%s", "GATE")GATE
%f %.2fdouble, 6 or 2 decimalsprintf("%.2f", 3.14159)3.14
%xhexadecimalprintf("%x", 255)ff
%5d %-5d %05dwidth, left-justify, zero padprintf("%5d|%-5d|%05d", 42, 42, 42) 42|42 |00042
%%a percent signprintf("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.

step 1 of 7
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)
main()
no variables yet
Output

Check yourself

What does printf("%d", printf("ab")) print?

Remember: printf prints exactly what the format says and returns the character count.
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.