Lesson 3 / 10

Operators and Control Flow

Conditionals

int score = 82;nstd::string grade;nif (score >= 90) {n    grade = "A";n} else if (score >= 75) {n    grade = "B";n} else {n    grade = "C";n}

Loops

for (int i = 0; i < 5; i++) {n    std::cout << "Lesson " << i << std::endl;n}nnint attempts = 0;nwhile (attempts < 3) {n    attempts++;n}

Reading input

int quantity;nstd::cout << "How many lessons today? ";nstd::cin >> quantity;

<< sends data out to the console (think of it as an arrow pointing data toward the output stream); >> reads data in from the keyboard, into a variable. The arrows visually point in the direction the data flows, which is a genuinely useful way to remember which is which.

Arithmetic and integer division

std::cout << 10 / 3;      // 3 -- integer division truncatesnstd::cout << 10 / 3.0;    // 3.33333 -- involving a double gives a decimal resultnstd::cout << 10 % 3;      // 1 -- remainder

Exactly like Java, dividing two integers in C++ truncates toward zero rather than rounding — a very common source of off-by-a-fraction bugs for anyone expecting a decimal result from that expression.

A common mistake: forgetting std::endl or “n”

Without a newline character, consecutive std::cout statements print directly next to each other on the same line, which can make debugging output confusing to read. std::endl both prints a newline and flushes the output buffer; a plain "n" is slightly faster since it skips the flush, and is preferred in tight loops that print a lot.