📝 Lesson 2: C++ Syntax Basics
Every C++ program is built from the same handful of pieces — comments, a main() function, statements, variables, and input/output. Learn them once here and you'll recognize them in every program you ever read.
🎯 Learning Objectives
By the end of this lesson, you will be able to:
- Write single-line and multi-line comments and explain why the compiler ignores them.
- Identify the parts of a minimal C++ program —
#includedirectives,main(), statements, and thereturnvalue. - Apply the core syntax rules: semicolons, braces, case sensitivity, and whitespace.
- Declare and initialize variables of the fundamental types, and name them well.
- Read input with
std::cinand print output withstd::coutusing the<<and>>operators. - Combine all of the above into a small interactive program.
Estimated Time: 40–50 minutes
Project: Build an interactive calculator that reads two numbers from the user and prints their sum, difference, product, and quotient. (An optional stretch peeks ahead to operator selection.)
In This Lesson
The Anatomy of a C++ Program
Almost every C++ program shares the same skeleton. Here is the classic first program, and below it a breakdown of every piece:
#include <iostream> // 1. bring in the input/output library
int main() { // 2. the program's entry point
std::cout << "Hello, World!" << std::endl; // 3. a statement
return 0; // 4. report success to the operating system
}
#include <iostream>— a preprocessor directive that pulls in the standard input/output library so you can usestd::coutandstd::cin.int main()— execution always begins here. Theintmeansmainhands an integer back to the operating system when it finishes.- Statements — the actual work, written between the
{ }braces. Each statement ends with a semicolon. return 0;—0conventionally means "finished successfully." Any non-zero value signals an error.
💡 What is std::?
Names from the C++ Standard Library live in the std namespace, so you write std::cout, std::string, and so on. You'll sometimes see using namespace std; near the top of small programs, which lets you drop the std:: prefix. It's handy for tiny examples but discouraged in larger code because it can cause name clashes — this course writes std:: explicitly.
Basic Syntax Rules
C++ is strict about a few mechanical rules. Learn these four now and you'll avoid the most common beginner compiler errors:
| Rule | What it means | Example |
|---|---|---|
| Semicolons | Every statement ends with a ;. Forgetting one is the #1 beginner error. | int x = 5; |
| Braces | { } group statements into a block (a function body, a loop, an if). | int main() { ... } |
| Case sensitivity | Count, count, and COUNT are three different names. | std::cout, not std::Cout |
| Whitespace | Extra spaces, tabs, and blank lines are ignored — use them freely to stay readable. | int x=5; ≡ int x = 5; |
⚠️ Watch out: because whitespace is ignored, the compiler won't complain about messy formatting — but a human reviewer will. Indent the code inside every pair of braces; it makes the structure obvious at a glance.
Variables & Types
A variable is a named container for a value. In C++ you must state the type of data it holds when you declare it, and the type never changes afterward.
int age = 25; // whole number
double price = 19.99; // number with a decimal point
char initial = 'R'; // a single character, in single quotes
bool isActive = true; // true or false
std::string name = "Ray"; // text, in double quotes (needs #include <string>)
Here are the fundamental types you'll use constantly:
| Type | Holds | Example value |
|---|---|---|
int | Whole numbers | -3, 0, 42 |
double | Decimal (floating-point) numbers | 3.14159 |
char | A single character | 'A' |
bool | A true/false value | true |
std::string | A sequence of characters (text) | "hello" |
Declaration vs. Initialization
Declaring a variable creates it; initializing it gives it a starting value. Always initialize — an uninitialized variable holds an unpredictable "garbage" value.
int count; // declared but NOT initialized — value is garbage
count = 0; // now assigned
int score = 0; // declared AND initialized in one step (preferred)
int lives{3}; // modern brace-initialization, also fine
Naming Rules
- Names may use letters, digits, and underscores, but cannot start with a digit.
- They are case-sensitive and cannot be a reserved keyword (
int,return, …). - Choose descriptive names:
studentCountbeatssc, and both beatx.
💡 const and auto
Mark a value that should never change with const, e.g. const double PI = 3.14159; — the compiler then stops you from accidentally reassigning it. (When the value is known at compile time, modern C++ prefers constexpr: constexpr double PI = 3.14159;.) And when the type is obvious from the right-hand side, auto lets the compiler deduce it: auto total = 0; gives an int. (We use these throughout later lessons.)
Input & Output
Console programs talk to the user through two objects from <iostream>: std::cout (character out) prints, and std::cin (character in) reads.
std::cout << "Enter your name: "; // << sends text TO the console
std::string userName;
std::cin >> userName; // >> reads input INTO the variable
std::cout << "Hello, " << userName << "!" << std::endl;
Two things worth noticing:
- Chaining. You can string several
<<together in one statement, as in the last line above, to print pieces one after another. - Direction of the arrows.
<<points towardcout(data flows out);>>points away fromcin(data flows into your variable).
Reading numbers works the same way — std::cin converts the typed text into the variable's type:
std::cout << "Enter your age: ";
int age;
std::cin >> age;
std::cout << "Next year you'll be " << age + 1 << ".\n";
💡 std::endl vs "\n"
Both move to a new line. "\n" is just a newline character; std::endl also flushes the output buffer, which is slightly slower. For everyday printing, either is fine.
Putting It All Together
Here's a complete program that uses everything from this lesson — comments, the program skeleton, variables, and input/output:
#include <iostream>
#include <string>
int main() {
// Greet the user and collect some information
std::string name;
int birthYear;
std::cout << "What's your name? ";
std::cin >> name;
std::cout << "What year were you born? ";
std::cin >> birthYear;
const int CURRENT_YEAR = 2026;
int age = CURRENT_YEAR - birthYear; // a little arithmetic
std::cout << "Nice to meet you, " << name << "!\n";
std::cout << "You are about " << age << " years old.\n";
return 0;
}
Read it top to bottom: it includes the libraries it needs, enters main(), declares variables, prompts and reads input, computes a value, prints the result, and returns 0. That shape will feel familiar within a week.
Practice Exercise: Interactive Calculator
🏋️ Build a Two-Number Calculator
Objective: Put comments, variables, and input/output together in one program — using only what this lesson covered.
Instructions:
- Prompt the user to enter two numbers (use
doubleso decimals work). - Read both numbers with
std::cin. - Print all four results — the sum, difference, product, and quotient — each with a clear label.
- Comment each step so a stranger could follow your logic.
Starter Code:
#include <iostream>
int main() {
double a, b;
// TODO: prompt for and read the first number into a
// TODO: prompt for and read the second number into b
// TODO: print the sum, difference, product, and quotient
return 0;
}
💡 Hint
You already have every tool you need: std::cout to prompt and print, std::cin to read. You can compute right inside the output statement, e.g. std::cout << "Sum: " << a + b << "\n";. No decisions or branching required — just do all four calculations in a row.
✅ Solution
#include <iostream>
int main() {
double a, b;
// Ask for the two numbers
std::cout << "Enter the first number: ";
std::cin >> a;
std::cout << "Enter the second number: ";
std::cin >> b;
// Print every operation, each with a label
std::cout << "Sum: " << a + b << "\n";
std::cout << "Difference: " << a - b << "\n";
std::cout << "Product: " << a * b << "\n";
std::cout << "Quotient: " << a / b << "\n";
return 0;
}
Try it with 4 and 0 for the second number: the quotient prints inf rather than crashing — that's how double division by zero behaves. Handling that gracefully needs a decision, which is exactly what the stretch below (and Lesson 4) is about.
🔭 Optional Stretch: An Operator-Driven Calculator (peek ahead)
This one reaches past this lesson on purpose — skip it with a clear conscience if you'd rather wait. Instead of printing all four results, let the user type one operator (+ - * /) and print just that result. Choosing which calculation to run based on the operator requires a decision — the if statement — which you'll learn properly in Lesson 4: Control Structures. Here's a taste so you can try it now if you're curious.
💡 Hint
Read the operator into a char with std::cin >> op;. Compare a char to a literal using single quotes: if (op == '+') { ... }. Chain the cases with else if.
✅ Solution
#include <iostream>
int main() {
double a, b;
char op;
std::cout << "Enter the first number: ";
std::cin >> a;
std::cout << "Enter an operator (+ - * /): ";
std::cin >> op;
std::cout << "Enter the second number: ";
std::cin >> b;
// Pick the calculation based on the operator the user typed
if (op == '+') {
std::cout << "Result: " << a + b << "\n";
} else if (op == '-') {
std::cout << "Result: " << a - b << "\n";
} else if (op == '*') {
std::cout << "Result: " << a * b << "\n";
} else if (op == '/') {
if (b != 0) {
std::cout << "Result: " << a / b << "\n";
} else {
std::cout << "Error: cannot divide by zero.\n";
}
} else {
std::cout << "Unknown operator: " << op << "\n";
}
return 0;
}
Notice the divide-by-zero guard — checking user input for trouble before using it is a habit worth building early. Don't worry if the if / else if syntax feels new; Lesson 4 covers it from the ground up.
🎯 Quick Quiz
Question 1: Which symbol begins a single-line comment in C++?
Question 2: Which header must be included to use std::cout and std::endl?
Question 3: In the line std::cin >> userName;, what does the >> operator do?
Summary
🎉 Key Takeaways
- ✓ Comments (
//and/* */) document your code and are ignored by the compiler — use them to explain why. - ✓ Every C++ program has
#includedirectives, anint main()entry point, statements, and areturnvalue. - ✓ The core syntax rules: end statements with
;, group code with{ }, respect case sensitivity, and format with whitespace for readability. - ✓ Variables have a fixed type declared up front —
int,double,char,bool,std::string— and should always be initialized. - ✓
std::cout << …prints andstd::cin >> …reads; the arrows show which way the data flows.
📚 Additional Resources
- cppreference — Comments
- cppreference — Basic concepts (program structure)
- LearnCpp — Introduction to iostream: cout, cin, and endl
🚀 What's Next?
You can now write, comment, and structure a basic C++ program, store values in variables, and get data in and out. Next, in Lesson 3: Data Types & Operators, you'll go deeper into the type system you just met — numeric types in detail, type conversion, and the arithmetic, comparison, and logical operators that let your programs actually compute.
🎉 Your first real C++ programs are up and running!
Comments, variables, and input/output are the building blocks every C++ program is made of — and you just shipped an interactive calculator with them.
Comments: Leaving Notes in Your Code
Comments are notes for humans. The compiler ignores them completely, so they never change what your program does — they exist to explain why the code does what it does, for you and for anyone who reads it later (including future-you).
✅ Good practice
Comment the why, not the obvious what.
i++; // add one to iis noise — the code already says that.i++; // skip the header rowis useful, because it explains intent the code can't.