Variables store values that later expressions can reuse.

variable A variable has a type, a name, and a value.

Variables

unitPrice
variables.cpp
Replay: real traced execution (multi-file project)
#include <iostream>

int main() {
    int unitPrice = 12;
    int quantity = 3;
    int total = unitPrice * quantity;

    std::cout << "unit=" << unitPrice << std::endl;
    std::cout << "total=" << total << std::endl;
    return 0;
}
#include <iostream>

int main() {
    int unitPrice = 8;
    int quantity = 3;
    int total = unitPrice * quantity;

    std::cout << "unit=" << unitPrice << std::endl;
    std::cout << "total=" << total << std::endl;
    return 0;
}
#include <iostream>

int main() {
    int unitPrice = 20;
    int quantity = 3;
    int total = unitPrice * quantity;

    std::cout << "unit=" << unitPrice << std::endl;
    std::cout << "total=" << total << std::endl;
    return 0;
}
  1. unitPrice ← 12, quantity ← 3, total ← 36

    3int main() {4    int unitPrice→ 12 = 12; //@unitPrice=8, 205    int quantity→ 3 = 3;6    int total→ 36 = unitPrice12 * quantity3;78    std::cout << "unit=" << unitPrice12 << std::endl;9    std::cout << "total=" << total36 << std::endl;10    return 0;11}
    outputunit=12
    total=36
  1. unitPrice ← 8, quantity ← 3, total ← 24

    3int main() {4    int unitPrice→ 8 = 8;5    int quantity→ 3 = 3;6    int total→ 24 = unitPrice8 * quantity3;78    std::cout << "unit=" << unitPrice8 << std::endl;9    std::cout << "total=" << total24 << std::endl;10    return 0;11}
    outputunit=8
    total=24
  1. unitPrice ← 20, quantity ← 3, total ← 60

    3int main() {4    int unitPrice→ 20 = 20;5    int quantity→ 3 = 3;6    int total→ 60 = unitPrice20 * quantity3;78    std::cout << "unit=" << unitPrice20 << std::endl;9    std::cout << "total=" << total60 << std::endl;10    return 0;11}
    outputunit=20
    total=60

Follow the Total

  1. unitPrice starts at 12.
  2. quantity starts at 3.
  3. total = unitPrice * quantity multiplies 12 * 3.
  4. total becomes 36.
  5. The program prints unit=12 and total=36. | unitPrice | quantity | total | | --- | --- | --- | | 8 | 3 | 24 | | 12 | 3 | 36 | | 20 | 3 | 60 |

Exercise: variables.cpp

Reproduce unit=12 and total=36, then try unitPrice 8 and 20 and predict each total before running it.