C Language track

Lesson 03 · Level 1: Basics

Input & Output

Standard I/O functions and format specifiers

Level 1: Basics4 min readFree lesson

Learn the two most basic tools for a program to communicate with the outside world. printf is output, and scanf is input.

Learning Objectives

  • Use the format specifier of printf according to the data type.
  • Receive integers, real numbers, and strings as scanf.
  • Organize the output with format options such as width/precision.
  • Avoid common errors with scanf (missing &, %lf vs %f).

Why is the input/output format so difficult?

printf/scanf are variable argument functions. Because the compiler cannot individually check the data types of the arguments, Look at the format string ("%d %f") to determine "how the value should be pulled out of memory." If there is a mismatch between the format and the actual data type, a garbage value or segmentation fault will occur.

This lesson is effectively a “memorizing the format specifier table”.

Key concepts

1) Main format specifiers

Designator printf data type scanf data type Yes
%d int int * printf("%d", 42)
%u unsigned int unsigned int *
%f double (automatic promotion) float * printf("%.2f", 3.14)
%lf double double * scanf("%lf", &x)
%c char (promoted to int) char * printf("%c", 'A')
%s char * char * scanf("%9s", buf)
%x, %o Hexadecimal/Octal integer printf("%x", 255) → ff
%zu size_t printf("%zu", sizeof(int))

The argument float in printf is automatically promoted to double according to the calling convention and is received as %f. This is not the case in scanf, so must be %f for float *, and %lf for double *.

2) Width and Precision

printf("[%5d]\n",   42);     //[ 42] Width 5
printf("[%-5d]\n",  42);     //[42] Left Align
printf("[%05d]\n",  42);     //[00042] 0 Fill
printf("[%8.3f]\n", 3.14);   //[ 3.140] Width 8, 3 decimal places

3) How to use scanf

int n;
scanf("%d", &n);          //Pass the address of the variable with &

Multiple values:

int a, b;
scanf("%d %d", &a, &b);   //Space/tab/newline separator

Caution: If you omit &, like scanf("%d", n);, compilation will pass. Segmentation fault on run.

4) fgets is safe for string input

scanf("%s", ...) stops when it encounters a space and does not check the buffer size. There is a risk of buffer overflow. For single line input, fgets is recommended.

char buf[64];
fgets(buf, sizeof(buf), stdin);   //Includes line breaks
buf[strcspn(buf, "\n")] = '\0';   //Remove line breaks

See as example

Example 1 — ex01_printf.c: Various format specifiers

Execution result

Decimal: 255
Hexadecimal: ff
Octal: 377
Letter: A (Code 65)
String: Hello
Real number default: 3.141592
2-digit real number: 3.14
Exponential notation: 3.141592e+00

Key point: The same value (255) is output differently depending on the decimal specifier.

Example 2 — ex02_scanf_int.c: Enter one integer

int n;
scanf("%d", &n);
printf("Input value: %d\nDouble: %d\n", n, n * 2);

Input: 7

Execution result

Please enter an integer: Input value: 7
Double: 14

Key point: If you remove & from &n, it will compile, but execution will be broken.

Example 3 — ex03_scanf_multi.c: Entering multiple values at once

Input: 17 5

Execution result

Enter two integers separated by a space: Sum: 22
Cars: 12
Product: 85
Share: 3

Key point: Input can be separated by anything space, tab, newline.

Example 4 — ex04_format.c : width/precision

Execution result

[   42]
[42   ]
[00042]
[    3.1416]
[3.1416    ]

Key point: Often used when aligning columns in tabular output.

A different perspective — printf is "Form Filling"

Format: "Value is %d, percentage is %.2f%%\n"
Factor: 42 0.75
                     │        │
                     ▼        ▼
Output: "Value is 42, percentage is 0.75%"

%d/%.2f in the form is blank, and the following arguments are filled in in their place. %% is an escape to print one character, %, on the screen.

Common Mistakes

  1. Missing & in scanf: scanf("%d", n) → crash. Must be &n.
  2. %f vs %lf: %lf for double input, %f for float input.
  3. Buffer overrun: Enter 9 characters in char buf[8]; scanf("%s", buf); → Memory damage. → Limit the width like scanf("%7s", buf) or use fgets.
  4. Newline remaining: When fgets is called after scanf("%d", ...), a blank line is read. → Absorb scanf followed by getchar() once, or use the fgets + sscanf pattern from the beginning.
  5. Send double to %d: The output value is meaningless (data type mismatch).

Cleanup

  • For printf/scanf, the format specifier is key and must match the data type.
  • scanf delivers the address (&x) of the input variable.
  • float is %f, double is printf, %f / scanf is %lf.
  • fgets is safe for inputting one line of string.
  • You can create neat table output with width/precision (%5d, %.2f).

Try it yourself

cd src
gcc -std=c11 -Wall -o ex01 ex01_printf.c && ./ex01
gcc -std=c11 -Wall -o ex02 ex02_scanf_int.c && echo 7 | ./ex02
gcc -std=c11 -Wall -o ex03 ex03_scanf_multi.c && echo "17 5" | ./ex03
gcc -std=c11 -Wall -o ex04 ex04_format.c && ./ex04

Application:

  • Delete & of &n in ex02 and compile and run. Observe the results.
  • Check the output when entering b = 0 in ex03.

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/ex01_printf.cC
#include <stdio.h>

int main(void) {
    int    n = 255;
    double x = 3.141592;

    printf("Decimal: %d\n", n);
    printf("Hexadecimal: %x\n", n);
    printf("Octal: %o\n", n);
    printf("Character: %c (code %d)\n", 'A', 'A');
    printf("String: %s\n", "Hello");
    printf("Real number default: %f\n", x);
    printf("Two-digit real number: %.2f\n", x);
    printf("Exponent notation: %e\n", x);

    return 0;
}
src/ex02_scanf_int.cC
#include <stdio.h>

int main(void) {
    int n;

    printf("Please enter an integer:");
    if (scanf("%d", &n) != 1) {
        printf("Input error\n");
        return 1;
    }

    printf("Input value: %d\n", n);
    printf("Double: %d\n", n * 2);
    return 0;
}
src/ex03_scanf_multi.cC
#include <stdio.h>

int main(void) {
    int a, b;

    printf("Enter two integers separated by a space:");
    if (scanf("%d %d", &a, &b) != 2) {
        printf("Input error\n");
        return 1;
    }

    printf("Sum: %d\n", a + b);
    printf("Tea: %d\n", a - b);
    printf("Product: %d\n", a * b);
    if (b != 0)
        printf("Share: %d\n", a / b);

    return 0;
}
src/ex04_format.cC
#include <stdio.h>

int main(void) {
    int   n = 42;
    double pi = 3.14159265;

    printf("[%5d]\n",   n);
    printf("[%-5d]\n",  n);
    printf("[%05d]\n",  n);
    printf("[%10.4f]\n", pi);
    printf("[%-10.4f]\n", pi);

    return 0;
}

Assignment

Problem 1

Enter the name and age from the user and print it in the following format.

Enter name: Hong Gil-dong
Enter your age: 20
Hong Gil-dong is 20 years old.
  • File name: hw01.c
  • Input example: scanf("%s", name); (assuming the name is one word without spaces)

Problem 2

Take three integers a, b, and c as input and output the average to two decimal places.

Enter three integers: 10 20 33
Average: 21.00
  • File name: hw02.c

Problem 3

Input the time in seconds (int seconds) and output it in Hour:Minute:Second format. Example: 3725 → 1:2:5

  • File name: hw03.c
Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

hw01.cC
#include <stdio.h>

int main(void) {
    char name[64];
    int  age;

    printf("Enter your name:");
    scanf("%63s", name);

    printf("Enter your age:");
    scanf("%d", &age);

    printf("%s is %d years old.\n", name, age);
    return 0;
}
hw02.cC
#include <stdio.h>

int main(void) {
    int a, b, c;

    printf("Enter three integers:");
    scanf("%d %d %d", &a, &b, &c);

    double avg = (a + b + c) / 3.0;
    printf("Average: %.2f\n", avg);
    return 0;
}
hw03.cC
#include <stdio.h>

int main(void) {
    int seconds;

    printf("Enter time in seconds:");
    scanf("%d", &seconds);

    int h = seconds / 3600;
    int m = (seconds % 3600) / 60;
    int s = seconds % 60;

    printf("%d:%d:%d\n", h, m, s);
    return 0;
}

Learn this lesson with a mentor

Work through the C Language track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now