Variables and Formatted Output
Give a value a name
A printed sign stays the same each time. A ticket count needs a value the program can remember and update. A variable is named storage for a value. Its type tells C what kind of value it holds.
Read int seats = 8; as “declare a whole-number variable called seats and initialize it to eight.” Declaring introduces the name; initializing gives it its first value. The 8 is an integer literal, a number written directly in the code.
#include <stdio.h>
int main(void) {
int tickets = 3;
printf("Tickets: %d\n", tickets);
tickets = tickets + 2;
printf("Tickets now: %d\n", tickets);
return 0;
}
The first print reads tickets while it holds 3. In tickets = tickets + 2;, C reads the old value on the right, calculates 5, then stores 5 on the left. = means assignment, not mathematical equality. The next print reads the updated value.
Match values to placeholders
In printf("Tickets: %d\n", tickets), the first argument is a format string. %d is a placeholder, also called a conversion specifier: it asks printf to display the next argument as an int. The comma separates arguments; it does not print.
| Value type | Use it for | Print it with |
|---|---|---|
int | Whole-number counts, such as 3 | %d |
double | Values with a fractional part, such as 2.5 | %f, or %.1f for one decimal place |
char | A single character, such as 'B' | %c |
#include <stdio.h>
int main(void) {
double distance = 2.5;
char zone = 'B';
printf("Zone %c is %.1f km away\n", zone, distance);
return 0;
}
Match left to right: %c uses zone, then %.1f uses distance. Single quotes make a character literal such as 'B'; double quotes make a string such as "Zone". They are not interchangeable.
Run both examples. The ticket output changes from 3 to 5, while the second example prints 2.5 with one decimal place. %.2f would display that same distance as 2.50; formatting changes its display, not the stored value.
Always initialize a local variable before reading it. It has no reliable starting value otherwise. Keep each format conversion matched to its argument's type; a mismatch can make program behavior undefined, meaning C gives you no dependable result.