The Wayback Machine - https://web.archive.org/web/20241122183006/https://www.geeksforgeeks.org/cpp-arrays/
Open In App

C++ Arrays

Last Updated : 10 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location.

For example, if we have to store the marks of 4 or 5 students then we can easily store them by creating 5 different variables but what if we want to store marks of 100 students or say 500 students then it becomes very challenging to create that numbers of variable and manage them. Now, arrays come into the picture that can do it easily by just creating an array of the required size.

Arrays-in-C++

Properties of Arrays in C++

  • 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 Declaration in C++

In C++, we can declare an array by simply specifying the data type first and then the name of an array with its size.

data_type array_name[Size_of_array];

Example

int arr[5];

Here,

  • int: It is the type of data to be stored in the array. We can also use other data types such as char, float, and double.
  • arr: It is the name of the array.
  • 5: It is the size of the array which means only 5 elements can be stored in the array.

array declaration in c++

Initialization of Array in C++

In C++, we can initialize an array in many ways but we will discuss some most common ways to initialize an array. We can initialize an array at the time of declaration or after declaration.

1. Initialize Array with Values in C++

We have initialized the array with values. The values enclosed in curly braces ‘{}’ are assigned to the array. Here, 1 is stored in arr[0], 2 in arr[1], and so on. Here the size of the array is 5.

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

2. Initialize Array with Values and without Size in C++

We have initialized the array with values but we have not declared the length of the array, therefore, the length of an array is equal to the number of elements inside curly braces.

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

3. Initialize Array after Declaration (Using Loops)

We have initialized the array using a loop after declaring the array. This method is generally used when we want to take input from the user or we cant to assign elements one by one to each index of the array. We can modify the loop conditions or change the initialization values according to requirements.

for (int i = 0; i < N; i++) {
arr[i] = value;
}

4. Initialize an array partially in C++

Here, we have declared an array ‘partialArray’ with size ‘5’ and with values ‘1’ and ‘2’ only. So, these values are stored at the first two indices, and at the rest of the indices ‘0’ is stored.

int partialArray[5] = {1, 2};

5. Initialize the array with zero in C++

We can initialize the array with all elements as ‘0’ by specifying ‘0’ inside the curly braces. This will happen in case of zero only if we try to initialize the array with a different value say ‘2’ using this method then ‘2’ is stored at the 0th index only.

int zero_array[5] = {0};

Accessing an Element of an Array in C++

Elements of an array can be accessed by specifying the name of the array, then the index of the element enclosed in the array subscript operator []. For example, arr[i].

Example 1: The C++ Program to Illustrate How to Access Array Elements

C++
//  C++ Program to Illustrate How to Access Array Elements
#include <iostream>
using namespace std;

int main()
{

    int arr[3];

    // Inserting elements in an array
    arr[0] = 10;
    arr[1] = 20;
    arr[2] = 30;

    // Accessing and printing elements of the array
    cout << "arr[0]: " << arr[0] << endl;
    cout << "arr[1]: " << arr[1] << endl;
    cout << "arr[2]: " << arr[2] << endl;

    return 0;
}

Output
arr[0]: 10
arr[1]: 20
arr[2]: 30

Update Array Element

To update an element in an array, we can use the index which we want to update enclosed within the array subscript operator and assign the new value.

arr[i] = new_value;

Traverse an Array in C++

We can traverse over the array with the help of a loop using indexing in C++. First, we have initialized an array ‘table_of_two’ with a multiple of 2. After that, we run a for loop from 0 to 9 because in an array indexing starts from zero. Therefore, using the indices we print all values stored in an array.

Example 2: The C++ Program to Illustrate How to Traverse an Array

C++
// C++ Program to Illustrate How to Traverse an Array
#include <iostream>
using namespace std;

int main()
{

    // Initialize the array
    int table_of_two[10]
        = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };

    // Traverse the array using for loop
    for (int i = 0; i < 10; i++) {
        // Print the array elements using indexing
        cout << table_of_two[i] << " ";
    }

    return 0;
}

Output
2 4 6 8 10 12 14 16 18 20 

Size of an Array in C++

In C++, we do not have the length function as in Java to find array size but we can calculate the size of an array using sizeof() operator trick. First, we find the size occupied by the whole array in the memory and then divide it by the size of the type of element stored in the array. This will give us the number of elements stored in the array.

data_type size = sizeof(Array_name) / sizeof(Array_name[index]);

Example 3: The C++ Program to Illustrate How to Find the Size of an Array

C++
// C++ Program to Illustrate How to Find the Size of an
// Array
#include <iostream>
using namespace std;

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

    // Size of one element of an array
    cout << "Size of arr[0]: " << sizeof(arr[0]) << endl;

    // Size of array '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;
}

Output
Size of arr[0]: 4
Size of arr: 20
Length of an array: 5

Relation between Arrays and Pointers in C++

In C++, arrays and pointers are closely related to each other. The array name is treated as a pointer that stored the memory address of the first element of the array. As we have discussed earlier, In array elements are stored at contiguous memory locations that’s why we can access all the elements of an array using the array name.

Example 4: Illustrating the Relationship between Array and Pointers

C++
// C++ Program to Illustrate that Array Name is a Pointer
// that Points to First Element of the Array
#include <iostream>
using namespace std;

int main()
{
    // Defining an array
    int arr[] = { 1, 2, 3, 4 };

    // Define a pointer
    int* ptr = arr;

    // Printing address of the arrary using array name
    cout << "Memory address of arr: " << &arr << endl;

    // Printing address of the array using ptr
    cout << "Memory address of arr: " << ptr << endl;

    return 0;
}

Output
Memory address of arr: 0x7fff2f2cabb0
Memory address of arr: 0x7fff2f2cabb0

Explanation:

In the above code, we first define an array “arr” and then declare a pointer “ptr” and assign the array “arr” to it. We are able to assign arr to ptr because arr is also a pointer. After that, we print the memory address of arr using reference operator (&) and also print the address stored in pointer ptr and we can see arr and ptr, both stores the same memory address.

Example 5: Printing Array Elements without Indexing in C++

We generally access and print the array elements using indexing. For example to access the first element we use array_name[0]. We have discussed above that the array name is a pointer that stored the address of the first element and array elements are stored at contiguous locations. Now, we are going to access the elements of an array using the array name only.

C++
// C++ Program to Print Array Elements without Indexing
#include <iostream>
using namespace std;

int main()
{

    // Define an array
    int arr[] = { 11, 22, 33, 44 };

    // Print elements of an array
    cout << "first element: " << *arr << endl;
    cout << "Second element: " << *(arr + 1) << endl;
    cout << "Third element: " << *(arr + 2) << endl;
    cout << "fourth element: " << *(arr + 3) << endl;

    return 0;
}

Output
first element: 11
Second element: 22
Third element: 33
fourth element: 44

Explanation

In the above code, we first declared an array “arr” with four elements. After that, we are printing the array elements. Let’s discuss how we do it. We discussed that the array name is a pointer that stores the address of the first element of an array so, to print the first element we have dereferenced that pointer (*arr) using dereferencing operator (*) which prints the data stored at that address.

To print the second element of an array we first add 1 to arr which is equivalent to (address of arr + size_of_one_element *1) that takes the pointer to the address just after the first one and after that, we dereference that pointer to print the second element. Similarly, we print rest of the elements of an array without using indexing.

Passing Array to Function in C++

To use arrays efficiently we should know how to pass arrays to function. We can pass arrays to functions as an argument same as we pass variables to functions but we know that the array name is treated as a pointer using this concept we can pass the array to functions as an argument and then access all elements of that array using pointer.

So ultimately, arrays are always passed as pointers to the function. Let’s see 3 ways to pass an array to a function that are majorly used.

1. Passing Array as a Pointer

In this method, we simply pass the array name in function call which means we pass the address to the first element of the array. In this method, we can modify the array elements within the function.

Syntax

return_type function_name ( data_type *array_name ) {
// set of statements
}

2. Passing Array as an Unsized Array

In this method, the function accepts the array using a simple array declaration with no size as an argument.

Syntax

return_type function_name ( data_type array_name[] ) {
// set of statements
}

3. Passing Array as a Sized Array

In this method, the function accepts the array using a simple array declaration with size as an argument. We use this method by sizing an array just to indicate the size of an array.

Syntax

return_type function_name(data_type array_name[size_of_array]){
// set of statements
}

Note: Array will be treated as a pointer in the passed function no matter what method we use. As the array are passed as pointers, they will loose the information about its size leading to a phenomenon named as Array Decay.

Example: Illustrating Different Ways to Pass Arrays to a Function

C++
#include <iostream>
using namespace std;

// passing array as a sized array argument
void printArraySized(int arr[3], int n)
{
    cout << "Array as Sized Array Argument: ";
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

// passing array as an unsized array argument
void printArrayUnsized(int arr[], int n)
{
    cout << "Array as Unsized Array Argument: ";
    for (int i = 0; i < n; i++) {
        cout << *(arr + i) << " ";
    }
    cout << endl;
}

// Passing array as a pointer argument
void printArrayPointer(int* ptr, int n)
{
    // Print array elements using pointer ptr
    // that store the address of array passed
    cout << "Array as Pointer Argument: ";
    for (int i = 0; i < n; i++) {
        cout << ptr[i] << " ";
    }
}

// driver code
int main()
{

    int arr[] = { 10, 20, 30 };

    // Call function printArray and pass
    // array and its size to it.
    printArraySized(arr, 3);
    printArrayUnsized(arr, 3);
    printArrayPointer(arr, 3);

    return 0;
}

Output
Array as Sized Array Argument: 10 20 30 
Array as Unsized Array Argument: 10 20 30 
Array as Pointer Argument: 10 20 30 

Multidimensional Arrays in C++

Arrays declared with more than one dimension are called multidimensional arrays. The most widely used multidimensional arrays are 2D arrays and 3D arrays. These arrays are generally represented in the form of rows and columns.

Multidimensional Array Declaration

Data_Type Array_Name[Size1][Size2]...[SizeN];

where,

  • Data_Type: Type of data to be stored in the array.
  • Array_Name: Name of the array.
  • Size1, Size2,…, SizeN: Size of each dimension.

Two Dimensional Array in C++

In C++, a two-dimensional array is a grouping of elements arranged in rows and columns. Each element is accessed using two indices: one for the row and one for the column, which makes it easy to visualize as a table or grid.

Syntax of 2D array

data_Type array_name[n][m];

Where,

  • n: Number of rows.
  • m: Number of columns.
    two dimensional array in c++

Example: The C++ Program to Illustrate the Two-Dimensional Array

C++
// c++ program to illustrate the two dimensional array
#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;
}

Output
0 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 in C++

The 3D array uses three dimensions. 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.

Declaration of Three-Dimensional Array in C++

To declare a 3D array in C++, we need to specify its third dimension along with 2D dimensions.

Data_Type Array_Name[D][R][C];

Where,

  • Data_Type: Type of data to be stored in each element.
  • Array_Name: Name of the array
  • D: Number of 2D arrays or Depth of array.
  • R: Number of rows in each 2D array.
  • C: Number of columns in each 2D array.

Example

int array[3][3][3];

three dimensional array in  c++

Example: The C++ Program to Illustrate the 3d Array

C++
// C++ program to illustrate the 3d array
#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;
}

Output
0st 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.

Related Articles



Previous Article
Next Article

Similar Reads

Multidimensional Arrays in C - 2D and 3D Arrays
Prerequisite: Arrays in C A multi-dimensional array can be defined as an array that has more than one dimension. Having more than one dimension means that it can grow in multiple directions. Some popular multidimensional arrays are 2D arrays and 3D arrays. In this article, we will learn about multidimensional arrays in C programming language. Synta
10 min read
Associative arrays in C++
Associative arrays are also called map or dictionaries. In C++. These are special kind of arrays, where indexing can be numeric or any other data type i.e can be numeric 0, 1, 2, 3.. OR character a, b, c, d... OR string geek, computers... These indexes are referred as keys and data stored at that position is called value. So in associative array we
2 min read
Count of distinct sums that can be obtained by adding prime numbers from given arrays
Given two arrays arr1[] and arr2[]. The task is to count the distinct sums that can be obtained while choosing a prime element from arr1[] and another prime element from arr2[].Examples: Input: arr1[] = {2, 3}, arr2[] = {2, 2, 4, 7} Output: 4 All possible prime pairs are (2, 2), (2, 2), (2, 7), (3, 2), (3, 2) and (3, 7) with sums 4, 4, 9, 5, 5 and
6 min read
Arrays and Strings in C++
Arrays An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used to store similar types of elements as in the data type must be the same for all elements. They can be used to store the collection of primitive data types such as int, float, doubl
5 min read
Jagged Arrays in C++
Prerequisite: Arrays in C++ An array of pointers in C++Dynamic 2D arrays in C++What is a Jagged Array? A jagged array is an array of arrays such that member arrays can be of different sizes, in 2D array terms for each row we can have a variable number of columns. These types of arrays are also known as Jagged arrays. Example: arr[3][] = 1 2 3 4 //
4 min read
Difference between Arrays and Pointers
The array and pointers are derived data types that have lots of differences and similarities. In some cases, we can even use pointers in place of an array, and arrays automatically get converted to pointers when passed to a function. So, it is necessary to know about the differences between arrays and pointers to properly utilize them in our progra
7 min read
Quickly merging two sorted arrays using std::merge() in C++ STL
C++ program to merge two sorted arrays of length 'n' and 'm' respectively in sorted order. Examples: Input: A[] = {3, 6, 9} B[] = {2, 7, 11} Output: C[] = {2, 3, 6, 7, 9, 11} Input: A[] = {1, 1, 3, 6, 9} B[] = {1, 2, 7, 11, 11} Output: C[] = {1, 1, 1, 2, 3, 6, 7, 9, 11, 11} We have discussed other approaches in below posts Merge two sorted arrays w
2 min read
Why is a[i] == i[a] in C/C++ arrays?
The definition of [] subscript operator operator in C, according to (C99, 6.5.2.1p2), is that E1[E2] is identical to (*((E1)+(E2))) Compilers use pointer arithmetic internally to access array elements. And because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of
2 min read
Initialization of Multidimensional Arrays in C++
In C++, multidimensional arrays are the type of arrays that have multiple dimensions, i.e., they can expand in multiple directions. In this article, we will discuss how to initialize the multidimensional arrays in C++. Methods to Initialize Multidimensional Array in C++We can initialize multidimensional arrays in C++ using the following ways: Initi
3 min read
One Dimensional Arrays in C++
One-dimensional arrays are like a row of boxes where you can store things where each box can hold one item, such as a number or a word. For example, in an array of numbers, the first box might hold 5, the second 10, and so on. You can easily find or change what's in each box by referring to its position, called an index. Arrays are handy because th
6 min read
Is std::vector So Much Slower Than Plain Arrays?
In C++, std::vector is a dynamic array provided by the Standard Template Library (STL), and it is commonly compared to plain arrays. A frequent question that arises is: Is std::vector significantly slower than plain arrays? The straightforward answer is no, std::vector is not significantly slower, though there are some performance differences we ne
6 min read
How to quickly swap two arrays of same size in C++?
Given two arrays a[] and b[] of same size, we need to swap their contents. Example : Input: a[] = {1, 2, 3, 4} b[] = {5, 6, 7, 8}Output: a[] = {5, 6, 7, 8}b[] = {1, 2, 3, 4} A simple solution is to iterate over elements of both arrays and swap them one by one. A quick solution is to use std::swap(). It can directly swap arrays if they are of same s
2 min read
Intersection of Two Arrays with Distinct Elements
Given two arrays a[] and b[] with distinct elements of size n and m respectively, the task is to find intersection (or common elements) of the two arrays. We can return the answer in any order. Note: Intersection of two arrays can be defined as a set containing distinct common elements between the two arrays. Examples: Input: a[] = { 5, 6, 2, 1, 4
9 min read
Variable Length Arrays (VLAs) in C
In C, variable length arrays (VLAs) are also known as runtime-sized or variable-sized arrays. The size of such arrays is defined at run-time. Variably modified types include variable-length arrays and pointers to variable-length arrays. Variably changed types must be declared at either block scope or function prototype scope. Variable length arrays
2 min read
C++ Programming Language
C++ is the most used and most popular programming language developed by Bjarne Stroustrup. C++ is a high-level and object-oriented programming language. This language allows developers to write clean and efficient code for large applications and software development, game development, and operating system programming. It is an expansion of the C pr
9 min read
30 OOPs Interview Questions and Answers (2024) Updated
Object-oriented programming, or OOPs, is a programming paradigm that implements the concept of objects in the program. It aims to provide an easier solution to real-world problems by implementing real-world entities such as inheritance, abstraction, polymorphism, etc. in programming. OOPs concept is widely used in many popular languages like Java,
15+ min read
C++ Interview Questions and Answers (2024)
C++ - the must-known and all-time favourite programming language of coders. It is still relevant as it was in the mid-80s. As a general-purpose and object-oriented programming language is extensively employed mostly every time during coding. As a result, some job roles demand individuals be fluent in C++. It is utilized by top IT companies such as
15+ min read
Virtual Function in C++
A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the meth
6 min read
Inheritance in C++
The capability of a class to derive properties and characteristics from another class is called Inheritance. Inheritance is one of the most important features of Object Oriented Programming in C++. In this article, we will learn about inheritance in C++, its modes and types along with the information about how it affects different properties of the
15+ min read
C++ Polymorphism
The word "polymorphism" means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. A real-life example of polymorphism is a person who at the same time can have different characteristics. A man at the same time is a father, a husband, and an employee. So the same person ex
7 min read
C++ Classes and Objects
In C++, classes and objects are the basic building block that leads to Object-Oriented programming in C++. In this article, we will learn about C++ classes, objects, look at how they work and how to implement them in our C++ program. What is a Class in C++?A class is a user-defined data type, which holds its own data members and member functions, w
10 min read
Decision Making in C (if , if..else, Nested if, if-else-if )
The conditional statements (also known as decision control structures) such as if, if else, switch, etc. are used for decision-making purposes in C programs. They are also known as Decision-Making Statements and are used to evaluate one or more conditions and make the decision whether to execute a set of statements or not. These decision-making sta
11 min read
Vector in C++ STL
In C++, vector is a dynamic array with the ability to resize itself automatically when an element is inserted or deleted. It is the part Standard Template Library (STL) and provide various useful functions for data manipulation. Let's take a look a simple example to demonstrate the use of vector container: [GFGTABS] C++ #include <bits/stdc++.h
9 min read
Map in C++ Standard Template Library (STL)
Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have the same key values. std::map is the class template for map containers and it is defined inside the <map> header file. Basic std::map Member FunctionsSome basic functions associated with std::
9 min read
Object Oriented Programming in C++
Object-oriented programming - As the name suggests uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc. in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data
10 min read
Operator Overloading in C++
in C++, Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning. In this article, we will further discuss about operator overloading in C++ with examples and see which operators we can or cannot overload in C++. C++ Operator OverloadingC++ has
9 min read
Templates in C++ with Examples
A template is a simple yet very powerful tool in C++. The simple idea is to pass the data type as a parameter so that we don't need to write the same code for different data types. For example, a software company may need to sort() for different data types. Rather than writing and maintaining multiple codes, we can write one sort() and pass the dat
10 min read
Friend Class and Function in C++
A friend class can access private and protected members of other classes in which it is declared as a friend. It is sometimes useful to allow a particular class to access private and protected members of other classes. For example, a LinkedList class may be allowed to access private members of Node. We can declare a friend class in C++ by using the
6 min read
Constructors in C++
Constructor in C++ is a special method that is invoked automatically at the time an object of a class is created. It is used to initialize the data members of new objects generally. The constructor in C++ has the same name as the class or structure. It constructs the values i.e. provides data for the object which is why it is known as a constructor
7 min read
Bitwise Operators in C
In C, the following 6 operators are bitwise operators (also known as bit operators as they work at the bit-level). They are used to perform bitwise operations in C. The & (bitwise AND) in C takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. The | (bitwise OR) in C takes two nu
7 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg