>RunTimeFix
BookStudyPracticeInterviewsYouTubeCoursesAbout
Log inGet Started

Table of Contents

01C++ Foundations & Input/Output02Loops & Direct Simulations03Arrays, Strings & Character Operations04Functions & Recursion05Strings & Character Operations06Structs, Lambdas & Structured Bindings07Preprocessor, Debug Macros & Compilation08Vectors, Pairs & Utility Algorithms09Sets, Maps & Multi-Containers10Sorting & Frequency Arrays11Complexity & Problem Solving12Basic Number Theory & Modular Arithmetic13Prefix Sums & Difference Arrays14Two Pointers & Sliding Window15Binary Search (Array & Answer Space)16Greedy Algorithms & Constructive Problems17Bit Manipulation & Masking18Stacks, Queues & Monotonicity19Disjoint Set Union (DSU)20Coordinate Compression, Fenwick Tree & Segment Tree21Graph Representation, DFS & BFS22Cycle Detection, Bipartite Checking & Topological Sort23Dijkstra, 0-1 BFS & Kruskal's MST24Rooted Trees — DFS, Subtree Size & Diameter25Binary Lifting, LCA & Euler Tour26Dynamic Programming — Foundations27Dynamic Programming — Knapsack & Subsets28Backtracking & Meet-in-the-Middle29Modular Inverse, Combinatorics & Fast Math30Hashing, String Algorithms & Geometry Basics
Study Library/Ch 1
Chapter 01 of 30

C++ Foundations & Input/Output

Master the fundamentals of C++: program structure, variables, data types, arithmetic operations, fast I/O, and conditionals.

Program Structure & CompilationVariables & Data TypesArithmetic Operations & ModuloInteger Overflow & The 1LL TrickInput/Output Streams & Fast I/OConditionals & Logical Operators
Share:

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:

hljs cpp
#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:

  1. Preprocessing — macros are expanded, headers are inlined
  2. Compilation — source code is translated to assembly
  3. Assembly — assembly is converted to object code
  4. Linking — object files are combined into an executable
hljs bash
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:

TypeSizeRange
int4 bytes≈ ±2 × 10⁹
long long8 bytes≈ ±9 × 10¹⁸
float4 bytes~7 decimal digits
double8 bytes~15 decimal digits
char1 byte-128 to 127
hljs cpp
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:

hljs cpp
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:

hljs cpp
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:

hljs cpp
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 — adding m before % 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:

hljs cpp
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:

hljs cpp
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⁹.

hljs cpp
// 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

hljs cpp
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

hljs cpp
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

hljs cpp
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

hljs cpp
if (n > 0) {
    // positive
} else if (n == 0) {
    // zero
} else {
    // negative
}

Ternary Operator

A compact if-else for simple assignments:

hljs cpp
int mx = (a > b) ? a : b;

Logical Operators

OperatorMeaningExample
&&ANDa > 0 && b > 0
||ORa == 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:

hljs cpp
if (i < n && a[i] > 0) { ... }  // safe: a[i] only accessed if i < n

Summary

  • Use long long by default to avoid overflow
  • The 1LL * trick promotes int multiplication to 64-bit
  • Always add ios_base::sync_with_stdio(false); cin.tie(nullptr); for fast I/O
  • Use \n instead of endl
  • Modulo arithmetic: (a - b + MOD) % MOD handles 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.

Ch 2: Loops & Direct Simulations

Prefer reading offline? Download the full book as a PDF.

Download Free Book
>RunTimeFix

Practical programming education. Books, videos, courses, and hands-on learning for competitive programming, DSA, and software engineering.

RunTimeFix

  • About
  • YouTube
  • Book
  • Study Library
  • Courses

Learn

  • Competitive Programming
  • DSA
  • Development
  • Databases

Legal

  • Privacy
  • Terms
  • Refund Policy

RunTimeFix — debug → solve → run

© 2026 RunTimeFix. All rights reserved.