Learn C · lesson 2 of 60 · about 7 minutes
Variables and int
Keep numbers in memory with int variables, change them, and print them with %d.
What you'll learn
- Declare an int variable
- Print numbers with %d
- Change a variable's value
Boxes in memory
A computer's memory is a long row of numbered boxes called bytes. A variable gives some of those boxes a name, so you can store a value and find it again.
In C you say what type a variable holds. int files = 42; sets aside room for an int (a whole number), calls it files and puts 42 in it.
Printing numbers
printf can't print a number on its own. You put a placeholder like %d in the text, and the value goes after a comma. Each %d is filled in order.
Declaring and printing
#include <stdio.h>
int main(void) {
int files = 42;
int used = 2048;
printf("Files: %d\n", files);
printf("%d files use %d KiB\n", files, used);
return 0;
}Output
Files: 42
42 files use 2048 KiBStep through it to see the boxes in memory
#include <stdio.h>
int main(void) {
int files = 42;
int used = 2048;
used = used + 512;
printf("%d files, %d KiB\n", files, used);
return 0;
}Output
42 files, 2560 KiBTip
Write the type only once, when you declare the variable. Writing int used = 2560; a second time is an error; to change it later, just write used = 2560;
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.