Chapter 4

Home

Storing Data with Arrays

Loops and conditionals let you process data. Arrays let you store it. Instead of declaring a1, a2, a3, ... a hundred variables, you declare one array and access each slot by index.

What is an Array?

An array is a contiguous block of memory holding elements of the same type. You access elements by their position (index), starting at 0.

10 20 30 40 50 ... index: 0 1 2 3 4

Declaration and Access

C++

#include <bits/stdc++.h>
using namespace std;

int main() {
    // fixed-size array
    int arr[5] = {10, 20, 30, 40, 50};
    cout << arr[0] << "\n";  // 10
    cout << arr[3] << "\n";  // 40

    // modify an element
    arr[2] = 99;
    cout << arr[2] << "\n";  // 99
    return 0;
}

Rust

fn main() {
    // fixed-size array
    let arr = [10, 20, 30, 40, 50];
    println!("{}", arr[0]); // 10
    println!("{}", arr[3]); // 40

    // modify — needs mut
    let mut arr = [10, 20, 30, 40, 50];
    arr[2] = 99;
    println!("{}", arr[2]); // 99
}

Looping Through an Array

Arrays and loops are a natural pair. Use a loop index to visit each element.

Problem: Sum of array elements

Given N and N integers, store them in an array and print their sum.

Sample input:
5
4 7 1 9 3

Expected output:
24

C++

#include <bits/stdc++.h>
using namespace std;

int main() {
    int n; cin >> n;
    vector<int> arr(n);
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }
    int total = 0;
    for (int i = 0; i < n; i++) {
        total += arr[i];
    }
    cout << total << "\n";
    return 0;
}

C++: vector<int> is a dynamic array. Use it instead of raw C arrays in CP.

Rust

use std::io::{self, Read};

fn main() {
    let mut input = String::new();
    io::stdin().lock().read_to_string(&mut input).unwrap();
    let nums: Vec<i64> = input
        .split_whitespace()
        .map(|x| x.parse().unwrap())
        .collect();

    let n = nums[0] as usize;
    let arr = &nums[1..=n];
    let total: i64 = arr.iter().sum();
    println!("{}", total);
}

Rust: Vec<T> is the dynamic array. iter().sum() is the idiomatic way.

Key Takeaways

Practice