Progress5 of 20 topics

25% complete

Arrays in C++

Arrays are fundamental data structures in C++ that allow you to store multiple values of the same type in contiguous memory locations. They provide an efficient way to manage collections of data under a single variable name with indexed access.

What You'll Learn

  • How to declare and initialize arrays
  • Accessing and modifying array elements
  • Common array operations and techniques
  • Working with multi-dimensional arrays
  • The relationship between arrays and pointers
  • Passing arrays to functions
  • Array limitations and alternatives in C++

Array Basics in C++

An array in C++ is a collection of elements of the same data type, stored in adjacent memory locations. Each element can be accessed using an index, which starts from 0 for the first element.

Declaring Arrays

The basic syntax for declaring an array in C++ is:

cpp
1dataType arrayName[arraySize];

Here are some examples of array declarations:

cpp
1// Array of 5 integers
2int numbers[5];
3
4// Array of 10 characters
5char letters[10];
6
7// Array of 3 doubles
8double prices[3];
9
10// Array of 4 booleans
11bool flags[4];

Important Note

In C++, array size must be a constant expression known at compile time when declaring a fixed-size array. The array size cannot be a variable whose value is determined at runtime (unless you use dynamic memory allocation).

Initializing Arrays

There are several ways to initialize arrays in C++:

cpp
1// Method 1: Initialize at declaration with values
2int scores[5] = {90, 85, 78, 92, 88};
3
4// Method 2: Initialize with fewer values than the size
5// Remaining elements are initialized to 0
6int partialScores[5] = {90, 85, 78}; // Elements at index 3 and 4 will be 0
7
8// Method 3: Let the compiler determine the size based on elements
9int autoSized[] = {10, 20, 30, 40, 50}; // Size is 5
10
11// Method 4: Initialize all elements to the same value
12int allZeros[5] = {}; // All elements initialized to 0
13int allOnes[5] = {1, 1, 1, 1, 1};
14
15// Method 5: Initialize specific elements
16int sparse[10] = {0}; // First element is 0, rest are also 0
17sparse[5] = 50; // Only set the 6th element
18
19// C++11 and later: Uniform initialization syntax
20int modern[5]{10, 20, 30, 40, 50};

Accessing Array Elements

Array elements are accessed using their index in square brackets. Remember that array indices start at 0 in C++.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int scores[5] = {90, 85, 78, 92, 88};
6
7 // Accessing individual elements
8 cout << "First element: " << scores[0] << endl; // 90
9 cout << "Third element: " << scores[2] << endl; // 78
10 cout << "Last element: " << scores[4] << endl; // 88
11
12 // Modifying elements
13 scores[1] = 95; // Change the second element
14 cout << "Updated second element: " << scores[1] << endl; // 95
15
16 // Iterating through all elements
17 cout << "All scores: ";
18 for (int i = 0; i < 5; i++) {
19 cout << scores[i] << " ";
20 }
21 cout << endl;
22
23 return 0;
24}

Warning: Array Bounds

C++ does not perform automatic boundary checking on arrays. Accessing elements outside the array bounds (like scores[10] for an array of size 5) leads to undefined behavior, which might cause crashes or subtle bugs that are hard to detect.

Common Array Operations

Finding Array Size

Unlike some programming languages, C++ does not store the size of an array as part of the array itself. There are several ways to determine the size:

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int numbers[] = {10, 20, 30, 40, 50};
6
7 // Method 1: sizeof operator (works for fixed-size arrays)
8 int size = sizeof(numbers) / sizeof(numbers[0]);
9 cout << "Array size: " << size << endl; // 5
10
11 // Method 2: C++11 and later - std::size (since C++17)
12 // #include <iterator>
13 // cout << "Array size: " << std::size(numbers) << endl;
14
15 // Method 3: C++11 and later - range-based for loop doesn't need size
16 cout << "Array elements: ";
17 for (int num : numbers) {
18 cout << num << " ";
19 }
20 cout << endl;
21
22 return 0;
23}

Searching an Array

Here's how to search for an element in an array:

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int numbers[] = {10, 20, 30, 40, 50};
6 int size = sizeof(numbers) / sizeof(numbers[0]);
7 int searchValue = 30;
8 bool found = false;
9 int position = -1;
10
11 // Linear search
12 for (int i = 0; i < size; i++) {
13 if (numbers[i] == searchValue) {
14 found = true;
15 position = i;
16 break; // Exit the loop once found
17 }
18 }
19
20 if (found) {
21 cout << searchValue << " found at position " << position << endl;
22 } else {
23 cout << searchValue << " not found in the array" << endl;
24 }
25
26 return 0;
27}

Sorting an Array

You can sort arrays either by implementing sorting algorithms yourself or using the standard library:

cpp
1#include <iostream>
2#include <algorithm> // For std::sort
3using namespace std;
4
5int main() {
6 int numbers[] = {45, 12, 85, 32, 89, 39, 69, 44, 42, 1, 6, 8};
7 int size = sizeof(numbers) / sizeof(numbers[0]);
8
9 // Before sorting
10 cout << "Before sorting: ";
11 for (int i = 0; i < size; i++) {
12 cout << numbers[i] << " ";
13 }
14 cout << endl;
15
16 // Sort the array using std::sort
17 sort(numbers, numbers + size);
18
19 // After sorting
20 cout << "After sorting: ";
21 for (int i = 0; i < size; i++) {
22 cout << numbers[i] << " ";
23 }
24 cout << endl;
25
26 return 0;
27}

Multi-dimensional Arrays

C++ supports multi-dimensional arrays, which are essentially arrays of arrays. The most common type is the two-dimensional array, often used to represent matrices or grids.

Declaring and Initializing 2D Arrays

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 // Declaration of a 3x4 2D array (3 rows, 4 columns)
6 int matrix[3][4];
7
8 // Initialization with values
9 int grid[3][3] = {
10 {1, 2, 3}, // Row 0
11 {4, 5, 6}, // Row 1
12 {7, 8, 9} // Row 2
13 };
14
15 // Partial initialization (remaining elements set to 0)
16 int partialGrid[3][3] = {
17 {1, 2},
18 {4}
19 };
20
21 // Accessing elements
22 cout << "Element at grid[1][2]: " << grid[1][2] << endl; // 6
23
24 // Modifying elements
25 grid[0][0] = 10;
26 cout << "Modified element at grid[0][0]: " << grid[0][0] << endl; // 10
27
28 return 0;
29}

Iterating Through 2D Arrays

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int grid[3][3] = {
6 {1, 2, 3},
7 {4, 5, 6},
8 {7, 8, 9}
9 };
10
11 // Print the grid
12 cout << "Grid contents:" << endl;
13 for (int row = 0; row < 3; row++) {
14 for (int col = 0; col < 3; col++) {
15 cout << grid[row][col] << " ";
16 }
17 cout << endl; // New line after each row
18 }
19
20 // Sum of all elements
21 int sum = 0;
22 for (int row = 0; row < 3; row++) {
23 for (int col = 0; col < 3; col++) {
24 sum += grid[row][col];
25 }
26 }
27 cout << "Sum of all elements: " << sum << endl;
28
29 // Using C++11 range-based for loop (not as common for 2D arrays)
30 sum = 0;
31 for (auto &row : grid) {
32 for (int value : row) {
33 sum += value;
34 }
35 }
36
37 return 0;
38}

Common 2D Array Applications

  • Game boards (chess, tic-tac-toe)
  • Pixel-based graphics (image processing)
  • Mathematical matrices
  • Spreadsheet-like data
  • Maze or map representations

Higher-Dimensional Arrays

C++ supports arrays with 3 or more dimensions:

cpp
// 3D array (2x3x4)
int cube[2][3][4];
// 4D array
int hyperCube[2][3][4][5];
// Initialization example
int threeDArray[2][2][2] = {
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};

Arrays and Pointers

In C++, arrays and pointers are closely related. The name of an array can be thought of as a pointer to its first element.

cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int numbers[5] = {10, 20, 30, 40, 50};
6
7 // Array name is a pointer to the first element
8 int *ptr = numbers; // Same as &numbers[0]
9
10 // Accessing elements using pointer arithmetic
11 cout << "First element: " << *ptr << endl; // 10
12 cout << "Second element: " << *(ptr + 1) << endl; // 20
13 cout << "Third element: " << *(ptr + 2) << endl; // 30
14
15 // Equivalent array notation
16 cout << "First element: " << numbers[0] << endl; // 10
17 cout << "Second element: " << numbers[1] << endl; // 20
18 cout << "Third element: " << numbers[2] << endl; // 30
19
20 // Pointer arithmetic
21 ptr++; // ptr now points to the second element
22 cout << "Element at ptr: " << *ptr << endl; // 20
23
24 return 0;
25}

Array Decay

When an array is passed to a function, it "decays" into a pointer to its first element. This means that information about the array's size is lost. This is why functions that take arrays as parameters often require the size to be passed as a separate argument.

Passing Arrays to Functions

There are several ways to pass arrays to functions in C++:

cpp
1#include <iostream>
2using namespace std;
3
4// Method 1: Using array notation (actually passes a pointer)
5void displayArray(int arr[], int size) {
6 for (int i = 0; i < size; i++) {
7 cout << arr[i] << " ";
8 }
9 cout << endl;
10}
11
12// Method 2: Using pointer notation (equivalent to Method 1)
13void displayArrayWithPointer(int *arr, int size) {
14 for (int i = 0; i < size; i++) {
15 cout << arr[i] << " ";
16 }
17 cout << endl;
18}
19
20// Method 3: Using fixed-size array notation (size is part of type)
21void displayFixedArray(int arr[5]) {
22 // Still doesn't know the true size; 5 is just part of the type
23 for (int i = 0; i < 5; i++) {
24 cout << arr[i] << " ";
25 }
26 cout << endl;
27}
28
29// Method 4: Using a reference to an array (preserves size information)
30template <size_t N>
31void displayArrayWithSize(int (&arr)[N]) {
32 for (int i = 0; i < N; i++) {
33 cout << arr[i] << " ";
34 }
35 cout << endl;
36}
37
38// Modifying an array in a function
39void doubleValues(int arr[], int size) {
40 for (int i = 0; i < size; i++) {
41 arr[i] *= 2; // Modifies the original array
42 }
43}
44
45int main() {
46 int numbers[5] = {10, 20, 30, 40, 50};
47 int size = sizeof(numbers) / sizeof(numbers[0]);
48
49 cout << "Original array: ";
50 displayArray(numbers, size);
51
52 displayArrayWithPointer(numbers, size);
53 displayFixedArray(numbers);
54 displayArrayWithSize(numbers);
55
56 doubleValues(numbers, size);
57
58 cout << "Array after doubling: ";
59 displayArray(numbers, size);
60
61 return 0;
62}

Array Limitations and Modern Alternatives

While arrays are fundamental in C++, they have several limitations:

  • Fixed size that must be known at compile time (for stack-allocated arrays)
  • No built-in bounds checking
  • Cannot be easily resized
  • No built-in methods for common operations
  • Size information is lost when passed to functions

Modern C++ offers several alternatives to traditional arrays:

AlternativeDescriptionAdvantages
std::vectorDynamic array implementation
  • Automatically resizes as needed
  • Provides size information
  • Includes bounds-checked access method
std::arrayFixed-size array wrapper
  • Knows its own size
  • Provides bounds checking with at()
  • Works with STL algorithms
std::spanView of a contiguous sequence (C++20)
  • Non-owning view of array elements
  • Preserves size information
  • Works with any contiguous data
cpp
1#include <iostream>
2#include <vector> // For std::vector
3#include <array> // For std::array
4using namespace std;
5
6int main() {
7 // std::vector example
8 vector<int> vec = {10, 20, 30, 40, 50};
9 vec.push_back(60); // Add a new element
10
11 cout << "Vector contents: ";
12 for (int num : vec) {
13 cout << num << " ";
14 }
15 cout << endl;
16
17 // Using vector's methods
18 cout << "Vector size: " << vec.size() << endl;
19 cout << "Element at index 2: " << vec.at(2) << endl; // Bounds-checked access
20
21 // std::array example (fixed size, but with benefits over C-style arrays)
22 array<int, 5> arr = {10, 20, 30, 40, 50};
23
24 cout << "Array contents: ";
25 for (int num : arr) {
26 cout << num << " ";
27 }
28 cout << endl;
29
30 // Using array's methods
31 cout << "Array size: " << arr.size() << endl;
32 cout << "Element at index 2: " << arr.at(2) << endl; // Bounds-checked access
33
34 return 0;
35}

Common Array Algorithms and Techniques

Finding Maximum and Minimum

cpp
1int findMax(int arr[], int size) {
2 int max = arr[0];
3 for (int i = 1; i < size; i++) {
4 if (arr[i] > max) {
5 max = arr[i];
6 }
7 }
8 return max;
9}
10
11int findMin(int arr[], int size) {
12 int min = arr[0];
13 for (int i = 1; i < size; i++) {
14 if (arr[i] < min) {
15 min = arr[i];
16 }
17 }
18 return min;
19}

Reversing an Array

cpp
1void reverseArray(int arr[], int size) {
2 int start = 0;
3 int end = size - 1;
4
5 while (start < end) {
6 // Swap elements
7 int temp = arr[start];
8 arr[start] = arr[end];
9 arr[end] = temp;
10
11 // Move pointers
12 start++;
13 end--;
14 }
15}

Calculating Average

cpp
1double calculateAverage(int arr[], int size) {
2 if (size == 0) return 0;
3
4 int sum = 0;
5 for (int i = 0; i < size; i++) {
6 sum += arr[i];
7 }
8
9 return static_cast<double>(sum) / size;
10}

Array Rotation

cpp
1// Rotate array left by one position
2void rotateLeft(int arr[], int size) {
3 if (size <= 1) return;
4
5 int temp = arr[0];
6 for (int i = 0; i < size - 1; i++) {
7 arr[i] = arr[i + 1];
8 }
9 arr[size - 1] = temp;
10}
11
12// Rotate array right by one position
13void rotateRight(int arr[], int size) {
14 if (size <= 1) return;
15
16 int temp = arr[size - 1];
17 for (int i = size - 1; i > 0; i--) {
18 arr[i] = arr[i - 1];
19 }
20 arr[0] = temp;
21}

Best Practices

  • Use modern C++ containers like std::vector or std::array instead of raw arrays when possible
  • Check array bounds before accessing elements to prevent buffer overflows
  • Pass arrays with their size to functions to ensure proper handling
  • Consider const correctness for arrays that shouldn't be modified
  • Use range-based for loops for cleaner iteration (C++11 and later)
  • Prefer std::algorithms for common operations (sorting, searching, etc.)

Summary

Arrays in C++ provide a fundamental way to store and manipulate collections of data. While they have some limitations compared to more modern container types, understanding arrays is essential for C++ programming and forms the basis for understanding more advanced data structures.

In this tutorial, we covered:

  • Basic array declaration and initialization
  • Accessing and modifying array elements
  • Common array operations
  • Multi-dimensional arrays
  • The relationship between arrays and pointers
  • Techniques for passing arrays to functions
  • Modern alternatives to traditional arrays

As you continue your C++ journey, you'll find that the concepts learned here will apply to more sophisticated container types like vectors, which offer the benefits of arrays with additional features like dynamic resizing and bounds checking.

Related Tutorials

Learn about pointers and their relationship with arrays in C++.

Learn more

Learn about the Standard Template Library including vectors, a dynamic array alternative.

Learn more

Understand dynamic memory allocation and management in C++.

Learn more