Help improve SovranCode?

Google Analytics can measure anonymous usage after you choose Allow. Essential account and progress features work either way.

SovranCode
C: Foundations for Systems Programming Input and Output with printf and scanf
This device
Course contentsInput and Output with printf and scanf · 15 titles

C foundations

What C Is and How C Programs RunYour First C ProgramVariables, Types, and OperatorsInput and Output with printf and scanfConditions and Loops

Program structure and data

Functions, Headers, and ScopeArrays and StringsPointers and Memory AddressesStructures, Enumerations, and UnionsFiles and Command-Line Arguments

Memory, tooling, and practice

Dynamic Memory AllocationPreprocessor Directives and Separate CompilationErrors, Debugging, and Undefined BehaviorBuild Tools and MakefilesProject: Command-Line Inventory Manager
C: Foundations for Systems Programming15 complete lessons

C foundations

What C Is and How C Programs RunYour First C ProgramVariables, Types, and OperatorsInput and Output with printf and scanfConditions and Loops

Program structure and data

Functions, Headers, and ScopeArrays and StringsPointers and Memory AddressesStructures, Enumerations, and UnionsFiles and Command-Line Arguments

Memory, tooling, and practice

Dynamic Memory AllocationPreprocessor Directives and Separate CompilationErrors, Debugging, and Undefined BehaviorBuild Tools and MakefilesProject: Command-Line Inventory Manager
PREVIOUS LESSONVariables, Types, and Operators
NEXT LESSONConditions and Loops
C fundamentals 70 min

Input and Output with printf and scanf

Input is not a value until a program converts it, stores it in the right place, and checks that the conversion succeeded. Learn the complete, typed path from standard input through scanf to a clear printf result.

What you will leave with

You will be able to format output with %d, %f, and %s; declare input variables before reading them; use scanf with & and matching %d or %lf placeholders; explain whitespace-separated input; identify failed conversion as an invalid value state; and avoid unsafe string scanning until arrays and strings are covered.

Follow data in both directions

Format outputUse a format string as a visible contract between a value and a terminal representation.
Read inputSupply numeric standard input and watch scanf store it in typed variables.
Trace conversionSeparate raw characters, a successful conversion, stored data, and later output.
Repair safelyUse a precise runner message to fix an address or format mismatch rather than guessing.

Output makes the program state observable

printf starts with a format string. Ordinary characters appear as written; a placeholder reserves a place for the next value after the string. The placeholder must describe that value accurately. In this course, use %d for an int, %f for a double, and %s for a text reference. Each placeholder consumes one following argument, from left to right.

C FUNDAMENTALS RUNNER

Format a typed output line

Change the activity text or seat count, predict the exact terminal line, then run it. Keep the %s and %d placeholders aligned with their values.

#include <stdio.h>

int main(void) {
  const char *activity = "C input practice";
  int available_seats = 8;

  printf("%s: %d seats available\n", activity, available_seats);
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Add a second printf line that shows the available seats after subtracting one int named reserved_seats.

printf("%d", count)

Print a whole number

%d receives an integer expression such as a count, difference, or named int variable.

printf("%f", hours)

Print a decimal quantity

%f displays a double. In this beginner form, printf shows six digits after the decimal point by default.

printf("%s", label)

Print text

%s prints a null-terminated text sequence. The text has already been prepared; printf does not ask the user for it.

printf("%%")

Print a percent sign

Use two percent characters in the format string to write one literal percent sign without consuming a value.

Input begins as characters, not as an int or double

When a person types 18, the environment first provides characters. scanf attempts to convert those characters according to its format string. On success, it stores the converted numeric value in a variable. That is why a variable must be declared before the scan, and why the format and target type must agree.

01Provide input

The terminal or Standard input panel supplies characters such as 18 or 1.5.

02Convert

scanf interprets the next token using its numeric placeholder.

03Store

The address marker points to a declared variable where the result belongs.

04Use deliberately

Only after successful conversion should a calculation or printf read that value.

Read one whole number with scanf

The source below declares attendees without an initial value because input will provide its first value. &attendees means “the address of attendees”: it gives scanf a place to store the converted number. Edit the Standard input panel below, predict the final output, and run the program. The browser runner reads its input panel in token order; a local terminal reads what you type there.

C FUNDAMENTALS RUNNER

Read an int from Standard input

The runner accepts one whole-number token for %d. Try a different positive, zero, or negative value and trace where it is stored.

#include <stdio.h>

int main(void) {
  int attendees;

  printf("Standard input supplies one whole number.\n");
  scanf("%d", &attendees);
  printf("Attendees: %d\n", attendees);
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Replace 18 with a different whole number, then make the terminal message describe that new value precisely.

The address marker is not optional

attendees is the numeric value. &attendees is the location where scanf can write a new numeric value. Omitting & passes the wrong kind of argument and makes a real C program unsafe or undefined. Treat compiler warnings about scanf arguments as urgent evidence.

Match scanf formats to the target type

For scanf, use %d with an int target and %lf with a double target. The extra l matters here: it tells scanf to write a double. This differs from printf, where %f displays a double. Memorizing one format character is less reliable than reading the entire pair: function, placeholder, target type, and address.

C FUNDAMENTALS RUNNER

Read an int and a double in order

The first Standard input token goes to sessions; the second goes to hours_per_session. Spaces and newlines both separate numeric input tokens in this runner.

#include <stdio.h>

int main(void) {
  int sessions;
  double hours_per_session;
  double total_hours;

  scanf("%d %lf", &sessions, &hours_per_session);
  total_hours = sessions * hours_per_session;
  printf("Sessions: %d\n", sessions);
  printf("Total study time: %f hours\n", total_hours);
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Change the input to 6 and 1.25. Predict total_hours before running the program.

scanf("%d", &count)

Read an int

Use a declared int and its address. The input should be a whole-number token such as 0, 18, or -4.

scanf("%lf", &hours)

Read a double

Use a declared double and its address. The input can include a fraction such as 1.5 or -0.25.

scanf return value

Confirm conversion later

Real C returns the number of fields it converted. When conditions arrive next, compare that result with the number you expected before using the input variables.

whitespace

Separate numeric tokens

For these numeric formats, spaces, tabs, and newlines separate values. A prompt should explain the expected order so a person can provide the right sequence.

Treat failed conversion as a real error state

If the program expects %d but the next input token is many, no valid integer is stored. In a complete C program, check the scanf return value before using the target variable. This course introduces that check concept now; the next lesson supplies the if statement needed to express the full recovery branch safely. The browser runner stops instead of pretending that invalid input produced a usable value.

Write prompts that state the unit and shape

“Enter duration in hours as a decimal” is safer than “Enter a value.” Good prompts tell users what the value means, whether a fraction is valid, and how many values the program expects.

Repair an address mistake before reading the value

This source has a single defect: the scanf call passes open_seats instead of its address. Leave the Standard input value in place, run the program, read the message, and add only the missing &. Then run it again and explain why the repaired program can safely store the number.

C FUNDAMENTALS RUNNER

Give scanf a storage address

The runner is intentionally strict about the address marker. Repair the call by changing the smallest possible part of the source.

#include <stdio.h>

int main(void) {
  int open_seats;

  scanf("%d", open_seats);
  printf("Open seats: %d\n", open_seats);
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: After the repair works, change the input to 20 and verify that the printed value changes too.

Do not use scanf for beginner text input yet

scanf("%s", name) is not a safe first text-input pattern. It needs a writable character array with a known capacity, a field width that prevents overflow, and a plan for spaces and the remaining newline. Those are array and string concepts, so this lesson intentionally limits interactive input to numeric int and double values. Later, you will compare bounded scans with line-based input such as fgets.

Do not solve a buffer problem by guessing a bigger number

Safe text input depends on the actual destination capacity and a deliberate length limit. It is not enough to add an arbitrary width to a format string without knowing what memory is available.

Compile locally and read input from a terminal

Save an example as input.c and compile it with warnings enabled. In a terminal, the program waits at scanf until you type the requested values and press Enter. The local compiler is the authority for the full language and will help identify a format or argument mismatch that the browser subset deliberately refuses.

macOSCompile with Clang and keep format warnings visible.clang -Wall -Wextra -Wpedantic -Wconversion input.c -o input./input
LinuxCompile with GCC or Clang from the system build-tools package.gcc -Wall -Wextra -Wpedantic -Wconversion input.c -o input./inputRead every format-related warning before running the executable. It often identifies the exact format and argument pair that disagree.
WindowsCompile in a configured Developer Command Prompt.cl /W4 input.cinput.exeThe command differs by toolchain, but the habit does not: compile, inspect diagnostics, type an expected input shape, then verify the output.

Independent lab: build an input-driven workshop report

Use the starter to generate a report from two user-supplied values. Change the workshop label, then provide a new whole-number registration count and decimal duration in Standard input. Add one meaningful calculation using the input—perhaps extra spaces, total minutes, or a different group size—and print it with a matching format. Keep every value's unit clear in its name and in the output label.

C FUNDAMENTALS RUNNER

Build a typed workshop report

The starter reads registrations and duration, then calculates full groups and remaining learners. Change the data and make the report yours.

#include <stdio.h>

int main(void) {
  const char *workshop = "C practice session";
  int registered;
  double duration_hours;
  int group_size = 4;
  int full_groups;
  int learners_left;

  scanf("%d %lf", &registered, &duration_hours);
  full_groups = registered / group_size;
  learners_left = registered % group_size;

  printf("%s\n", workshop);
  printf("Registered: %d\n", registered);
  printf("Duration: %f hours\n", duration_hours);
  printf("Full groups: %d, learners left: %d\n", full_groups, learners_left);
  return 0;
}
TERMINAL OUTPUT
Edit the program, predict its output, then run it.

This safe browser runner supports the lesson subset: scalar and fixed-size int/double arrays, character strings, indexed reads and numeric writes, arithmetic, printf/puts, numeric scanf into scalar or bounded array-element addresses, comparisons, bounded if/else, for/while loops, and return.

Try this next: Change group_size, provide new input values, then add one %d output line for a calculation you can explain.

Lesson review

You now know how typed data crosses a program boundary. printf turns known values into readable terminal text. scanf attempts to turn incoming characters into typed values at the addresses you provide. Reliable input code matches every format to its target, explains the expected shape to the user, verifies conversion before using data, and postpones text scanning until memory capacity is understood.

  • I can match %d, %f, and %s with the values passed to printf.
  • I can declare an int or double before scanning, then pass its address with &.
  • I can explain why scanf uses %d for an int and %lf for a double, while printf uses %f to display a double.
  • I can describe conversion failure, whitespace-separated input order, and why text input must wait for arrays, bounds, and string-safety techniques.
KNOWLEDGE CHECK

Trace a typed value from input to output

Answer from the data flow: a typed declaration prepares storage, scanf converts input into that storage, and printf displays a value with a matching format.

01Which scanf call correctly reads a whole-number value into int attendees;?
02Which scanf placeholder matches double session_hours;?
03What does scanf return in real C when it successfully converts one requested input field?
04Why does this lesson avoid scanf("%s", name) for text input?
05The Standard input panel contains 4 on one line and 1.5 on the next. What can scanf("%d %lf", &sessions, &hours); read?
PREVIOUS LESSONVariables, Types, and Operators
NEXT LESSONConditions and Loops
ON THIS PAGEInput and Output with printf and scanfLesson mapOutput with printfInput modelRead an intRead an int and doubleFailed conversionRepair an addressText safetyCompile locallyIndependent labLesson reviewKnowledge check
Course contents