Changing values
Read · 1 of 4
= means "store", not "equals"
score = score + 10; reads the old score, adds 10, and stores the result back in score. The old value is gone.
Shortcuts: score += 10; does the same thing, count++; adds 1, and count--; takes 1 away.
Read this lesson as text
Overwrite a variable, use +=, ++ and --, and swap two values with a spare box.
= means "store", not "equals"
score = score + 10; reads the old score, adds 10, and stores the result back in score. The old value is gone.
Shortcuts: score += 10; does the same thing, count++; adds 1, and count--; takes 1 away.
Swapping needs a spare box
#include <stdio.h>
int main() {
int a = 3;
int b = 8;
int temp = a;
a = b;
b = temp;
printf("%d %d\n", a, b);
return 0;
}- Line 4: a holds 3.
- Line 5: b holds 8.
- Line 6: Copy a into temp before we overwrite it.
- Line 7: a gets b's value. The 3 would be lost now without temp.
- Line 8: b gets the saved 3.
- Line 9: Swapped.
Follow the changes
#include <stdio.h>
int main() {
int x = 5;
x += 3;
x = x * 2;
x--;
printf("%d\n", x);
return 0;
}What does this print?
- 15
- 16
- 9
Show the answer
15 5 + 3 is 8, times 2 is 16, minus 1 is 15.
Exercise: Swap without losing anything
The program should print 20 10, but it prints 20 20. Fix the swap using a third variable.