Arrays in C++ provide an efficient way to store and manage multiple values of the same data type under a single variable name. Whether you’re working with numbers, characters, or objects, arrays help organize and process data efficiently.
Here’s what makes arrays indispensable:
for
, while
, or even enhanced for
loops, arrays can be traversed to perform operations such as displaying values, summing elements, or reversing their order.For advanced needs, multidimensional arrays, like 2D arrays, enable handling grid-like data structures effectively. Dive into arrays to simplify your coding tasks and enhance data manipulation!
Arrays in C++ are used to store multiple values of the same type in a single variable, making it easier to manage large sets of data. Here’s an overview of arrays and how they work in C++:
An array is declared by specifying the data type, followed by the array name and its size in square brackets.
int arr[5];
You can initialize an array during declaration:
int arr[5]={1,2,3,4,5}
int arr[5]={0};
int arr[] = {10, 20, 30}; // compiler determines the size (3 elements)
array elements are accessed using an index.
Char s[2]={‘A’,’B’}
cout << arr[0]; // prints 1
cout << arr[4]; // prints 5
You can update elements using their index:
arr[2] = 10; // Updates the third element to 10
Traversing an array means accessing and processing each element of the array, typically in a sequential manner, from the first element to the last. It is commonly done using loops like for, while, or do-while.
You traverse an array to:
Examples for traversing array elements:
int a[5]={1,2,3,4,5}
for(int i=0;i<5;i++)
{
cout<<a[i];
}
Ways to traverse an array:
for loop:
for (int i = 0; i < size; i++) {
cout << arr[i] << endl;
}
while loop:
int i = 0;
while (i < size) {
cout << arr[i] << endl;
i++;
}
using the enhanced for loops
int a={1,2,3,4,5}
for(int i: a)
{
cout<<a[i];
}
reverse traversal:
a[size]={1,2,3,4,5}
for(int i=size-1;i>=0;i–)
{
cout<<a[i];
}
Declaring and initializing two dimensional array:
int arr[2][2]={{1,2},{3,4}}
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
cout<<a[i][j];
}
}
Indian Institute of Embedded Systems – IIES