In C++, an array is a derived data type that is used to store multiple values of similar data types in a contiguous memory location.
Arrays in C++Create an Array
In C++, we can create/declare an array by simply specifying the data type first and then the name of the array with its size inside [] square brackets(better known as array subscript operator).
C++
data_type array_name [size]
This statement will create an array with name array_name that can store size elements of given data_type. Once the array is declared, its size cannot be changed.
Example:
C++
This will create an array with name arr that can store 5 integers.
Array DeclarationWhen we declared an array, the elements of array do not contain any valid value.
Initialize the Array
Initialization means assigning initial values to array elements. We can initialize the array with values enclosed in curly braces '{}' are assigned to the array. For example:
C++
int arr[5] = {2, 4, 8, 12, 16};
These values will be assigned sequentially. It means that the first element (index 0) will be 10, second will be 20, and so on. The number of values in the list cannot be more than the size of the array. But they can be less that the size. This is called partial initialization.
C++
The size of the array can be skipped if the size should be same as the number of values.
C++
int arr[] = {2, 4, 8, 12, 16};
Array InitializationMoreover, all the elements can be easily initialized to 0 as shown below:
C++
This method only works for 0, but not for any other value.
Note: The value assigned should be of the same type of the array elements specified in the declaration
Access Array Elements
Elements of an array can be accessed by their position (called index) in the sequence. In C++, indexes of an array starts from 0 instead of 1. We just have to pass this index inside the [] square brackets with the array name as shown:
C++
It is important to note that index cannot be negative or greater than size of the array minus 1. (0 ≤ index ≤ size - 1). Also, it can also be any expression that results in valid index value.
Example:
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {2, 4, 8, 12, 16};
// Accessing fourth element
cout << arr[3] << endl;
// Accessing first element
cout << arr[0];
return 0;
}
Update Array Elements
To change the element at a particular index in an array, just use the = assignment operator with new value as right hand expression while accessing the array element.
C++
array_name[index] = value;
Example:
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {2, 4, 8, 12, 16};
// Updating fourth element
arr[3] = 90;
cout << arr[3] << endl;
// Updating first element
arr[1] = 90;
cout << arr[0];
return 0;
}
Traverse Array
Traversing means visiting each element one by one. The advantage of array is that it can be easily traversed by using a loop with loop variable that runs from 0 to size - 1. We use this loop variable as index of the array and access each element one by one sequentially.
Example:
C++
#include <iostream>
using namespace std;
int main() {
int arr[5] = {2, 4, 8, 12, 16};
// Traversing and printing arr
for (int i = 0; i < 5; i++)
cout << arr[i] << " ";
return 0;
}
There are more methods to traverse array that are listed here - Traverse an Array in C++
Size of Array
In C++, we do not have the length function as in Java to find array size, but it can be calculated using sizeof() operator trick. First find the size occupied by the whole array in the memory, then divide it by the size of the single element. As all the elements will have same size (due to being same type), this will give us the size/length of the array.
C++
#include <iostream>
using namespace std;
int main() {
char arr[] = {'a', 'b', 'c', 'd', 'f'};
// Size of one element of an array
cout << "Size of arr[0]: " << sizeof(arr[0])
<< endl;
// Size of 'arr'
cout << "Size of arr: " << sizeof(arr) << endl;
// Length of an array
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Length of an array: " << n << endl;
return 0;
}
OutputSize of arr[0]: 1
Size of arr: 5
Length of an array: 5
To know more methods, refer to the article - Length of Array in C++
Arrays and Pointers
In C++, arrays and pointers are closely related to each other. The array name can be treated as a constant pointer that stored the memory address of the first element of the array.
C++
#include <iostream>
using namespace std;
int main() {
int arr[5];
// Printing array name
cout << arr << endl;
// Printing address of first element
cout << &arr[0];
return 0;
}
Output0x7ffd57920530
0x7ffd57920530
Internally, arrays operators are performed usingpointer arithmetic. So, we can do almost any array operation using by using pointer to the first element. For example, we can access all the elements of an array using pointer to the first element.
C++
#include <iostream>
using namespace std;
int main() {
int arr[] = {2, 4, 8, 12, 16};
// Define a pointer to first element
int* ptr = arr;
for (int i = 0; i < 5; i++)
cout << *(ptr + i) << " ";
return 0;
}
Refer to this article to know more - Relationship Between Pointer and Array
Pass Array to Function
Just like other datatypes in C, arrays can also be passed to functions as parameters for different tasks, but there is a catch. Arrays are always passed as pointers to the function. There are 3 different notations to pass arrays to functions:
C++
#include <stdio.h>
// Functions that take array as argument
void sized_array_notation(int arr[5]) {}
void unsized_array_notation(int arr[]) {}
void pointer_notation(int* arr) {}
int main() {
int arr[] = {2, 4, 8, 12, 16};
int n = sizeof(arr)/sizeof(arr[0]);
// Passing array
sized_array_notation(arr);
unsized_array_notation(arr);
pointer_notation(arr);
return 0;
}
No matter what notation we use, array will still be passed as pointer due to array decay. The direct consequence of this is that passed will lose the information about its size inside the function. It means that we cannot determine the size of the array using sizeof. The compiler will just treat the name arr as pointer and return the size accordingly. To resolve this, it is recommended to pass the size as additional parameter.
C++
#include <stdio.h>
// Functions that take array as argument
void sized_array_notation(int arr[5], int size) {}
void unsized_array_notation(int arr[], int size) {}
void pointer_notation(int* arr, int size) {}
int main() {
int arr[] = {2, 4, 8, 12, 16};
int n = sizeof(arr)/sizeof(arr[0]);
// Passing array
sized_array_notation(arr, n);
unsized_array_notation(arr, n);
pointer_notation(arr, n);
return 0;
}
Multidimensional Arrays
In the above examples, we saw 1D (one dimensional) array. This array's size can only increase in a single direction (called dimension). C provides the feature to have as many dimensions as desired for an array. Arrays declared with more than one dimension are called multidimensional arrays.
Create Multidimensional Array
C++
data_type array_name [size1][size2]...
where size1, size2 ... are the sizes of each dimension.
The complexity of the array operations increases exponentially with increase in dimensions. So, among multidimensional arrays, 2D arrays and 3D arrays are most widely used.
Two-Dimensional Array
In C++, a two-dimensional array is an array that can grow in two directions. It can be visualized as a table arranged in rows and columns. Each element is accessed using two indices: one for the row and one for the column.
Create 2D array
C++
#include <iostream>
using namespace std;
int main() {
// Declaring 2D array
int arr[4][4];
// Initialize 2D array using loop
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
arr[i][j] = i + j;
}
}
// Printing the element of 2D array
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
return 0;
}
Output0 1 2 3
1 2 3 4
2 3 4 5
3 4 5 6
Explanation: In the above code, we have declared a 2D array with 4 rows and 4 columns after that we initialized the array with the value of (i+j) in every iteration of the loop. Then we are printing the 2D array using a nested loop and we can see in the below output that there are 4 rows and 4 columns.
Three-Dimensional Array
The 3D array uses three dimensions. A can be visualized as a collection of various two-dimensional arrays piled on top of one another can be used to represent it. Three indices: the row index, column index, and depth index are used to uniquely identify each element in a 3D array.
Create 3D Array
C++
#include <iostream>
using namespace std;
int main() {
// Declaring 3d array
int arr[3][3][3];
// Initializing the array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
arr[i][j][k] = i + j + k;
}
}
}
// Printing the array
for (int i = 0; i < 3; i++) {
cout << i << "st layer:" << endl;
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
cout << arr[i][j][k] << " ";
}
cout << endl;
}
cout << endl;
}
return 0;
}
Output0st layer:
0 1 2
1 2 3
2 3 4
1st layer:
1 2 3
2 3 4
3 4 5
2st layer:
2 3 4
3 4 5
4 5 6
Explanation: In the above code, we have declared a 3D array and then initialized it using three nested for loops. After that, we printed all layers of the 3D array again using three nested for loops as seen in the output.
Properties of Arrays
- An array is a collection of data of the same data type, stored at a contiguous memory location.
- Indexing of an array starts from 0. It means the first element is stored at the 0th index, the second at 1st, and so on.
- Elements of an array can be accessed using their indices.
- Once an array is declared its size remains constant throughout the program.
- An array can have multiple dimensions.
- The size of the array in bytes can be determined by the sizeof operator using which we can also find the number of elements in the array.
- We can find the size of the type of elements stored in an array by subtracting adjacent addresses.
Array Practice Problems
The below practice problems provide you some commonly used scenarios and exercises for practicing arrays in C++:
Similar Reads
C++ Tutorial | Learn C++ Programming C++ is a popular programming language that was developed as an extension of the C programming language to include OOPs programming paradigm. Since then, it has become foundation of many modern technologies like game engines, web browsers, operating systems, financial systems, etc.Features of C++Why
5 min read
Introduction to c++
Difference between C and C++C++ is often viewed as a superset of C. C++ is also known as a "C with class" This was very nearly true when C++ was originally created, but the two languages have evolved over time with C picking up a number of features that either weren't found in the contemporary version of C++ or still haven't m
3 min read
Setting up C++ Development EnvironmentC++ is a general-purpose programming language and is widely used nowadays for competitive programming. It has imperative, object-oriented, and generic programming features. C++ runs on lots of platforms like Windows, Linux, Unix, Mac, etc. Before we start programming with C++. We will need an enviro
8 min read
Header Files in C++C++ offers its users a variety of functions, one of which is included in header files. In C++, all the header files may or may not end with the ".h" extension unlike in C, Where all the header files must necessarily end with the ".h" extension. Header files in C++ are basically used to declare an in
6 min read
Namespace in C++Name conflicts in C++ happen when different parts of a program use the same name for variables, functions, or classes, causing confusion for the compiler. To avoid this, C++ introduce namespace.Namespace is a feature that provides a way to group related identifiers such as variables, functions, and
6 min read
Writing First C++ Program - Hello World ExampleThe "Hello World" program is the first step towards learning any programming language and is also one of the most straightforward programs you will learn. It is the basic program that demonstrates the working of the coding process. All you have to do is display the message "Hello World" on the outpu
4 min read
Basics
C++ Data TypesData types specify the type of data that a variable can store. Whenever a variable is defined in C++, the compiler allocates some memory for that variable based on the data type with which it is declared as every data type requires a different amount of memory.C++ supports a wide variety of data typ
7 min read
C++ VariablesIn C++, variable is a name given to a memory location. It is the basic unit of storage in a program. The value stored in a variable can be accessed or changed during program execution.Creating a VariableCreating a variable and giving it a name is called variable definition (sometimes called variable
4 min read
Operators in C++C++ operators are the symbols that operate on values to perform specific mathematical or logical computations on given values. They are the foundation of any programming language.Example:C++#include <iostream> using namespace std; int main() { int a = 10 + 20; cout << a; return 0; }Outpu
9 min read
Basic Input / Output in C++In C++, input and output are performed in the form of a sequence of bytes or more commonly known as streams.Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory then this process is called input.Output Stream: If the direction of flow of bytes
5 min read
Control flow statements in ProgrammingControl flow refers to the order in which statements within a program execute. While programs typically follow a sequential flow from top to bottom, there are scenarios where we need more flexibility. This article provides a clear understanding about everything you need to know about Control Flow St
15+ min read
C++ LoopsIn C++ programming, sometimes there is a need to perform some operation more than once or (say) n number of times. For example, suppose we want to print "Hello World" 5 times. Manually, we have to write cout for the C++ statement 5 times as shown.C++#include <iostream> using namespace std; int
7 min read
Functions in C++A function is a building block of C++ programs that contains a set of statements which are executed when the functions is called. It can take some input data, performs the given task, and return some result. A function can be called from anywhere in the program and any number of times increasing the
9 min read
C++ ArraysIn C++, an array is a derived data type that is used to store multiple values of similar data types in a contiguous memory location.Arrays in C++Create an ArrayIn C++, we can create/declare an array by simply specifying the data type first and then the name of the array with its size inside [] squar
10 min read
Strings in C++In C++, strings are sequences of characters that are used to store words and text. They are also used to store data, such as numbers and other types of information in the form of text. Strings are provided by <string> header file in the form of std::string class.Creating a StringBefore using s
5 min read
Core Concepts
Pointers and References in C++In C++ pointers and references both are mechanisms used to deal with memory, memory address, and data in a program. Pointers are used to store the memory address of another variable whereas references are used to create an alias for an already existing variable. Pointers in C++ Pointers in C++ are a
5 min read
new and delete Operators in C++ For Dynamic MemoryIn C++, when a variable is declared, the compiler automatically reserves memory for it based on its data type. This memory is allocated in the program's stack memory at compilation of the program. Once allocated, it cannot be deleted or changed in size. However, C++ offers manual low-level memory ma
6 min read
Templates in C++C++ template is a powerful tool that allows you to write a generic code that can work with any data type. The idea is to simply pass the data type as a parameter so that we don't need to write the same code for different data types.For example, same sorting algorithm can work for different type, so
9 min read
Structures, Unions and Enumerations in C++Structures, unions and enumerations (enums) are 3 user defined data types in C++. User defined data types allow us to create a data type specifically tailored for a particular purpose. It is generally created from the built-in or derived data types. Let's take a look at each of them one by one.Struc
3 min read
Exception Handling in C++In C++, exceptions are unexpected problems or errors that occur while a program is running. For example, in a program that divides two numbers, dividing a number by 0 is an exception as it may lead to undefined errors.The process of dealing with exceptions is known as exception handling. It allows p
11 min read
File Handling through C++ ClassesIn C++, programs run in the computerâs RAM (Random Access Memory), in which the data used by a program only exists while the program is running. Once the program terminates, all the data is automatically deleted. File handling allows us to manipulate files in the secondary memory of the computer (li
8 min read
Multithreading in C++Multithreading is a technique where a program is divided into smaller units of execution called threads. Each thread runs independently but shares resources like memory, allowing tasks to be performed simultaneously. This helps improve performance by utilizing multiple CPU cores efficiently. Multith
5 min read
C++ OOPS
Standard Template Library (STL)
Practice Problem