C++ Foundations & Input/Output
Master the fundamentals of C++: program structure, variables, data types, arithmetic operations, fast I/O, and conditionals.
C++ Foundations & Input/Output
Every competitive programmer's journey starts here. This chapter covers the building blocks you'll use in every single problem: how C++ programs are structured, how to read and write data efficiently, and the basic operations that form the backbone of algorithmic thinking.
Program Structure & Compilation
A C++ program begins at the main function. Every solution you submit to an online judge follows this skeleton:
#include <bits/stdc++.h>
using namespace std;
int main() {
// your code here
return 0;
}
The #include <bits/stdc++.h> header pulls in the entire C++ standard library — a convenience that saves time during contests. In production code you'd include only what you need, but in competitive programming, speed of writing matters.
Compilation
When you compile with g++, the compiler goes through several stages:
- Preprocessing — macros are expanded, headers are inlined
- Compilation — source code is translated to assembly
- Assembly — assembly is converted to object code
- Linking — object files are combined into an executable
g++ -O2 -std=c++17 -Wall -Wextra solution.cpp -o solution
Key flags:
-O2— enables optimizations (always use this; judges compile with-O2)-std=c++17— sets the language standard-Wall -Wextra— enables warnings (helps catch bugs early)
Variables & Data Types
C++ is statically typed — every variable has a known type at compile time. For competitive programming, these are the types that matter:
| Type | Size | Range |
|---|---|---|
int | 4 bytes | ≈ ±2 × 10⁹ |
long long | 8 bytes | ≈ ±9 × 10¹⁸ |
float | 4 bytes | ~7 decimal digits |
double | 8 bytes | ~15 decimal digits |
char | 1 byte | -128 to 127 |
int n = 100;
long long big = 1e18;
double pi = 3.14159265358979;
char letter = 'A';
Rule of thumb: Use long long when there's any chance of overflow. In competitive programming, int overflow is the silent killer — your code runs, produces a wrong answer, and gives you zero hints about why.
Arithmetic Operations & Modulo
The basic operations work as you'd expect:
int a = 10, b = 3;
int sum = a + b; // 13
int diff = a - b; // 7
int prod = a * b; // 30
int quot = a / b; // 3 (integer division truncates)
int rem = a % b; // 1 (modulo / remainder)
Integer Division Truncates
This is the single most common source of bugs for beginners:
7 / 2 == 3 // NOT 3.5
-7 / 2 == -3 // truncates toward zero
If you need exact division, cast to double first or restructure your logic.
Modulo Arithmetic
Modulo (%) is everywhere in competitive programming. Many problems ask you to compute answers mod 10⁹ + 7:
const int MOD = 1e9 + 7;
int add(int a, int b) {
return (a + b) % MOD;
}
int mul(int a, int b) {
return (1LL * a * b) % MOD;
}
Key properties:
(a + b) % m = ((a % m) + (b % m)) % m(a * b) % m = ((a % m) * (b % m)) % m(a - b + m) % m— addingmbefore%prevents negative results
Integer Overflow & The 1LL Trick
When you multiply two int values that are each close to 10⁹, the result exceeds 2 × 10⁹ and overflows:
int a = 1e9, b = 1e9;
int product = a * b; // OVERFLOW — undefined behavior!
The fix is to cast one operand to long long before the multiplication:
long long product = 1LL * a * b; // correct
The 1LL trick: multiplying by the long long literal 1 forces the entire expression into 64-bit arithmetic. Use it whenever you multiply two int values whose product might exceed ~2 × 10⁹.
// Always safe for large intermediates
long long result = 1LL * a * b % MOD;
Input/Output Streams & Fast I/O
On Codeforces and similar platforms, large inputs can make the difference between AC (Accepted) and TLE (Time Limit Exceeded). The default cin/cout synchronization with stdio is slow.
The Speed Hack
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
This disables the synchronization between C and C++ I/O streams, making cin/cout nearly as fast as scanf/printf.
Reading Input
int n;
cin >> n; // reads a single integer
vector<int> a(n);
for (int i = 0; i < n; i++) {
cin >> a[i];
}
string s;
cin >> s; // reads a word (stops at whitespace)
getline(cin, s); // reads a full line
Writing Output
cout << answer << "\n"; // use \n, not endl (endl flushes = slow)
Always prefer \n over endl. endl forces a buffer flush on every line, which is expensive when you're printing thousands of lines.
Conditionals & Logical Operators
If-Else
if (n > 0) {
// positive
} else if (n == 0) {
// zero
} else {
// negative
}
Ternary Operator
A compact if-else for simple assignments:
int mx = (a > b) ? a : b;
Logical Operators
| Operator | Meaning | Example |
|---|---|---|
&& | AND | a > 0 && b > 0 |
|| | OR | a == 0 || b == 0 |
! | NOT | !(a > b) |
C++ uses short-circuit evaluation: in A && B, if A is false, B is never evaluated. This is useful for guarding against invalid access:
if (i < n && a[i] > 0) { ... } // safe: a[i] only accessed if i < n
Summary
- Use
long longby default to avoid overflow - The
1LL *trick promotesintmultiplication to 64-bit - Always add
ios_base::sync_with_stdio(false); cin.tie(nullptr);for fast I/O - Use
\ninstead ofendl - Modulo arithmetic:
(a - b + MOD) % MODhandles negatives - Short-circuit evaluation is your friend — use it to guard bounds checks
In the next chapter, we'll use these foundations to solve problems with loops and direct simulation.
Prefer reading offline? Download the full book as a PDF.
Download Free Book