Input & Output (printf & scanf)
printf() for output and scanf() for input, both of which rely heavily on format specifiers.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.
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.
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.
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.
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().
Write a program that asks for a person's age and height, reads both with scanf, and prints them back in a formatted sentence.
#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;
}