Topic 33 of 91 6. C++ Arrays and Strings Interactive Tutorial

Arrays in C++: Declaring, Initializing, Accessing, and Updating Elements

15 mins read Last updated: 26 Sep 2026 22,300 views

Direct Answer & Core Concept

Arrays are an important part of C++ programming. They allow you to store multiple values of the same data type using a single variable name.

Instead of declaring separate variables for every value, you can use an array to organize related data and access individual elements using their indexes.

Detailed Explanation & Mechanics

1. What Is an Array in C++?

An array is a collection of elements of the same data type stored in a sequence of memory locations.

Each element is accessed using an index.

In a traditional C++ array, indexing starts from 0.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};

    cout << numbers[0] << endl;
    cout << numbers[1] << endl;
    cout << numbers[2] << endl;

    return 0;
}

Output:

Explanation

  • numbers is the array name.

  • int specifies the data type.

  • 5 specifies the number of elements.

  • {10, 20, 30, 40, 50} initializes the array.

  • numbers[0] accesses the first element.

An array is useful when you need to store and process multiple related values.

2. Array Declaration in C++

Before using an array, you generally declare it by specifying its data type, name, and size.

Syntax

main.cpp
Run Online
data_type array_name[array_size];

Examples

main.cpp
Run Online
int marks[5];
float prices[10];
char letters[4];
double salaries[6];

Explanation

DeclarationMeaning
int marks[5]Array of 5 integers
float prices[10]Array of 10 floating-point values
char letters[4]Array of 4 characters
double salaries[6]Array of 6 double-precision values

The size of a built-in array must be a compile-time constant expression in standard C++.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int marks[5];

    marks[0] = 80;
    marks[1] = 75;
    marks[2] = 90;
    marks[3] = 85;
    marks[4] = 95;

    cout << marks[0] << endl;
    cout << marks[4] << endl;

    return 0;
}

Output:

3. Array Initialization in C++

Array initialization means assigning initial values to the elements when the array is created.

C++ supports several ways to initialize arrays.

1. Initialize all elements

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};

    for (int i = 0; i < 5; i++) {
        cout << numbers[i] << endl;
    }

    return 0;
}

Output:

2. Initialize without specifying the size

You can let the compiler determine the array size from the number of initial values.

main.cpp
Run Online
int numbers[] = {
  10, 20, 30, 40
}
;

The compiler determines that the array contains four elements.

3. Partial initialization

You can provide fewer initial values than the declared array size.

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {10, 20};

    for (int i = 0; i < 5; i++) {
        cout << numbers[i] << endl;
    }

    return 0;
}

Output:

The remaining elements are initialized to zero.

4. Initialize all elements to zero

All five elements are initialized to zero.

You can also write:

5. Initialize using a loop

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[5];

    for (int i = 0; i < 5; i++) {
        numbers[i] = (i + 1) * 10;
    }

    for (int i = 0; i < 5; i++) {
        cout << numbers[i] << endl;
    }

    return 0;
}

Output:

4. Accessing Array Elements in C++

You can access an individual array element using its index inside square brackets.

Syntax

Remember that array indexing starts from 0.

For an array containing five elements, valid indexes are 0 through 4.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};

    cout << "First element: " << numbers[0] << endl;
    cout << "Second element: " << numbers[1] << endl;
    cout << "Third element: " << numbers[2] << endl;
    cout << "Last element: " << numbers[4] << endl;

    return 0;
}

Output:

main.cpp
Run Online
First element: 10
Second element: 20
Third element: 30
Last element: 50

Array index reference

IndexElementValue
0numbers[0]10
1numbers[1]20
2numbers[2]30
3numbers[3]40
4numbers[4]50

Important: Accessing an element outside the valid array range causes undefined behavior.

5. Updating Array Elements in C++

You can change an array element by assigning a new value to its index.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};

    numbers[0] = 100;
    numbers[2] = 300;
    numbers[4] = 500;

    for (int i = 0; i < 5; i++) {
        cout << numbers[i] << endl;
    }

    return 0;
}

Output:

Explanation

  • numbers[0] = 100 updates the first element.

  • numbers[2] = 300 updates the third element.

  • numbers[4] = 500 updates the fifth element.

The array size remains unchanged.

6. Traversing an Array Using a for Loop

Traversing means visiting each array element one by one.

A for loop is commonly used to process all array elements.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};

    for (int i = 0; i < 5; i++) {
        cout << numbers[i] << endl;
    }

    return 0;
}

Output:

How does it work?

  1. The loop starts with i = 0.

  2. It checks whether i is less than 5.

  3. It prints the element at numbers[i].

  4. It increments i.

  5. The loop stops when i reaches 5.

This is one of the most common ways to process an array.

7. Traversing an Array Using a while Loop

You can also use a while loop to access array elements.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[5] = {10, 20, 30, 40, 50};

    int i = 0;

    while (i < 5) {
        cout << numbers[i] << endl;
        i++;
    }

    return 0;
}

Output:

The loop continues until every element has been processed.

8. Traversing an Array Using a Range-Based for Loop

C++11 introduced the range-based for loop.

It provides a simpler way to visit every element in an array.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    for (int value : numbers) {
        cout << value << endl;
    }

    return 0;
}

Output:

Modifying elements with a reference

If you want to modify the original elements, use a reference in the range-based loop.

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30};

    for (int& value : numbers) {
        value *= 2;
    }

    for (int value : numbers) {
        cout << value << endl;
    }

    return 0;
}

Output:

Using int value would modify only a copy. Using int& value allows the loop to update the original array elements.

9. Finding the Length of an Array

For a built-in array in the same scope where it is still an array, you can use the sizeof operator to calculate its number of elements.

Syntax

main.cpp
Run Online
sizeof(array) / sizeof(array[0])

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    int size = sizeof(numbers) / sizeof(numbers[0]);

    cout << "Array size: " << size << endl;

    return 0;
}

Output:

Explanation

  • sizeof(numbers) returns the total size of the array in bytes.

  • sizeof(numbers[0]) returns the size of one element.

  • Dividing the total size by the element size gives the number of elements.

Modern C++ alternative:

You can use std::size() from the <iterator> header in C++17 and later.

main.cpp
Run Online
#include <iostream>
#include <iterator>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    cout << size(numbers) << endl;

    return 0;
}

Output:

Remember that a built-in array passed to a function as an ordinary array parameter is adjusted to a pointer. In that function, sizeof(parameter) gives the pointer size, not the original array size. Pass the size separately or use a suitable container or array reference.

10. Finding the Sum of Array Elements

You can use a loop to calculate the sum of all array elements.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    int sum = 0;

    for (int i = 0; i < 5; i++) {
        sum += numbers[i];
    }

    cout << "Sum: " << sum << endl;

    return 0;
}

Output:

Explanation

The program starts with sum = 0 and adds each array element to the total.

This approach is useful for calculating marks, sales totals, expenses, and other numerical data.

11. Finding the Largest and Smallest Array Elements

Arrays are useful for comparing values and finding the maximum or minimum element.

Example: Finding the largest value

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {25, 80, 15, 100, 45};

    int largest = numbers[0];

    for (int i = 1; i < 5; i++) {
        if (numbers[i] > largest) {
            largest = numbers[i];
        }
    }

    cout << "Largest: " << largest << endl;

    return 0;
}

Output:

Example: Finding the smallest value

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {25, 80, 15, 100, 45};

    int smallest = numbers[0];

    for (int i = 1; i < 5; i++) {
        if (numbers[i] < smallest) {
            smallest = numbers[i];
        }
    }

    cout << "Smallest: " << smallest << endl;

    return 0;
}

Output:

Both examples assume the array contains at least one element.

12. Searching for an Element in an Array

You can search for a particular value by checking each element.

This method is called linear search.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    int searchValue = 30;
    int position = -1;

    for (int i = 0; i < 5; i++) {
        if (numbers[i] == searchValue) {
            position = i;
            break;
        }
    }

    if (position != -1) {
        cout << "Element found at index: " << position << endl;
    } else {
        cout << "Element not found" << endl;
    }

    return 0;
}

Output:

Explanation

  • The program checks each element.

  • When it finds 30, it stores the index.

  • break stops the loop.

  • The program prints the result.

Linear search works with both sorted and unsorted arrays.

13. Reversing an Array in C++

Reversing an array means changing the order of its elements so that the last element becomes the first.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[] = {10, 20, 30, 40, 50};

    int size = 5;

    for (int i = 0; i < size / 2; i++) {
        int temp = numbers[i];

        numbers[i] = numbers[size - 1 - i];

        numbers[size - 1 - i] = temp;
    }

    for (int value : numbers) {
        cout << value << " ";
    }

    return 0;
}

Output:

The program swaps elements from opposite ends until it reaches the middle.

14. One-Dimensional Arrays in C++

A one-dimensional array stores elements in a single sequence.

Syntax

main.cpp
Run Online
data_type array_name[size];

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int marks[5] = {70, 80, 85, 90, 95};

    for (int i = 0; i < 5; i++) {
        cout << "Student " << i + 1
             << ": " << marks[i] << endl;
    }

    return 0;
}

Output:

main.cpp
Run Online
Student 1: 70
Student 2: 80
Student 3: 85
Student 4: 90
Student 5: 95

One-dimensional arrays are useful for storing lists of marks, prices, ages, temperatures, and other related values.

15. Two-Dimensional Arrays in C++

A two-dimensional array stores values in rows and columns.

It is commonly used to represent tables and matrices.

Syntax

main.cpp
Run Online
data_type array_name[rows][columns];

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[2][3] = {
        {10, 20, 30},
        {40, 50, 60}
    };

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            cout << numbers[i][j] << " ";
        }

        cout << endl;
    }

    return 0;
}

Output:

Explanation

  • The array contains two rows.

  • Each row contains three columns.

  • numbers[i][j] accesses an element using its row and column indexes.

  • Nested loops traverse all elements.

16. Three-Dimensional Arrays in C++

A three-dimensional array stores elements using three indexes.

It can represent data arranged in layers, rows, and columns.

Syntax

main.cpp
Run Online
data_type array_name[layers][rows][columns];

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    int numbers[2][2][2] = {
        {
            {10, 20},
            {30, 40}
        },
        {
            {50, 60},
            {70, 80}
        }
    };

    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            for (int k = 0; k < 2; k++) {
                cout << numbers[i][j][k] << " ";
            }

            cout << endl;
        }

        cout << endl;
    }

    return 0;
}

Output:

Three-dimensional arrays are useful for certain scientific, mathematical, and simulation applications.

17. Character Arrays in C++

A character array stores individual characters.

Character arrays are sometimes used to represent C-style strings, which are terminated by the null character '\0'.

Example

main.cpp
Run Online
#include <iostream>
using namespace std;

int main() {
    char name[] = {'H', 'e', 'l', 'l', 'o', '\0'};

    cout << name << endl;

    return 0;
}

Output:

You can also initialize a character array using a string literal.

The compiler includes the terminating null character.

For ordinary text processing in modern C++, std::string is usually easier and safer.

18. Arrays vs Vectors in C++

Built-in arrays and std::vector are both used to store multiple values, but they have different features.

A built-in array has a fixed size, while a vector can grow or shrink dynamically.

Comparison table

FeatureBuilt-in arraystd::vector
SizeFixedDynamic
Declarationint a[5]vector<int> a
Memory managementAutomatic for local arraysManaged by the container
Adding elementsNo direct resizingpush_back()
Removing elementsNo direct resizingpop_back()
Accessa[i]a[i] or a.at(i)
Library supportLanguage featureStandard library container

Example using vector

main.cpp
Run Online
#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> numbers = {10, 20, 30};

    numbers.push_back(40);

    for (int value : numbers) {
        cout << value << " ";
    }

    return 0;
}

Output:

Use built-in arrays when a fixed-size array is appropriate. Prefer std::vector when the number of elements may change during program execution.

19. Common Mistakes When Working With Arrays

Beginners often make these mistakes when using arrays.

1. Accessing an invalid index

Incorrect:

main.cpp
Run Online
int numbers[5] = {10, 20, 30, 40, 50};

// Invalid: index 5 is outside the array.
cout << numbers[5];

Solution: For an array of five elements, use indexes from 0 to 4.

2. Forgetting that indexing starts at zero

The first element is numbers[0], not numbers[1].

3. Using an uninitialized local array

The elements are not automatically initialized to zero in this declaration.

Solution: Initialize the array when creating it, or assign values before reading them.

4. Using the wrong array size

The declared size must match the number of elements you intend to store.

5. Assuming arrays can grow automatically

Built-in arrays have a fixed size.

Solution: Use std::vector when you need a resizable collection.

6. Forgetting array size when passing to functions

An ordinary array parameter is adjusted to a pointer, so the function does not automatically know the original array length.

Solution: Pass the size separately or use std::array or std::vector.

20. Best Practices for Using Arrays in C++

Follow these practices when working with arrays:

  1. Use meaningful array names.

  2. Initialize elements before reading them.

  3. Always check valid array indexes.

  4. Use loops to process multiple elements.

  5. Use range-based for loops when suitable.

  6. Use const when array elements should not be modified.

  7. Prefer std::array for fixed-size collections when appropriate.

  8. Prefer std::vector for dynamically sized collections.

  9. Avoid hard-coding array sizes in multiple places.

  10. Test programs with empty, small, and large collections where applicable.

21. Frequently Asked Questions (FAQs)

Q1. What is an array in C++?

An array is a collection of elements of the same data type stored in a sequence and accessed using indexes.

Q2. How do you declare an array in C++?

Use the data type, array name, and size:

Q3. How do you initialize an array?

You can assign values when declaring it:

main.cpp
Run Online
int numbers[5] = {
  10, 20, 30, 40, 50
}
;

Q4. Does array indexing start from zero in C++?

Yes. The first element has index 0, the second has index 1, and so on.

Q5. How do you access an array element?

Use the array name followed by the element index:

Q6. Can we update array elements?

Yes. Assign a new value to a valid index:

Q7. What is a multidimensional array?

A multidimensional array uses more than one index. A two-dimensional array, for example, stores elements in rows and columns.

Q8. What is the difference between an array and a vector?

A built-in array has a fixed size, while std::vector can change its size dynamically.

Q9. How do you find the length of an array?

For a built-in array in its original scope, use sizeof(array) / sizeof(array[0]), or use std::size() in C++17 and later.

Q10. Can an array store different data types?

A built-in array stores elements of one type. To store different types together, consider structures, classes, or suitable standard library types such as std::variant.

Runnable Code Example: Arrays in C++

C++20 / C++23
main.cpp
Run Online
#include <iostream>
#include <array>

int main() {
    // Modern std::array
    std::array<int, 5> scores = {92, 85, 78, 95, 88};

    scores[0] = 96; // Direct indexing

    std::cout << "Array Size: " << scores.size() << "
";
    std::cout << "Elements: ";
    for (int score : scores) {
        std::cout << score << " ";
    }
    std::cout << "
";

    // Safe bounds-checked access
    try {
        std::cout << "Element at index 2: " << scores.at(2) << "
";
        // scores.at(10); // Throws std::out_of_range
    } catch (const std::out_of_range& e) {
        std::cerr << "Out of range error caught: " << e.what() << "
";
    }
    return 0;
}

Common C++ Technical Interview Questions & Answers

Interview Prep
Q

Q: Why does accessing an out-of-bounds array index in C-style arrays cause undefined behavior?

A: C++ does not perform runtime bounds checks on the `[]` operator for maximum speed. Accessing `arr[10]` in an array of size 5 reads or writes adjacent memory, causing data corruption or segmentation faults.
Q

Q: What is the benefit of std::array over built-in C-style arrays?

A: `std::array` provides a standard STL container interface (`size()`, `begin()`, `end()`, `at()`), does not decay to a pointer implicitly, can be passed and returned by value, and has identical memory layout with zero runtime performance cost.

Key Takeaways, Modern Best Practices & Idioms

C++ Best Practices & Production Rules

1. Replace raw C-style arrays with `std::array` for fixed sizes or `std::vector` for dynamic sizes. 2. Use `.at(index)` when bounds validation is critical to throw `std::out_of_range`. 3. Iterate with range-based for loops `for (const auto& x : arr)` to eliminate off-by-one errors.