LECTURE 1 · INTRODUCTION TO C++
Why C++, and your first programs
Mon, 26 Oct 2026 · 9:30 – 11:00 PM
Attendance
Scan to mark yourself present
ADD TWO NUMBERS
Same task, two languages
Python
2 lines
a, b = map(int, input().split())
print(a + b)
C++
9 lines
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
cout << a + b << '\n';
return 0;
}
So why would anyone choose C++?
THE SPEED RACE
Now let’s race them
import time
start = time.perf_counter()
total = 0
for i in range(100_000_000):
total += i * i % 7
print(total)
print(time.perf_counter() - start, "s")
Python
9.6 s
auto t0 = chrono::steady_clock::now();
long long total = 0;
for (long long i = 0; i < 100000000; i++)
total += i * i % 7;
auto t1 = chrono::steady_clock::now();
chrono::duration<double> d = t1 - t0;
cout << total << '\n' << d.count() << " s\n";
C++ (-O2)
0.10 s
10⁸ steps each, same answer. About 90× faster. By the end of today you’ll know why.
WHERE IT’S USED
C++ runs more of the world than you think
Trading
High-frequency trading, where microseconds are money
Games
Unreal Engine and most AAA game engines
Browsers & apps
Chrome, Photoshop, Microsoft Office, Blender
Databases
MySQL, MongoDB, cloud infrastructure
AI / ML
The engines under PyTorch & TensorFlow; llama.cpp
Systems
Compilers (GCC, Clang), OS parts, low-level design
Embedded
Cars, flight software, robots (ROS)
CP
The most-used language in competitive programming
WHY C++
Why C++, out of thousands of languages?
Speed · runs straight on the CPU
Control · you decide size, memory, lifetime
Predictable · no surprise pauses
High-level tools · low-level speed
Ecosystem · decades of code and engineers
Python is an automatic car.
C++ is a manual race car.
Harder to drive. You control everything.
UNDER THE HOOD
Why is it so much faster?
C++
translated once
Your code
Compiler
Executable
CPU
Python
translated while running
Your code
Bytecode
Interpreter
CPU
Java
translated while running
Your code
Bytecode
JVM
CPU
the middleman: translates while your program runs
More reasons:
types known in advance
compact numbers
data stored side by side
no garbage collector
compiler optimizations
PART 2
Let’s write some C++
On every slide: what’s different from Python
No g++ yet? Code along in your browser today:
YOUR FIRST FILE
The C++ starter template
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
// your code here
return 0;
}
#include <…>
Like Python’s import
using namespace std;
Write cout, not std::cout
int main()
The program starts here
return 0;
“Finished successfully”
{ } and ;
Braces replace indentation; ; ends a line
FIRST PROGRAM
Hello, world
#include <iostream>
using namespace std;
int main() {
// a one-line comment
cout << "Hello, C++!" << '\n';
/* a comment that can
span many lines */
return 0;
}
$ g++ hello.cpp -o hello
$ ./hello
Hello, C++!
TRY IT
Print your name inside a box of * stars
VOCABULARY
Program, statement, variable
Program
A list of instructions, run top to bottom inside main()
Statement
One instruction. Ends with ;
int age = 20;
Variable
A named box with a fixed type
20
age
type: int
SPOT THE BUG
int x = 5
cout << x;
CIN AND COUT
Input and output
C++
int a, b;
cin >> a >> b;
cout << a + b << '\n';
Python
a, b = map(int, input().split())
print(a + b)
NICE
cin skips spaces and newlines: 3 5 or 3 then 5 on two lines both work
TRY IT
Read your birth year, print your age in 2026
MEMORY BASICS
Bits and bytes
0
1
0
0
0
0
0
1
128
64
32
16
8
4
2
1
= 65 = 'A'
one byte = 8 bits
1 byte
8 bits · 256 values
1 KB
1024 bytes
1 MB
1024 KB ≈ 10⁶ bytes
1 GB
1024 MB ≈ 10⁹ bytes
CP FACT
256 MB memory limit = about 67 million ints (4 bytes each)
DATA TYPES
The five types you’ll use most
Type | Size | Holds | Example |
int | 4 bytes | whole numbers, up to ≈ 2.1 × 10⁹ | int age = 20; |
long long | 8 bytes | whole numbers, up to ≈ 9.2 × 10¹⁸ | long long pop = 8000000000; |
double | 8 bytes | decimals, about 15 digits | double pi = 3.14159; |
char | 1 byte | one character | char grade = 'A'; |
bool | 1 byte | true or false | bool rain = false; |
sizeof(int) → 4
PICK A TYPE
Your age · world population · π · your grade · is it raining?
THE FULL FAMILY · 1 OF 2
Whole-number types
Type | Size | Range | In CP |
short | 2 bytes | −32,768 to 32,767 | rarely used |
int | 4 bytes | ≈ ±2.1 × 10⁹ | the default |
unsigned int | 4 bytes | 0 to ≈ 4.3 × 10⁹ | rarely used |
long | 4 or 8 bytes | depends on the system | avoid |
long long | 8 bytes | ≈ ±9.2 × 10¹⁸ | big values |
unsigned long long | 8 bytes | 0 to ≈ 1.8 × 10¹⁹ | hashing, bit tricks |
unsigned = no negatives, so twice the positive range
THE FULL FAMILY · 2 OF 2
Characters, true/false and decimals
Type | Size | Holds |
char | 1 byte | one character (really a small number, −128 to 127) |
bool | 1 byte | true or false |
float | 4 bytes | decimals, about 7 digits |
double | 8 bytes | decimals, about 15 digits |
long double | 8–16 bytes | decimals, about 18 digits (depends on the system) |
bool uses a whole byte for one yes/no
void means “no value” (functions, Lecture 2)
OVERFLOW
When the box is too small
int x = INT_MAX; // 2147483647
x = x + 1;
cout << x; // -2147483648 !
PREDICT
int a = 50000;
cout << a * a;
99999
+ 1
00000
A car’s odometer rolling over
OVERFLOW TRAP
The #1 beginner bug in CP
int a = 100000, b = 100000;
long long c = a * b; // wrong: still overflows
long long d = 1LL * a * b; // right
int × int
overflows as int
then stored in long long
1e9 is a double, not an int
1'000'000'000 is valid C++
DISCUSS
What if your number doesn’t fit in long long?
30! = 265252859812191058636308480000000
BIGGER NUMBERS
When long long isn’t enough
Option | Range | The catch |
unsigned long long | up to ≈ 1.8 × 10¹⁹ | no negatives; 0 − 1 wraps to a huge number |
__int128 | up to ≈ 1.7 × 10³⁸ | GCC only; cin and cout can’t read or print it |
number as a string | unlimited | you write +, −, × digit by digit, like on paper |
Python’s int | unlimited, automatic | slower, and uses much more memory |
So why doesn’t C++ just do this automatically?
DECIMALS
float vs double
float · 4 bytes
≈ 7
significant digits
double · 8 bytes
≈ 15–16
significant digits
cout << (0.1 + 0.2 == 0.3); // 0 (false!)
In CP: always double
OPERATORS
Arithmetic
+
-
*
/
%
7 / 2 → 3 // ints: decimal dropped
7 / 2.0 → 3.5
7 % 2 → 1 // remainder
PYTHON TRAP
C++ | Python | |
-7 / 2 | -3 | -4 |
-7 % 3 | -1 | 2 |
Python’s row uses // for division
CASTING
Changing a value’s type
(double)7 / 2
3.5
convert first, then divide
(double)(7 / 2)
3
too late: the division already happened
int x = 3.99;
3
chops the decimals, doesn’t round
1.0 * a / b
2.5
a handy shortcut (a = 5, b = 2)
The full rules for conversions come in Lecture 2
SHORTHAND
Assignment and ++
Write | Means |
x += 5 | x = x + 5 |
x -= 2 | x = x - 2 |
x *= 3 | x = x * 3 |
x /= 2 | x = x / 2 |
x %= 4 | x = x % 4 |
int a = 5;
int b = a++; // b = 5, a = 6
int c = ++a; // c = 7, a = 7
CAREFUL
= stores, == compares. if (x = 5) is always true.
OPERATORS
Comparisons and logic
C++ | Python | Meaning |
== != | == != | equal, not equal |
< > <= >= | same | less, greater… |
&& | and | both true |
|| | or | at least one true |
! | not | flips true / false |
cout << (5 > 3);
// prints 1
True and false print as 1 and 0
DECISIONS
if / else
Python
if age >= 18:
print("adult")
elif age >= 13:
print("teen")
else:
print("child")
C++
if (age >= 18) {
cout << "adult\n";
} else if (age >= 13) {
cout << "teen\n";
} else {
cout << "child\n";
}
( ) around the condition
{ } instead of :
else if, not elif
LOOPS
The for loop
for (int i = 1; i <= n; i++) {
sum += i;
}
Start
runs once, before the loop
Condition
keep going while it’s true
Update
runs after every step
Python: for i in range(1, n + 1):
LOOPS
The while loop
C++ · count the digits
int n = 1234, digits = 0;
while (n > 0) {
n /= 10;
digits++;
}
cout << digits; // 4
Python
n, digits = 1234, 0
while n > 0:
n //= 10
digits += 1
print(digits)
TRY IT
Count down 10, 9, … 1, then print “Liftoff!”
SCOPE
Where does a variable live?
int g = 100; // global
int main() {
int x = 5; // local to main
if (x > 0) {
int y = 10; // only inside { }
cout << g + x + y;
}
cout << y; // error!
}
global · g
main · x
if { } · y
Python: variables made inside if or for survive after it. C++: they die at the closing }
TRAP
Uninitialized variables
Local
int main() {
int x;
cout << x;
}
garbage
whatever was left in that memory
Global
int g;
int main() {
cout << g;
}
0
globals always start at zero
Python would stop with a NameError. C++ just carries on.
Always initialize:
int x = 0;
QUIZ · RAISE YOUR HAND
Guess the output (1 of 2)
7 / 2
-7 % 3
(double)(7 / 2)
'7' - '0'
→ 3
int ÷ int drops the decimal
→ -1
sign follows the left side (Python says 2)
→ 3
divided first, converted too late
→ 7
characters are numbers: 55 − 48
QUIZ · RAISE YOUR HAND
Guess the output (2 of 2)
int x = 3.99; x?
0.1 + 0.2 == 0.3
1 < 10 < 5
INT_MAX + 1
→ 3
converting to int chops, never rounds
→ 0
false: decimals aren’t stored exactly
→ 1
(1 < 10) is 1, and 1 < 5 is true
→ -2147483648
overflow wraps around (in practice)
PART 3
Competitive programming
Puzzles, a judge, and a clock
HOW IT WORKS
What is competitive programming?
Read the problem
Write the code
Submit
Judge runs hidden tests
AC
Accepted
WA
Wrong answer
TLE
Too slow
RE
Crashed
CE
Didn’t compile
Practise on
Codeforces
CodeChef
AtCoder
CSES
LeetCode
CODEFORCES 4A
Problem: Watermelon
Two friends buy one watermelon weighing w kilos.
Can they cut it into two parts so that each part weighs an even number of kilos (and isn’t empty)?
INPUT
One integer w, 1 ≤ w ≤ 100
OUTPUT
YES or NO
EXAMPLE
8 → YES (2 + 6)
Your answer? Think for a minute.
CODEFORCES 4A
Watermelon: the catch
First try · WA
if (w % 2 == 0)
w = 2
2 = 1 + 1, and 1 is odd → NO
Fixed · AC
int w;
cin >> w;
if (w % 2 == 0 && w > 2)
cout << "YES\n";
else
cout << "NO\n";
Always test the smallest inputs
HANDY TECHNIQUE
Powers of 2 ≈ powers of 10
2¹⁰
≈
10³
thousand (1024)
2²⁰
≈
10⁶
million
2³⁰
≈
10⁹
billion
2⁶⁰
≈
10¹⁸
quintillion
int (32 bits)
any 9-digit number
long long (64 bits)
any 18-digit number
FITS IN INT?
999,999,999 · 3 × 10⁹ · 10¹⁰
RULE OF THUMB
How much can you do in 1 second?
≈ 10⁸
simple operations per second
Steps | ≈ as 2ˣ | Time |
10⁶ | 2²⁰ | instant |
10⁸ | 2²⁷ | ≈ 1 second, borderline |
10⁹ | 2³⁰ | ≈ 10 seconds → TLE |
10¹⁸ | 2⁶⁰ | ≈ 300 years |
long long can store 10¹⁸, but you can never loop to it.
TIME LIMIT: 1 SECOND
Will it finish in time?
N = 2²⁰
one loop over N
N = 2²⁰
a loop inside a loop
N = 2¹²
a loop inside a loop
N = 2¹⁷
a loop inside a loop
N = 2¹⁰
three loops, nested
N = 2⁶⁰
halve N until it reaches 1
2²⁰ ≈ 10⁶
Instant
2⁴⁰ ≈ 10¹²
TLE: about 3 hours
2²⁴ ≈ 1.7 × 10⁷
Fine: about 0.2 s
2³⁴ ≈ 1.7 × 10¹⁰
TLE: about 3 minutes
2³⁰ ≈ 10⁹
TLE: about 10 s
60 steps
Instant
PART 4
Compilers are smart
How we build programs, and the tricks the compiler plays
G++
Compiling from the terminal
$ g++ sol.cpp -o sol
$ ./sol
# Windows: sol.exe
What judges (and you) should use:
$ g++ -Wall -O2 -std=c++17 sol.cpp -o sol
Flag | Does |
-o sol | names the program |
-Wall | shows warnings |
-O2 | optimizes |
-std=c++17 | modern C++ |
-g | helps debugging |
UNDER THE HOOD
What g++ actually does
hello.cpp · 6 lines
what you wrote
1
Preprocess
pastes in every #include
.ii · 36,520 lines
2
Compile
C++ → assembly (CPU steps as text)
.s · 66 lines
3
Assemble
assembly → machine code (0s and 1s)
.o
4
Link
joins your code with library code
hello
A peek at hello.s (not examined)
.LC0:
.string "Hello, C++!"
main:
endbr64
pushq %rbp
movq %rsp, %rbp
…
$ g++ -save-temps hello.cpp
COMPILER TRICK 1
You wrote a loop. It wrote a formula.
You wrote
auto t0 = chrono::steady_clock::now();
long long s = 0;
for (long long i = 1; i <= n; i++)
s += i;
auto t1 = chrono::steady_clock::now();
chrono::duration<double> d = t1 - t0;
It may effectively run
long long s =
n * (n + 1) / 2;
n = 10⁹
g++ -O0
2.4 s
g++ -O2
0.33 s
clang++ -O2
0.0000001 s
COMPILER TRICK 2
Constant folding
int week = 60 * 60 * 24 * 7;
int week = 604800;
Worked out once, before the program even runs
What about this?
Can the compiler work out a × b × c in advance?
cin >> a >> b >> c;
cout << a * b * c;
No: a, b and c are only known when the program runs.
If they were fixed values written in the code, then yes, it could fold them.
COMPILER TRICKS 3–5
More work it quietly does for you
Dead code removed
for (...) {
int x = i * i;
} // x never used
whole loop deleted
Cheaper operations
y = x * 8;
y = x << 3; // a bit shift
Repeated work hoisted
for (...)
a[i] = i * (k*k + 7);
t = k*k + 7; // once
for (...) a[i] = i * t;
KEEP IN MIND
Smart, but not magic
Not guaranteed: depends on the compiler, its version and the flags
Can’t fix a slow idea: 10¹² steps stay 10¹² steps
Judges use -O2: test with it too
No middleman + a smart compiler = why C++ won our race
RECAP
Python vs C++: what we collected today
Python | C++ |
runs through an interpreter | compiled to machine code |
a variable can change type | each variable has one fixed type |
integers never overflow | int and long long can overflow |
-7 // 2 is -4 | -7 / 2 is -3 |
indentation and : | { } and ; |
no ++ | ++ and -- |
prints True / False | prints 1 / 0 |
variables outlive if / for | variables die at the closing } |
unset variable → NameError | unset local → garbage value |
Before Lecture 2
Install g++ using the setup guide
Make a Codeforces account
Solve a few introductory problems in C++
Think: how would you add two 100-digit numbers?