Lesson 2

Variables and input

Short answer: a variable is a named box in memory holding one value of one type. Declare it (int age;), give it a value (age = 20;), and from then on the name is that value.

Four types cover almost all beginner code

TypeHoldsExample
intwhole numbersint score = 95;
doubledecimalsdouble price = 19.99;
charone character, single quoteschar grade = 'A';
booltrue or falsebool passed = true;

The type decides how many bytes the box takes and how the bits are read. That is why 'A' and "A" differ — single quotes make a char, double quotes make a string literal (the long version).

Declare, assign, print

#include <iostream>
using namespace std;

int main() {
    int score = 95;
    double price = 19.99;
    char grade = 'A';
    bool passed = true;

    cout << "score:  " << score << endl;
    cout << "price:  " << price << endl;
    cout << "grade:  " << grade << endl;
    cout << "passed: " << passed << endl;   // bools print as 1 / 0
    return 0;
}

That last line is the first surprise: bool prints as 1 or 0, not true/false. It is how cout treats booleans by default.

Reading input with cin

cin >> name reads one value from the keyboard. The arrow points into the variable — a useful way to remember the direction:

#include <iostream>
using namespace std;

int main() {
    int a, b;
    cin >> a;
    cin >> b;
    cout << "sum = " << a + b << endl;
    return 0;
}

Change the numbers in the input box: the program is not a calculator app, it is four lines of arithmetic that happen to run in a browser.

Integer division, once more

The most common numeric surprise: int / int is an int, fraction discarded.

#include <iostream>
using namespace std;

int main() {
    int a = 7, b = 2;
    cout << a / b << endl;             // 3 — fraction discarded
    cout << (double)a / b << endl;     // 3.5 — one side is double
    return 0;
}

Why, including negatives and %: why 7 / 2 is 3.

Errors you will hit this week

Practice this lesson

These problems exercise exactly what you just read: