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!
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];
int
, float
, char
, or even user-defined types like structures.
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).
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.
There are two main ways to initialize an array with values:
{}
while declaring the array.
int veggies[3] = {1, 3, 2}; // Initializes 'veggies' with 1, 3, and 2 at indices 0, 1, and 2 respectively
=
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.
Now that you can create and access arrays, let’s explore some common operations you can perform on them
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
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
You can iterate through the array and accumulate values to calculate the sum or average of elements.
#include
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
There are multiple ways to search for a specific value within an array. Here’s a simple linear search example:
#include
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
arr
, its size size
, and the key element key
.for
loop.index
and break out of the loop.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 Algorithms are generally used to sort the arrays in ascending order from smaller to larger element.
#include
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
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
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
#include // for std::sort
#include // 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
<algorithm>
header to access the std::sort
function and <iostream>
for input-output operations.arr
with unsorted elements.sizeof(arr) / sizeof(arr[0])
.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.arr
is sorted in ascending order.0
from the main()
function, indicating successful execution.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:
#include
// 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
printArray
that takes an integer array arr
and its size size
as parameters.main()
function, we declare a sample array arr
with values {1, 2, 3, 4, 5}
.sizeof(arr) / sizeof(arr[0])
.printArray
function, passing the array arr
and its size as arguments.printArray
function prints all the elements of the array.0
from the main()
function, indicating successful execution.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
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
printArray
that takes an integer array arr
and its size size
as parameters.main()
function, we declare a sample array arr
with values {1, 2, 3, 4, 5}
.sizeof(arr) / sizeof(arr[0])
.printArray
function, passing the array arr
and its size as arguments.printArray
function prints all the elements of the array.0
from the main()
function, indicating successful execution.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
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
arr
with 5 elements.ref
to the third element of the array (arr[2]
).ref
.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! ❤️