Lesson 17 +10 XP

Printing Numbers with printf

Printing Numbers with printf

printf prints text, but numbers need a format specifier - a placeholder that says "put a number here".

The %d format specifier

%d is a placeholder for an integer (decimal number):

printf("%d\n", 42);        // prints 42
printf("%d\n", 42 + 3);    // prints 45

The first argument is the format string; the second is the value to insert.

Multiple placeholders

You can print several values at once:

printf("%d and %d\n", 5, 10);   // 5 and 10

Each %d grabs the next value in order.

Decimal numbers with %f

For numbers with fractions use %f:

printf("%f\n", 3.14);       // prints 3.140000
printf("%.2f\n", 3.14159);  // prints 3.14

The .2 in %.2f rounds to two decimal places.

A note on literal text

Anything in the format string that isn't a placeholder prints as-is.

TL;DR

  • printf("%d", x) prints an integer.
  • printf("%f", pi) prints a float/double.
  • %.2f rounds a float to 2 decimals.
  • Each % placeholder consumes the next argument in order.