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
| Type | Holds | Example |
|---|---|---|
int | whole numbers | int score = 95; |
double | decimals | double price = 19.99; |
char | one character, single quotes | char grade = 'A'; |
bool | true or false | bool 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
- Used before declared. C++ reads top to bottom; using
xbeforeint x;is a compile error, not zero. - Uninitialised.
int sum; sum += 5;adds 5 to whatever was in memory. Always writeint sum = 0;. - Overflow.
intstops near 2.1 billion —20!does not fit. Our factorial problem makes you hit that wall on purpose. - Double quotes for a char.
char c = "A";fails; write'A'.
Practice this lesson
These problems exercise exactly what you just read: