90 min

printf: formatted output

How printf reads its format string from left to right: copied text, escape sequences, %d %f %c %%, several values in one call, and width and precision.

Input and output

A program talks with the user in two directions. Input (קלט) is data that enters the program: the user types on the keyboard. Output (פלט) is data that leaves the program: text that appears in the console window.

In C, the keyboard is called standard input (stdin) and the console is standard output (stdout). Two functions from stdio.h do the work:

  • printf writes formatted output to the console. This lesson.
  • scanf reads formatted input from the keyboard. Next lesson.

The whole unit uses one example: a lab console for controller boards. Each board has an ID (int board_id = 417), a measured voltage (double voltage = 4.98) and a channel letter (char channel = 'B'). The goal is a clear ticket like this one:

BOARD INTAKE
Board ID: 417
Voltage: 4.98 V
Channel: B
Status: RECORDED

Anatomy of a printf call

printf("System ready\n");

Read it as a sentence: call printf and give it a format string.

  • printf is the function (פונקציה) name. A function is a named job that someone already wrote. printf prints formatted text.
  • The parentheses ( ) hold the arguments (ארגומנטים): the information we give the function.
  • "System ready\n" is the format string (מחרוזת פורמט): the text to print, in double quotes.
  • The semicolon ; ends the statement.

Text is printed exactly as written

printf prints exactly what is inside the quotes, and nothing more. It never adds a new line by itself:

printf("Board ready");
printf("ID: 417");
Board readyID: 417

Two calls did not make two lines. To end a line, you ask for it with \n:

printf("Board ready\n");
printf("ID: 417\n");
Board ready
ID: 417
Step through the two versions. The console shows each call's output as it runs; without \n the second text lands on the same line.Open full screen

Escape sequences

Some characters are hard to type inside the quotes. An escape sequence (רצף בריחה) is a backslash \ and one more character. It is two characters in the code and one character in the output.

In the codeMeaningExampleOutput
\nnew lineprintf("A\nB\n");A and B on two lines
\ttab: jump to the next tab stopprintf("ID:\t417\n");ID: 417
\"a double quote inside the textprintf("Status: \"READY\"\n");Status: "READY"
\\one backslashprintf("Path: C:\\Labs\n");Path: C:\Labs

Tab stops are usually every 8 columns, so after the 3 characters of ID: the tab adds 5 spaces.

The format string is a plan

The format string can also hold places for values. Each place starts with % and is called a conversion specifier (מציין המרה). The values come after the format string, separated by commas:

printf("Board %d uses channel %c\n", board_id, channel);

printf reads the format string from left to right, like a plan:

  1. Copy the text Board to the console, exactly as it is.
  2. %d takes the 1st value after the format string: board_id, so it prints 417.
  3. Copy the text uses channel.
  4. %c takes the 2nd value: channel, so it prints B.
  5. \n ends the line.
Board 417 uses channel B
Click through the steps. The highlighted piece of the format string is the one printf is reading now; the console line grows piece by piece, and each value comes from the variable with the same number.Open full screen

Each type has its own conversion

The conversion must match the type of the value:

Value typeConversionCodeOutput
int%dprintf("%d", board_id);417
double (or float)%fprintf("%f", voltage);4.980000
char%cprintf("%c", channel);B
no value%%printf("98%%");98%

%f prints 6 digits after the decimal point unless you ask for fewer. %% takes no value: a single % starts a conversion, so to print the percent sign itself you write it twice. Later in the course, %s prints text (strings).

Several values in one call

One call can build a whole line. The values follow the format string in the same order as the conversions: 1st conversion with the 1st value, 2nd with the 2nd, and so on. Same order, same count.

#include <stdio.h>
 
int main(void)
{
    int board_id = 417;
    double voltage = 4.98;
    char channel = 'B';
 
    printf("Board %d | %.2f V | Channel %c\n", board_id, voltage, channel);
    return 0;
}
Board 417 | 4.98 V | Channel B

%.2f prints the voltage with two digits after the point. The next section explains it.

Width and precision

Between the % and the letter you can add a width (רוחב) and a precision (דיוק). In %8.2f, the 8 is the width and .2 is the precision:

  • Precision is the number of digits after the decimal point. printf rounds: 4.96 with %.1f prints 5.0.
  • Width is the minimum number of characters. If the value is shorter, printf adds spaces on the left. If it is longer, nothing is cut.
  • A 0 before the width fills with zeros instead of spaces.

The bars | in these examples are part of the format string. They only show where the output starts and ends:

CodeOutputMeaning
printf("|%f|", voltage);|4.980000|default: 6 digits after the point
printf("|%.2f|", voltage);|4.98|2 digits after the point
printf("|%8.2f|", voltage);| 4.98|at least 8 characters, 2 after the point
printf("|%04d|", board_id);|0417|at least 4 characters, filled with zeros
The format lab. Choose a value, a width, a precision and the fill, and watch the output change. Each cell is one character; the shaded cells are the fill printf adds.Open full screen

Predict the output

Write the exact output before you run it. Count the lines, include every space and punctuation mark, and apply the precision.

printf("A\nB\n");
printf("Value: %d\n", 12);
printf("Voltage: %.1f V\n", 4.96);
printf("Progress: 75%%\n");
Answer

Try it yourself first, then open the solution step by step.

    Key words

    EnglishHebrewMeaning
    inputקלטdata that enters the program
    outputפלטdata that leaves the program
    functionפונקציהa named job, like printf
    argumentארגומנטinformation given to a function, inside the parentheses
    format stringמחרוזת פורמטthe text in quotes that printf reads from left to right
    conversion specifierמציין המרה%d, %f, %c: where a value is printed
    escape sequenceרצף בריחה\n, \t, \", \\
    widthרוחבthe minimum number of characters, %8.2f
    precisionדיוקthe number of digits after the point, %.2f

    Practice

    More questions, with answers, on the practice page.