Input & Output (printf & scanf)

⚙️ C Language 🟢 Lesson 4 of 20 📅 2026 Edition
Every useful program needs to communicate with the outside world — displaying results and accepting input from the user. C's Standard I/O library gives you printf() for output and scanf() for input, both of which rely heavily on format specifiers.
1printf() in Depth
C Language ▶ Run Code
int score = 95;
float gpa = 3.85;
printf("Score: %d, GPA: %.2f\n", score, gpa);

%.2f rounds a float to 2 decimal places — the number after the dot controls precision. You can also control minimum field width, e.g. %5d pads a number with spaces to at least 5 characters wide, which is useful for aligning tables of output.

2scanf() for Reading Input
C Language ▶ Run Code
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("You are %d years old\n", age);

Notice the & before age — this is the address-of operator, telling scanf() exactly where in memory to store the value it reads. Forgetting it is one of the most common C bugs, covered below.

3Reading Multiple Values at Once
C Language ▶ Run Code
int day, month, year;
printf("Enter date as DD MM YYYY: ");
scanf("%d %d %d", &day, &month, &year);

scanf() can read several values in one call, separated by spaces in the format string that match how the user is expected to type them, separated by spaces or newlines.

4Reading Characters and Strings Safely
C Language ▶ Run Code
char initial;
scanf(" %c", &initial);   // note the leading space, explained below

char name[50];
scanf("%49s", name);      // %s does NOT need & for arrays, explained in Lesson 10-11

The leading space before %c tells scanf() to skip any leftover whitespace or newline characters sitting in the input buffer from a previous read — without it, you'll often read an unwanted blank character instead of the one the user actually typed.

⚠️ Common Mistake: Forgetting the & (Address-Of Operator) in scanf

Writing scanf("%d", age) instead of scanf("%d", &age) is arguably the single most common C bug beginners write. Without &, scanf() has no idea where in memory to store the value, which can crash your program or silently corrupt memory. Always double-check for & before every non-array variable passed to scanf().

💻 Try It Yourself

Write a program that asks for a person's age and height, reads both with scanf, and prints them back in a formatted sentence.

C Language ▶ Run Code
#include <stdio.h>

int main() {
    int age;
    float height;

    printf("Enter your age: ");
    scanf("%d", &age);
    printf("Enter your height in feet: ");
    scanf("%f", &height);

    printf("You are %d years old and %.1f feet tall.\n", age, height);
    return 0;
}
Run This in Our Compiler →