Variables: named boxes
Read · 1 of 5
A variable is a box with a name
int marks = 72; makes a box called marks that holds whole numbers (int) and puts 72 in it.
In C you must say the type when you create the variable. After that, you use just the name.
Read this lesson as text
Declare a variable with its type, give it a value, and print it.
A variable is a box with a name
int marks = 72; makes a box called marks that holds whole numbers (int) and puts 72 in it.
In C you must say the type when you create the variable. After that, you use just the name.
Watch memory change
#include <stdio.h>
int main() {
int marks = 72;
int bonus = 5;
int total = marks + bonus;
printf("Total: %d\n", total);
return 0;
}- Line 4: A box named marks is created, holding 72.
- Line 5: Another box, bonus, holding 5.
- Line 6: C reads marks and bonus, adds them, and stores 77 in a new box.
- Line 7: %d is replaced by the value in total.
Name or value?
#include <stdio.h>
int main() {
int apples = 4;
printf("apples = %d\n", apples * 3);
return 0;
}What does this print?
- apples = 12
- 12 = 12
- apples = apples * 3
Show the answer
apples = 12 Text in quotes is printed as it is; the %d is filled by the value of apples * 3.
Spot the mistake
#include <stdio.h>
int main() {
int price = 40;
printf("%d\n", Price);
return 0;
}Which line has the mistake?
Show the answer
Line 5. C cares about capitals: Price and price are different names, and Price was never declared.
Exercise: Area and perimeter
Make two int variables, length = 12 and width = 5.
Print Area: 60 and then Perimeter: 34, worked out from the variables.