← C++ from Scratch Lesson 2 of 62 · 10 XP

Syntax

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

The rules of writing C++:

  • blocks are curly braces { }; indentation doesn't affect anything (but we use it for people);
  • statements end with ;;
  • case matters: Main and main are different names;
  • std:: is the namespace of the standard library: std::cout means "cout from std". People often write using namespace std; and then just cout. In big programs this isn't recommended — names can clash. More on this in the last module. In this course we write std:: explicitly.

An output chain: each << adds the next piece, and numbers are printed as numbers:

std::cout << "2 + 3 = " << 2 + 3 << '\n';   // 2 + 3 = 5

'\n' in single quotes is one character, while "\n" is a string of one character. Either works for a line break. There's also std::endl — a line break plus a forced flush of the buffer; it's slower, so in loops '\n' is better.

Task. With one std::cout chain, print 7 * 6 = 42 — the number 42 must be calculated by the program.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.