>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 3
Chapter 03 of 30

Arrays, Strings & Character Operations

Learn 1D and 2D arrays in C++, row-major layout, std::string operations, and character manipulation for competitive programming.

1D Arrays (C-Style)2D Arrays & Row-Major Layoutstd::string & Character Operations
Share:

Arrays, Strings & Character Operations

Arrays are the most fundamental data structure in competitive programming. Nearly every problem involves reading data into an array, processing it, and outputting a result. This chapter covers arrays, 2D arrays, strings, and the character operations you'll use constantly.

1D Arrays (C-Style)

A C-style array is a contiguous block of memory:

hljs cpp
int a[100];          // array of 100 integers (uninitialized)
int b[5] = {1, 2, 3, 4, 5};  // initialized array
int c[5] = {};       // all zeros

Reading Input into Arrays

hljs cpp
int n;
cin >> n;
int a[n];  // VLA — works in GCC but not standard C++

// Standard approach: use vector (covered later)
// For now, fixed-size arrays:
int a[100000];
for (int i = 0; i < n; i++) {
    cin >> a[i];
}

Array Indexing

Arrays are 0-indexed: the first element is a[0], the last is a[n-1.

hljs cpp
// Reverse an array
for (int i = 0; i < n / 2; i++) {
    swap(a[i], a[n - 1 - i]);
}

Common Array Patterns

hljs cpp
// Prefix sum (precompute running totals)
long long prefix[100001];
prefix[0] = a[0];
for (int i = 1; i < n; i++) {
    prefix[i] = prefix[i - 1] + a[i];
}

// Range sum [l, r] in O(1)
long long rangeSum = prefix[r] - (l > 0 ? prefix[l - 1] : 0);

2D Arrays & Row-Major Layout

2D arrays represent grids, matrices, and tables:

hljs cpp
int grid[100][100];  // 100x100 grid

// Reading a grid
for (int i = 0; i < n; i++) {
    for (int j = 0; j < m; j++) {
        cin >> grid[i][j];
    }
}

Row-Major Order

C++ stores 2D arrays in row-major order: grid[0][0], grid[0][1], ..., grid[0][m-1], grid[1][0], .... This means iterating row-by-row is cache-friendly and faster:

hljs cpp
// Cache-friendly (fast)
for (int i = 0; i < n; i++)
    for (int j = 0; j < m; j++)
        // access grid[i][j]

// Cache-unfriendly (slow)
for (int j = 0; j < m; j++)
    for (int i = 0; i < n; i++)
        // access grid[i][j]

Grid Traversal

Moving in 4 directions (up, down, left, right):

hljs cpp
int dx[] = {-1, 1, 0, 0};
int dy[] = {0, 0, -1, 1};

for (int dir = 0; dir < 4; dir++) {
    int nx = x + dx[dir];
    int ny = y + dy[dir];
    if (nx >= 0 && nx < n && ny >= 0 && ny < m) {
        // (nx, ny) is a valid neighbor
    }
}

std::string & Character Operations

std::string is a dynamic, resizable sequence of characters:

hljs cpp
string s = "hello";
string t;
cin >> t;         // reads a word
getline(cin, s);  // reads a full line

Common String Operations

hljs cpp
int len = s.length();      // or s.size()
char first = s[0];         // access by index
s.push_back('!');          // append a character
s += " world";             // append a string
s.substr(2, 3);            // substring starting at index 2, length 3
s.find("lo");              // returns index of first occurrence (or string::npos)
s.empty();                 // true if length is 0

Iterating Over Characters

hljs cpp
// Range-based for (modern C++)
for (char c : s) {
    cout << c << " ";
}

// Index-based
for (int i = 0; i < (int)s.length(); i++) {
    cout << s[i] << " ";
}

Character Operations & ASCII

Characters are just integers in C++. 'A' is 65, 'a' is 97, '0' is 48:

hljs cpp
// Convert lowercase to uppercase
char upper = 'a' - 32;  // or: char upper = toupper('a');

// Convert char digit to integer
int digit = '5' - '0';  // digit = 5

// Check if a character is a letter
bool isLetter = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');

// Check if a character is a digit
bool isDigit = (c >= '0' && c <= '9');

String to Number Conversion

hljs cpp
// String to integer
int n = stoi("123");

// Integer to string
string s = to_string(42);

Summary

  • Arrays are 0-indexed; a[n-1] is the last element
  • 2D arrays: iterate row-by-row for cache efficiency
  • Grid traversal: use dx/dy arrays for 4-directional movement
  • std::string supports indexing, push_back, substr, find
  • Characters are ASCII integers: 'a' - 'A' == 32, '5' - '0' == 5
Ch 2: Loops & Direct SimulationsCh 4: Functions & Recursion

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.