Like other programming languages, in C++, an array is a collection of similar types of elements with contiguous memory locations.
In C++, std::array is a container that encapsulates fixed-size arrays. In C++, array indexing starts at 0. We can only store a fixed number of elements in a C++ array.
In C/C++ programming languages or other programming languages, storing a group of related data items in adjacent memory locations is called an array. Array elements can be accessed randomly using the array index. Arrays can store any type of primitive data types, including int, float, double, char, etc. In C/C++, arrays can also store derived data types, such as structures, pointers, and other data types, which is an additional feature. Below is a diagram of an array.
👇Click to receive👇
👉C Language Knowledge Resource Collection
Advantages of C++ Arrays
-
Code optimization (reducing code size)
-
Random access
-
Easy to traverse data
-
Easy to manipulate data
-
Easy to sort data, etc.
Disadvantages of C++ Arrays
-
Fixed size
Types of C++ Arrays
In C++ programming, there are two types of arrays:
-
One-dimensional arrays
-
Multi-dimensional arrays
C++ One-Dimensional Arrays
Let’s look at a simple example of a C++ array where we will create, initialize, and traverse the array.
#include <iostream>
using namespace std;
int main() {
int arr[5]={10, 0, 20, 0, 30}; // Create and initialize array
// Traverse array
for (int i = 0; i < 5; i++) {
cout << arr[i] << "\n";
}
}
Output:
10020030
C++ Array Example: Using foreach Loop to Traverse
We can also use a foreach loop to traverse the array elements. It returns the array elements one by one.
#include <iostream>
using namespace std;
int main() {
int arr[5]={10, 0, 20, 0, 30}; // Create and initialize array
// Traverse array
for (int i: arr) {
cout << i << "\n";
}
}
Output:
1020304050
Why Do We Need Arrays?
For a finite number of objects, we can use regular variables (v1, v2, v3, …), but when we need to save many instances, it becomes difficult to manage them with regular variables. To represent multiple instances in a variable, we use arrays.
What Happens If We Try to Access Elements Beyond the Array Bounds?
If we define an array of size 10, then the elements of the array will be indexed from 0 to 9.
If we try to access elements at index positions greater than 10, it results in undefined behavior.
Empty Members in C++ Arrays
In C++, the maximum number of elements that can be stored in an array is n. But what happens if we store fewer than n elements?
For example
// Store only 3 elements in the array
int x[6] = {19, 10, 8};
In this case, the array x has a width of 6 elements, but we only initialized it with three elements.
When this happens, the compiler fills the blank spaces with random values. This random value usually appears as 0.
Important Points to Remember When Using Arrays
-
Array indexing starts at 0. This means the first item stored is at index 0, which is x[0].
-
The last element of an array of size n is stored at index (n-1). The last element in this example is x[5].
-
Array elements have contiguous addresses. Consider the case where the address of x[0] is 2120.
The address of the next element x[1] will be 2124, followed by the address of x[2] being 2128, and so on.
In this case, each element size increases by four times. This is because the size of the int type is 4 bytes.
What is a Two-Dimensional Array?
Each element in this array is described by two indices, with the first index representing the row and the second index representing the column.
As you can see, using rows and columns organizes elements into a two-dimensional array; there are I rows and j columns.
What is a Multi-Dimensional Array?
Two-dimensional arrays are the most basic type of multi-dimensional arrays; they also fit the definition of multi-dimensional arrays. The dimension of an array has no limit.
How to Insert Elements into an Array?
int mark[5] = {19, 10, 8, 17, 9}; // Change the 4th element to 9
mark[3] = 9; // Get value from user input
// Store at the 3rd position
cin >> mark[2]; // Get value from user input
// Insert at the ith position
cin >> mark[i-1];
// Print the first element of the array
cout << mark[0]; // Print the ith element of the array
cout << mark[i-1];
How to Display the Sum and Average of Array Elements?
#include <iostream>
using namespace std;
int main() {
// Initialize array without specifying size
double numbers[] = {7, 5, 6, 12, 35, 27};
double sum = 0;
double count = 0;
double average;
cout << "The numbers are: ";
// Print array elements
// Using range-based for loop
for (const double &n : numbers) {
cout << n << " ";
// Calculate sum
sum += n;
// Count array elements
++count;
}
// Print sum
cout << "\nTheir Sum = " << sum << endl;
// Calculate average
average = sum / count;
cout << "Their Average = " << average << endl;
return 0;
}
Output:
The numbers are: 7 5 6 12 35 27Their Sum = 92Their Average = 15.3333
How to Display Array Elements?
#include <iostream>
using namespace std;
int main() {
int numbers[5] = {7, 5, 6, 12, 35};
cout << "The numbers are: ";
// Print array elements
// Using range-based for loop
for (const int &n : numbers) {
cout << n << " ";
}
cout << "\nThe numbers are: ";
// Print array elements
// Using traditional for loop
for (int i = 0; i < 5; ++i) {
cout << numbers[i] << " ";
}
return 0;
}
Output:
The numbers are: 7 5 6 12 35The numbers are: 7 5 6 12 35
Popular Recommendations
-
C Language Tutorial – Common Interview Questions and Answers (5)
-
CLion Tutorial – Comparing Files from the Command Line in CLion
-
C++ Tutorial – In-Depth Guide to C++ Language Storage Classes