Input and Output in C: scanf, printf and Formatted Reports

MODULE 3 • LESSON 04

A program that cannot take in data or show its results is not much use. Every algorithm you wrote in Module 2 started with INPUT and ended with OUTPUT. In C, the two workhorses are printf, which writes formatted text to the screen, and scanf, which reads values typed at the keyboard into variables. Both live in the standard library, and both are declared in stdio.h (standard input/output), which is why almost every C program begins with #include <stdio.h>.

This lesson goes beyond “printf prints things”. You will control exactly how numbers appear (width, decimal places, alignment), produce neat headings and report tables, read several values of different types, and understand the input buffer, which explains the most common and most puzzling scanf bugs.

What you will learn

  • How printf uses a format string, format specifiers and escape sequences.
  • How to control field width, precision and alignment to output formatted data.
  • How to plan and print headings and neatly aligned report tables.
  • How to read int, float, double and char values with scanf, and why it needs the address-of operator.
  • How the input buffer works, why a leftover newline breaks %c, and how to fix it.
  • How to recognise and correct common input and output errors.

Part 1: Output with printf

printf takes a format string in double quotes, followed by zero or more values. Ordinary characters in the format string are printed as they are. Each format specifier, beginning with %, is a placeholder that is replaced by the next value in the list:

printf("Total: %d items\n", count);

Here “Total: ” is printed, then %d is replaced by the value of count written as a whole number, then ” items”, then a new line. The specifiers must match the values in number, order and type. If they do not, the output is wrong (and the compiler, with warnings switched on, will tell you).

SpecifierPrintsExample
%dan int42 shows as 42
%freal, 6 decimals3.5 shows as 3.500000
%.2freal, 2 decimals3.14159 shows as 3.14
%escientific notation384400.0 shows as 3.844000e+05
%cone character‘B’ shows as B
%sa string (text)“CAPE” shows as CAPE
%%a percent signprintf(“100%%”); shows 100%

Some characters cannot be typed directly inside a string, so C uses escape sequences, which start with a backslash:

EscapeMeaning
\nnew line
\ttab (jump to the next tab stop)
\\a backslash
\”a double quote inside a string
\’a single quote (in a char)

Two simpler output functions are also useful. puts("Hello"); prints a string followed automatically by a new line, and putchar('A'); prints a single character. Neither can format numbers, so printf remains the main tool.

Part 2: Width, precision and alignment

Between the % and the letter you can add extra instructions. The full pattern is % flags width .precision type:

  • Width (a whole number) sets the minimum number of characters the value takes up. Shorter values are padded with spaces; longer values are never cut off.
  • Precision (a dot then a number) sets the number of decimal places for %f and %e, rounding the value. For %s it sets the maximum number of characters printed.
  • Flags: a minus sign (-) left-aligns the value in its field (the default is right-aligned); a zero (0) pads numbers with zeros instead of spaces.

Width and precision are measured in characters, and the decimal point and minus sign count. So %8.2f with 85.5 prints “85.50” (5 characters) with 3 spaces in front, 8 characters altogether.

Worked example 1: one value, many formats

The square brackets in each format string are ordinary characters. They are there only so you can see where each field starts and ends.

#include <stdio.h>

int main(void)
{
    int n = 42;
    float x = 3.14159;
    char c = 'Q';

    printf("[%d]\n", n);
    printf("[%5d]\n", n);
    printf("[%-5d]\n", n);
    printf("[%05d]\n", n);
    printf("[%f]\n", x);
    printf("[%.2f]\n", x);
    printf("[%8.3f]\n", x);
    printf("[%e]\n", x);
    printf("[%c]\n", c);
    printf("[%s]\n", "CAPE");
    printf("[%6s]\n", "CAPE");
    printf("[%d%%]\n", n);
    return 0;
}

Output:

[42]
[   42]
[42   ]
[00042]
[3.141590]
[3.14]
[   3.142]
[3.141590e+00]
[Q]
[CAPE]
[  CAPE]
[42%]

Notice that %8.3f rounded 3.14159 to 3.142, and that the float 3.14159 printed with %f shows 3.141590: six decimal places by default. Notice too that numbers are right-aligned by default, which is exactly what you want in a column of money amounts so that the decimal points line up.

Try it 1printf format builder

Choose a specifier and a value, then change the width, precision and flags. Watch the format string and the output change. Can you match all five targets?

Value
Width
Precision

Part 3: Headings and report tables

Many exam questions and real programs ask you to "print a heading" and then rows of results underneath. The secret of a tidy report is to plan the column widths first and then use the same widths in the heading and in every row. A quick layout plan on paper might be: item name left-aligned in 10 characters, quantity right-aligned in 4, cost right-aligned in 9 with 2 decimal places. That gives the format %-10s%4d%9.2f for each row and %-10s%4s%9s for the heading (the heading words are strings, so %s with the same widths).

Worked example 2: a formatted receipt

#include <stdio.h>

#define VAT 0.125

int main(void)
{
    int qty1 = 3, qty2 = 10;
    float price1 = 12.50, price2 = 4.80;
    float cost1, cost2, sub, tax;

    cost1 = qty1 * price1;
    cost2 = qty2 * price2;
    sub = cost1 + cost2;
    tax = sub * VAT;

    printf("   ISLAND STATIONERY\n");
    printf("=======================\n");
    printf("%-10s%4s%9s\n",
           "Item", "Qty", "Cost");
    printf("%-10s%4d%9.2f\n",
           "Notebook", qty1, cost1);
    printf("%-10s%4d%9.2f\n",
           "Pen", qty2, cost2);
    printf("-----------------------\n");
    printf("%-14s%9.2f\n", "Subtotal",
           sub);
    printf("%-14s%9.2f\n", "VAT 12.5%",
           tax);
    printf("%-14s%9.2f\n", "TOTAL",
           sub + tax);
    printf("Thank you!\tCome again.\n");
    return 0;
}

Output:

   ISLAND STATIONERY
=======================
Item       Qty     Cost
Notebook     3    37.50
Pen         10    48.00
-----------------------
Subtotal          85.50
VAT 12.5%         10.69
TOTAL             96.19
Thank you!	Come again.

Points to notice:

  • The title and underline are plain strings. Lines of = and - are a simple, effective way to make a heading stand out.
  • The heading row uses %s with the same widths as the data rows, so the columns line up exactly.
  • Long printf calls are split over two lines. C ignores the line break inside the brackets, so this is allowed and keeps code readable.
  • "VAT 12.5%" is printed with %s, so its % sign is just a character in the value. Only a % inside the format string needs doubling to %%.
  • The last line uses \t, a tab, to jump to the next tab stop.

Part 4: Input with scanf

scanf reads what the user types and converts it to the right type. Like printf, it takes a format string, but the values after it are the addresses of the variables to fill:

scanf("%d", &age);

The & is the address-of operator. printf only needs a copy of a value to display it, but scanf must change the variable, so it needs to know where in memory the variable lives (Lesson 03: every variable has an address). Forgetting the & is the single most common scanf error: the program compiles (perhaps with a warning) but crashes or misbehaves when it runs, because scanf writes to a random location.

Type of variablescanf specifierprintf specifier
int%d%d
float%f%f
double%lf%f (or %lf)
char%c (or " %c")%c
string (char array)%s, and no &%s

The one to watch is double. printf is happy with %f, but scanf must be told with %lf ("long float") that it is filling an 8-byte double. Using %f for a double in scanf stores a float-sized value into it and you get nonsense.

Always prompt first. scanf just waits silently, so print a message telling the user what to type: printf("Enter your age: ");. A prompt usually has no \n, so the cursor stays on the same line. One scanf can read several values, for example scanf("%d %f", &age, &height);; the user can separate them with spaces or press Enter between them.

Worked example 3: reading mixed types

For this run the user typed 17 1.68 on the first line, 2500.5 on the second and B on the third. (The typed input does not appear in the output below because it came from a file, so all three prompts are on one line.)

#include <stdio.h>

int main(void)
{
    int age = 0;
    float height = 0.0;
    double savings = 0.0;
    char grade = ' ';

    printf("Age and height: ");
    scanf("%d %f", &age, &height);
    printf("Savings: ");
    scanf("%lf", &savings);
    printf("Grade: ");
    scanf(" %c", &grade);

    printf("\nAge:     %d\n", age);
    printf("Height:  %.2f m\n", height);
    printf("Savings: $%.2f\n", savings);
    printf("Grade:   %c\n", grade);
    return 0;
}

Sample input: 17 1.68 2500.5 B

Output:

Age and height: Savings: Grade: 
Age:     17
Height:  1.68 m
Savings: $2500.50
Grade:   B

Every variable is initialised before input, the double uses %lf, and the char uses " %c" with a space. The next part explains why that space matters.

Part 5: Inside the input buffer

When the user types, the characters do not go straight into your variables. They wait in an area of memory called the input buffer, and nothing is sent to the program until Enter is pressed. Enter itself adds a newline character to the buffer. Each scanf then takes characters from the front of the buffer:

  • %d, %f and %lf first skip any whitespace (spaces, tabs, newlines), then read as many characters as can form a number, and stop at the first one that cannot. That character stays in the buffer.
  • %c reads the very next character, whatever it is, including a space or a newline. It does not skip whitespace.
  • A space in the format string means "skip any amount of whitespace here". So " %c" skips leftover spaces and newlines before reading a character.
  • %s skips whitespace, then reads characters up to the next space, so it reads one word only.
  • scanf returns the number of values it successfully read. If the user types letters where a number is expected, it returns 0, leaves the variable unchanged and leaves the letters in the buffer.

Put together, these rules explain the classic bug. After scanf("%d", &n); the newline from Enter is still in the buffer. A following scanf("%c", &c); grabs that newline at once, and the program seems to skip the question. Step through it below.

Try it 2Input buffer simulator

Choose a scenario. The boxes show what the user has typed: · is a space and ⏎ is the newline from Enter. Grey characters have been used; the orange box is where scanf will look next. Predict each step.

Input buffer

A safe pattern for menu programs and yes/no questions is therefore: read numbers with %d, %f or %lf, and read single characters with " %c". In Module 3 Lesson 05 and beyond you will also check scanf’s return value to reject bad input, which you designed as validation in Module 2.

Part 6: Common input and output errors

Exam questions often give you a short fragment and ask you to find and correct the errors. These are the ones to look for first:

ErrorExampleCorrection
Missing & in scanfscanf("%d", age);scanf("%d", &age);
Specifier does not match the typeprintf("%d", price); with float priceprintf("%.2f", price);
%f used to read a doublescanf("%f", &dist); with double distscanf("%lf", &dist);
%s used for a numberprintf("%s", count);printf("%d", count);
Missing quotes around the formatprintf(Total: %d, t);printf("Total: %d", t);
Wrong number of valuesprintf("%d %d", a);printf("%d %d", a, b);
No new line, so output runs togetherprintf("Done");printf("Done\n");
Text in a scanf formatscanf("Enter %d", &n);Use printf for the prompt, then scanf("%d", &n);

With -Wall switched on, gcc catches most of the mismatches as warnings (Lesson 02), and the -Werror option used for every program in this course turns them into errors so they cannot be ignored. Missing quotes is a syntax error, and a missing & is reported because the argument type is wrong.

Good input and output habits

  • Prompt for every input, and say what kind of value and units are expected, for example "Enter height in metres: ".
  • Label every output. A bare number such as 96.19 means nothing to a user; "TOTAL 96.19" does.
  • Choose sensible decimal places. Money gets 2; a percentage may get 1; a count gets none. Never leave the default six decimal places in a report.
  • End output lines with \n so the next output, or the command prompt, starts on a fresh line.
  • Initialise variables before reading into them, so that if input fails the variable holds a known value rather than garbage.
  • Test with awkward input: a decimal where a whole number is expected, letters, extra spaces, and pressing Enter early. Module 2 called these invalid and boundary test data.

These habits matter in exams too. In a "write a program" question, examiners usually reward a prompt before each input and a clear label on each output, even when the question does not mention them explicitly.

Try it 3Format practice

Pick a mode. "Specifier" asks for the right format specifier. "Output" asks what a formatted printf displays (· = space).

Summary

IdeaRemember
printfFormat string plus values; specifiers must match in number, order and type.
Specifiers%d int, %f float or double, %c char, %s string, %e scientific, %% a percent sign.
Formatting% flags width .precision type, for example %-10s and %8.2f.
HeadingsPlan column widths; use the same widths for the heading and the rows.
scanfNeeds the address-of operator before each variable (not for strings); %lf for double.
BufferNumber specifiers skip whitespace; %c does not, so use " %c". scanf returns the count read.

Review questions

1. Write a printf statement that displays the float variable avg to 1 decimal place, with the label "Average: ".

Show answer

printf("Average: %.1f\n", avg);

2. What is displayed by printf("[%6.2f]", 7.456); ? Show spaces clearly.

Show answer

[ 7.46] : the value rounds to 7.46 (4 characters), so 2 spaces are added in front to make 6.

3. Explain why scanf needs the address-of operator but printf does not.

Show answer

scanf must store a value into the variable, so it needs the variable’s address in memory. printf only displays the value, so a copy is enough.

4. A program declares double rate; Write a statement to read rate from the keyboard.

Show answer

scanf("%lf", &rate);

5. Write statements to print a heading with columns Name (left-aligned, 12 wide) and Score (right-aligned, 6 wide), then one row for "Ava" with score 87.

Show answer

printf("%-12s%6s\n", "Name", "Score");
printf("%-12s%6d\n", "Ava", 87);

6. A program reads a number with scanf("%d", ...) and then a Y/N answer with scanf("%c", ...). The second input never seems to happen. Explain and correct.

Show answer

The newline from pressing Enter after the number stays in the input buffer, and %c reads it immediately. Correct with a space before %c: scanf(" %c", &answer);

7. State what scanf returns, and give one use for it.

Show answer

The number of items successfully read. A program can compare it with the expected number to detect invalid input (for example letters typed instead of a number).

8. Find and correct TWO errors: printf("Mark: %s\n, mark); where mark is an int.

Show answer

The closing quote is missing after \n, and %s should be %d: printf("Mark: %d\n", mark);

Homework

  1. Write a program that asks for a student’s name initial, three test marks (int) and prints a report: a heading, each mark on its own line with the test number, and the average to 2 decimal places.
  2. Write a currency converter that reads an amount in TT dollars as a double and the exchange rate, then prints the converted amount right-aligned in a field 12 wide with 2 decimal places.
  3. Print a table of the numbers 1 to 5 with their squares and cubes, using fixed widths so the columns line up. (You may repeat printf five times; Lesson 06 shows how a loop does this.)
  4. Type in the "Leftover newline" scenario from Try it 2 as a real program and run it. Then apply the fix and run it again. Describe what you saw.
  5. Find out what %x and %o print. Use them to print 255 and check your answer with Module 1 number conversion.

Mastery quiz: Input and Output in C

This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

Mastery quiz: Input and Output in C: scanf, printf and Formatted Reports

Your course badges: loading saved progress…

View badges

    No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

    Saved in this browser on this device. Clearing browser data may remove your badges.

    Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

    1. Which header file declares printf and scanf?
    2. Which specifier reads a value into a double with scanf?
    3. What does printf("%.2f", 3.14159); display?
    4. What does printf("%5d", 42); display (dots are spaces)?
    5. Which format left-aligns a string in 10 characters?
    6. Which statement prints 50% correctly?
    7. Which escape sequence moves to a new line?
    8. Why does scanf need the address-of operator before a variable name?
    9. After reading a number, scanf("%c", ...) reads a newline. What fixes it?
    10. The user types abc when scanf("%d", ...) runs. scanf returns...

    Exam tips

    Specimen Unit 1 Paper 01 (2021), Item 40. Choosing the correct scanf statement for a double. Check three things in every option: the specifier (%lf for double), the address-of operator, and the quotes.

    CAPE 2024 Unit 1 Paper 02, Question 5(b). Identifying and correcting errors in C statements, including mismatched format specifiers and missing quotes. Use the error table in Part 6 as your checklist, and always write the full corrected statement.

    CAPE 2019 Unit 1 Paper 02, Question 5, Part B. Writing a short program that reads values (including a real number) and outputs results. Marks go for prompts, correct specifiers, the address-of operator and clearly labelled output. A worked answer is in the Go further box.

    When a question asks you to "print a heading", print it once before any data, and make it clearly describe the output that follows.

    More worked answers are on the CS Solutions page.

    Previous: Module 3 • Lesson 03 – Variables, Data Types and Assignment in C (with enum). Next: Module 3 • Lesson 05 – Selection in C: if, else if and switch.

    Syllabus link: CAPE Computer Science (CXC A19/U2/21), Programming (Unit 1, Module 3). Specific Objective 4: use input and output statements (input data into variables; output formatted data from variables; print headings).

    Video search terms

    Search YouTube for: "C printf format specifiers width precision", "C scanf tutorial", "scanf newline problem %c".

    Try it 4Quick quiz

    Tap an answer. All eight questions are self-checks on this lesson.

    Updates

    2026/12/01

    - Updated the copyright line.

    2026/11/24

    - First version of the lesson.

    © 2026 islandclass.org

    Leave a Reply