Arrays in C++

This chapter dives deep into the world of arrays in C++, a fundamental building block for storing and manipulating collections of data. We'll explore everything you need to know, from the basic principles to advanced techniques. Buckle up, and get ready to become an array maestro!

Understanding Arrays

An array is a powerful data structure that allows you to store a fixed-size collection of elements all of the same data type under a single variable name. Imagine you have a shopping basket, and you can only put items of the same type (like fruits) in it. Arrays work similarly, but instead of physical objects, they hold data like numbers, characters, or even other arrays (we’ll get to that later).

Here’s the basic syntax for declaring an array in C++:

				
					data_type array_name[size];

				
			
  • data_type: This specifies the type of data the array can hold. It can be any fundamental data type like intfloatchar, or even user-defined types like structures.
  • array_name: This is the name you give to your array, just like a label for your shopping basket.
  • size: This is a whole number that defines the number of elements the array can hold. It’s crucial to remember that the size of an array is fixed once declared.
				
					int fruits[5]; // An array named 'fruits' that can hold 5 integers

				
			

This code creates an array named fruits that can store up to 5 integer values (like quantities of different fruits).

Accessing Elements

Now that you have your array, how do you access the individual elements within it? This is where indexing comes in. Arrays use a zero-based indexing system. This means the first element is at index 0, the second at index 1, and so on, up to the last element at index (size-1).

Here’s how you access and modify elements using their index:

				
					array_name[index] = value;  // Assigns 'value' to the element at 'index'
value = array_name[index];  // Reads the value from the element at 'index'

				
			
				
					fruits[0] = 2;  // Stores the value 2 (maybe 2 apples) in the first element (index 0)
int apple_count = fruits[0];  // Assigns the value stored at index 0 (2) to the variable 'apple_count'

				
			

Important Note: Be cautious with array indexing! Trying to access an element outside the valid range (0 to size-1) will result in undefined behavior, potentially causing errors in your program.

Initializing Arrays

There are two main ways to initialize an array with values:

  1. During declaration: You can directly assign values within curly braces {} while declaring the array.
				
					int veggies[3] = {1, 3, 2};  // Initializes 'veggies' with 1, 3, and 2 at indices 0, 1, and 2 respectively

				
			
  1. After declaration: You can use the assignment operator = to assign values to individual elements after the array is declared.
				
					char colors[4];
colors[0] = 'R';
colors[1] = 'G';
colors[2] = 'B';
colors[3] = 'W';  // Assigns 'R', 'G', 'B', and 'W' to the 'colors' array

				
			

Important Note: Be cautious with array indexing! Trying to access an element outside the valid range (0 to size-1) will result in undefined behavior, potentially causing errors in your program.

Array Operations

Now that you can create and access arrays, let’s explore some common operations you can perform on them

Finding the Sum or Average

Looping through each element in the array is essential for processing data. You can use a for loop to iterate from index 0 to size-1.

				
					#include <iostream>

int main() {

    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]); // Calculate size of array

    // Print array elements
    std::cout << "Array elements: ";
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl; // Print newline after printing array

    return 0;
}

				
			
				
					// output //
Array elements: 1 2 3 4 5 

				
			

Finding the Sum or Average

You can iterate through the array and accumulate values to calculate the sum or average of elements.

				
					#include <iostream>

int main() {
    // Sample array
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]); // Calculate size of array

    // Calculate sum of array elements
    int sum = 0;
    for (int i = 0; i < size; ++i) {
        sum += arr[i];
    }

    // Print the sum
    std::cout << "Sum of array elements: " << sum << std::endl;

    return 0;
}

				
			
				
					// output //
Sum of array elements: 15

				
			

Searching an Array

There are multiple ways to search for a specific value within an array. Here’s a simple linear search example:

				
					#include <iostream>

int main() {
    // Sample array
    int arr[] = {12, 45, 23, 6, 34, 78};
    int size = sizeof(arr) / sizeof(arr[0]); // Calculate size of array

    // Element to search
    int key = 34;

    // Linear search
    int index = -1;
    for (int i = 0; i < size; ++i) {
        if (arr[i] == key) {
            index = i;
            break; // Stop searching once the element is found
        }
    }

    // Print the result
    if (index != -1) {
        std::cout << "Element found at index: " << index << std::endl;
    } else {
        std::cout << "Element not found in the array." << std::endl;
    }

    return 0;
}

				
			
				
					// output //
Element found at index: 4

				
			

Explanation:

  • We define the array arr, its size size, and the key element key.
  • We perform linear search by iterating through the array using a for loop.
  • Inside the loop, we check if each element of the array is equal to the key element.
  • If the key element is found, we store its index in the variable index and break out of the loop.
  • After the loop, we check if index is still -1. If it’s not, we print the index where the element was found. Otherwise, we print a message indicating that the element was not found.

Sorting an Array

Sorting Algorithms are generally used to sort the arrays in ascending order from smaller to larger element.

Possible sorting Algorithms

  1. Bubble Sort
  2. Selection Sort
  3. Insertion Sort
  4. Merge Sort
  5. Quick Sort
  6. Heap Sort
  7. Radix Sort
  8. Bucket Sort

Bubble Sort Algorithm

				
					#include <iostream>

int main() {
    // Sample array
    int arr[] = {12, 45, 23, 6, 34, 78};
    int size = sizeof(arr) / sizeof(arr[0]); // Calculate size of array

    // Sorting the array using Bubble Sort algorithm
    for (int i = 0; i < size - 1; ++i) {
        for (int j = 0; j < size - i - 1; ++j) {
            if (arr[j] > arr[j + 1]) {
                // Swap elements if they are in the wrong order
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }

    // Print the sorted array
    std::cout << "Sorted array: ";
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

				
			
				
					// output //
Sorted array: 6 12 23 34 45 78 

				
			

Explanation:

  1. The Bubble Sort algorithm is used to sort the array.
  2. Two nested loops are used to iterate through the array.
  3. In the inner loop, adjacent elements are compared, and if they are in the wrong order, they are swapped.
  4. After each iteration of the outer loop, the largest element “bubbles up” to its correct position.
  5. This process repeats until the array is sorted.
  6. Finally, the sorted array is printed.

Note :  here we only use Bubble sort Algorithm , in the same way we can implement other as well for more optimization and reducing sorting time of elements

Using in-built Sort function

C++ provides in built sort function inside  which will sort the elements in minimum time and memory we will discuss this in more detail when we start learning about STL library.

				
					#include <iostream>
#include <algorithm> // for std::sort
#include <vector>    // for std::vector (optional)

int main() {
    // Sample array
    int arr[] = {12, 45, 23, 6, 34, 78};
    int size = sizeof(arr) / sizeof(arr[0]); // Calculate size of array

    // Sorting the array using std::sort
    std::sort(arr, arr + size);

    // Print the sorted array
    std::cout << "Sorted array: ";
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

				
			
				
					// output //
Sorted array: 6 12 23 34 45 78 

				
			

Explanation:

  1. We include the <algorithm> header to access the std::sort function and <iostream> for input-output operations.
  2. We define a sample array arr with unsorted elements.
  3. We calculate the size of the array using sizeof(arr) / sizeof(arr[0]).
  4. We call std::sort(arr, arr + size) to sort the array. std::sort accepts two iterators representing the beginning and end of the range to be sorted. Here, arr points to the beginning of the array, and arr + size points to one past the end of the array.
  5. The array arr is sorted in ascending order.
  6. We print the sorted array using a loop.
  7. Finally, we return 0 from the main() function, indicating successful execution.

Pointers and Arrays

Pointers and arrays are closely related in C++. The array name itself actually decays to a pointer to the first element. This allows for some advanced operations:

  • Passing Arrays to Functions: You can pass entire arrays to functions by passing the array name. However, this often decays to a pointer, so remember to handle it accordingly within the function.
				
					#include <iostream>

// Function to print array elements
void printArray(int arr[], int size) {
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;
}

int main() {
    // Sample array
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]); // Calculate size of array

    // Print array elements by passing array to function
    std::cout << "Array elements: ";
    printArray(arr, size);

    return 0;
}

				
			
				
					// output //
Array elements: 1 2 3 4 5 

				
			

Explanation:

  • We define a function printArray that takes an integer array arr and its size size as parameters.
  • Inside the function, we use a loop to iterate through the array and print each element.
  • In the main() function, we declare a sample array arr with values {1, 2, 3, 4, 5}.
  • We calculate the size of the array using sizeof(arr) / sizeof(arr[0]).
  • We then call the printArray function, passing the array arr and its size as arguments.
  • The printArray function prints all the elements of the array.
  • Finally, we return 0 from the main() function, indicating successful execution.

Advanced Topics

Dynamic Memory Allocation with new

While array size is fixed at declaration, C++ offers dynamic allocation using new to create arrays at runtime. However, proper memory management (using delete) is crucial to avoid memory leaks.

				
					int* ptr = new int[size];  // Allocate memory for 'size' integers
// Use the array pointed to by ptr
delete[] ptr;  // Deallocate memory when done

				
			
				
					#include <iostream>

int main() {
    int size;

    // Prompt user for the size of the array
    std::cout << "Enter the size of the array: ";
    std::cin >> size;

    // Dynamically allocate memory for the array
    int *arr = new int[size];

    // Populate the array with values
    std::cout << "Enter " << size << " integers:\n";
    for (int i = 0; i < size; ++i) {
        std::cin >> arr[i];
    }

    // Print the array elements
    std::cout << "Array elements: ";
    for (int i = 0; i < size; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    // Free dynamically allocated memory
    delete[] arr;

    return 0;
}
				
			
				
					// output //
Enter the size of the array: 5
Enter 5 integers:
1 2 3 4 5
Array elements: 1 2 3 4 5

				
			

Explanation:

  • We define a function printArray that takes an integer array arr and its size size as parameters.
  • Inside the function, we use a loop to iterate through the array and print each element.
  • In the main() function, we declare a sample array arr with values {1, 2, 3, 4, 5}.
  • We calculate the size of the array using sizeof(arr) / sizeof(arr[0]).
  • We then call the printArray function, passing the array arr and its size as arguments.
  • The printArray function prints all the elements of the array.
  • Finally, we return 0 from the main() function, indicating successful execution.

References and Arrays

References can be used as aliases to array elements, providing another way to access and modify elements indirectly.

Note : If you pass array inside a function every time it will be passed by reference only So if you modify Array elements inside a outside Function where array is passed as parameter it will reflect in main function as well  

				
					int numbers[3] = {7, 8, 9};
int &ref = numbers[1];  // Reference 'ref' refers to the element at index 1

ref = 15;  // Modifying 'ref' modifies the element at index 1 (numbers[1] becomes 15)

				
			
				
					#include <iostream>

int main() {
    int arr[5] = {1, 2, 3, 4, 5};

    // Create a reference to an array element
    int& ref = arr[2];

    std::cout << "Original array: ";
    for (int i = 0; i < 5; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    // Modify the array element through the reference
    ref = 10;

    std::cout << "Modified array: ";
    for (int i = 0; i < 5; ++i) {
        std::cout << arr[i] << " ";
    }
    std::cout << std::endl;

    return 0;
}

				
			
				
					// output //
Original array: 1 2 3 4 5 
Modified array: 1 2 10 4 5 

				
			

Explanation:

  • We declare an integer array arr with 5 elements.
  • We create a reference ref to the third element of the array (arr[2]).
  • We print the original array.
  • We modify the array element through the reference ref.
  • We print the modified array.

Arrays are versatile data structures in C++ that allow for efficient storage and manipulation of collections of elements. Understanding how to work with arrays is essential for writing robust and efficient C++ programs.Happy coding! ❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India