Home Icon Home Resource Centre Array In C++ | Define, Types, Access & More (Detailed Examples)

Table of content: 

  • What Is Array In C++?
  • How To Declare An Array In C++?
  • How To Initialize An Array In C++?
  • How To Access Elements Of An Array In C++?
  • How To Update/ Change Elements In An Array In C++?
  • How To Insert & Print Elements In An Array In C++?
  • C++ Array With Empty Members
  • Size Of An Array In C++
  • How To Pass An Array To A Function In C++?
  • What Does Out Of Bounds Array In C++ Mean?
  • C++ Array Types
  • Pointers And Array In C++
  • Other Ways To Declare An Array In C++
  • Advantages & Disadvantages Of An Array In C++
  • Conclusion
  • Frequently Asked Questions
expand icon

Array In C++ | Define, Types, Access & More (Detailed Examples)

Arrays in C++ are a collection of elements stored in contiguous memory locations. All elements in an array are of the same data type and are accessed using an index. The first element has an index of 0, the second element has an index of 1, and so on.
Schedule Icon 0 min read
Array In C++ | Define, Types, Access & More (Detailed Examples)

An array in C++ is a collection of elements of the same data type arranged in consecutive memory locations. This powerful data structure allows us to manage and organize data efficiently, providing easy access to each element using an index.

In this article, we'll explore the different aspects of arrays in C++. We'll start by understanding how to declare and initialize arrays, followed by discussing their advantages, limitations, and common use cases.

What Is Array In C++?

An array in C++ language is a group of identical data type objects that are kept in contiguous memory locations, and each array can be accessed independently using the index. In other words, arrays are utilized to store numerous values of the same data type in a single variable.

In the diagram below, you can see an array with 7 elements. The syntax for this is given at the top of the image.

Representation of an array in C++

The line of code in the image above shows how to declare an array of integers with 7 elements. That is-

  • The expression int myArray[7] signifies that the elements will be of integer data type. The name of the array is myArray, and it has 7 elements. We will discuss this in greater detail in the next section.
  • Each empty box in the image above corresponds to a component of the array. These values are of the type int in this instance. The numbers 0 through 6 represent the position of the elements, with 0 being the first and 6 being the last. The index for the first element of the array in C++ is always zero.

Array indexing in C++

How To Declare An Array In C++?

Declaration of array in C++

Whenever declaring an array in C++, you must typically provide both the size and the type of elements it will contain. In short, we must write the data type, the array name, and a bracket [ ]( index notation) indicating the number of elements the array holds.

The following is the syntax for declaring an array in C++:

type arrayName[arraySize];

Here,

  • The term type refers to the data type of elements in the array.
  • The arrayName refers to the name given to the array being created.
  • And the arraySize refers to the number of elements that will be there in the entire collection or array.

Example: string names[2];

The snippet above, when used in a code, will declare an array with two string elements, just like a  normal variable.

For Example: string names[2] = {"John", "Mark"};

Rules For Declaring A Single-Dimension Array In C++

When declaring a single-dimension array in C++, there are a few rules you need to follow to ensure correct syntax and behavior. Here are the rules for declaring a single-dimension array:

  1. Specify the Data Type: We must specify the data type of the elements that the array will hold beforehand. The data type can be any fundamental data type (e.g., int, double, char) or user-defined data type (e.g., structures or classes). It is also important to note that an array in C++ can hold elements of a single data type only.

  2. Choose a Valid Identifier: The name of the array must be a valid identifier, following the rules of C++ naming conventions (e.g., cannot start with a digit, cannot contain spaces, etc.). The name should be meaningful and reflect its purpose.

  3. Use Square Brackets: Square brackets [] are used to declare an array. You specify the size of the array within these brackets. If the size is not known at compile-time, you must use a constant expression or a literal. Example: int numbers[5];

  4. Zero-Based Indexing: In C++, array indexing is zero-based, meaning the first element is accessed using index 0, the second using index 1, and so on. The last element is accessed using the index arraySize - 1. We will discuss the method of accessing elements in a section later on.

  5. Initialization (Optional): You can optionally initialize the array elements at the time of declaration. Initialization can be done using an initializer list, enclosing the values within curly braces {} and separating them with commas. Example: int numbers[5] = {1, 2, 3, 4, 5};

  6. Fixed Size: The size of the array is fixed at compile time, and it cannot be changed during the program's execution. If you need a dynamically sized collection, you might have to consider using a dynamic data structure like a vector or allocating memory dynamically using pointers. Example: int dynamicArray[]; // Not allowed, size must be specified

How To Initialize An Array In C++?

In C++, there are various ways to initialize an array, depending on the specific needs of your program. We can initialize an array either at the time of declaration or afterwards. Let's explore some of the most commonly used methods for initialization of arrays in C++. 

Initialization of array in C++

1. Initializing An Array At Time Of Declaration (Inline Initialization Of Array In C++)

We can initialize an array directly when it is declared by providing a list of values enclosed in curly braces {}(known as list initializers). This process is known as direct initialization.

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

In this example, arr[0] is initialized to 1, arr[1] to 2, and so on. The size of the array is explicitly defined as 5. This method is clear and concise, ensuring that each element is assigned its respective value right at the start.

2. Initializing An Array Without Specifying Size (Implicit Size, Inline Initialization Of Arrays In C++)

We can initialize an array without explicitly specifying its size. In this case, the compiler automatically determines the size based on the number of elements provided.

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

Here, the size of the array is inferred from the number of values inside the curly braces, which in this case is 5. This approach is useful when the exact size of the array is not critical or when we want the array size to be flexible.

3. Initializing An Array In C++ Separately Using Loops

Arrays can also be initialized after their declaration using loops. This method is especially useful for dynamic initialization, where values may be determined at runtime.

int arr[5];
for (int i = 0; i < 5; i++) {
arr[i] = i + 1;
}

In this method, we declare the array first and then use a loop to assign values to each element. For instance, the above loop initializes arr[0] with 1, arr[1] with 2, and so forth. This approach is highly flexible, allowing us to modify the loop conditions or the values assigned to meet specific requirements.

Now let's take a look at an example to see how this is implemented in practice.

Code:

Output:

myArray: [10, 20, 30]
First element: 10
Second element: 20
Third element: 30

Explanation:

  1. In the code above, we declare and initialize an array called myArray with three elements: 10, 20, and 30.
  2. During the declaration, we provide the initial values of the elements within curly braces {}, as mentioned in the code comment.
  3. The size of the array is automatically determined based on the number of elements in the initializer list.
  4. Next, we start a for loop, which iterates through the array and prints its elements.
  5. We use sizeof(myArray) / sizeof(myArray[0]) to calculate the number of elements in the array, which ensures that the loop iterates through all the elements.
  6. Finally, we access and print individual elements of the array using index notation along with the cout command. (For e.g., myArray[0] for the first element, myArray[1] for the second element, and so on).
  7. The output shows the initialized array and the values of its elements.

How To Access Elements Of An Array In C++?

In C++, each element in an array is accessed using an index value (with array subscript operator), which is a unique number representing the position of the element within the array. Array indices start at 0 and go up to size -1, where size is the total number of elements in the array. There are two primary methods to access elements of an array:

Using Index Values To Directly Access Elements Of Array In C++ 

As we've mentioned before, each element in an array is associated with a unique index, starting from 0 up to size - 1. We can use this index value, specified inside square brackets, to access a specific element. This method is straightforward and ideal for accessing or modifying a single element when you know its index. 

Syntax:

arrayName[index]

Here:

  • arrayName: The name of the array.
  • index: The index of the element you want to access (must be an integer value within the range [0, size - 1]).

Code: 

Output:

Element at index 0: 10
Element at index 3: 40

Explanation: 

In the above code example-

  1. Inside the main() function, we declare and initialize an integer array arr of size 5 with the values {10, 20, 30, 40, 50}.
  2. We then access and print specific elements of the array directly using their index values.
    • We access the element at index 0 and print its value, which is 10.
    • Similarly, we access the element at index 3 and print its value, which is 40.
  3. Finally, the main() function returns 0, indicating that the program has completed successfully.

Using Loops To Traverse & Access Elements Of Array In C++ 

We can use loops to traverse (hence access and process) all the elements of an array in C++. The use of for loops to iterate over the array indices from 0 to (size-1), is a common way to access and perform operations on each element sequentially.

Syntax: 

for (int i = 0; i < size; ++i) {
// Access array elements using arrayName[i]
}

Code:

Output:

Array elements:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50

Explanation: 

In the above code example-

  1. Inside the main() function, we declare and initialize an integer array arr of size 5 with the values {10, 20, 30, 40, 50}.
  2. To display the elements of the array, we use a for loop that iterates through the array indices from 0 to 4.
  3. During each iteration of the loop, we print the index and the value of the element at that index using cout.
  4. Finally, the main() function returns 0, indicating that the program executed successfully.

How To Update/ Change Elements In An Array In C++?

Updating or changing elements in an array in C++ is a straightforward process. Each element in an array is accessed using its index, starting from 0 for the first element. To modify an element, we simply assign a new value to the specific index. This can be done individually for each element or in bulk using loops.

Code: 

Output: 

Updated array: 10 20 100 40 50

Explanation: 

In the above code example-

  1. Inside the main() function, we declare an integer array arr of size 5 and initialize it with the values {10, 20, 30, 40, 50}.
  2. Next, we update the third element of the array (arr[2]). Since array indices start at 0, arr[2] corresponds to the third element. We change its value from 30 to 100.
  3. To display the updated array, we use a for loop that iterates through each element of the array.
  4. We use cout to print each element of the array, followed by a space for readability.
  5. Finally, the main() function returns 0, indicating successful execution of the program.

How To Insert & Print Elements In An Array In C++?

To insert and print elements in an array in C++, we first declare an array with a fixed size and initialize its elements. To insert a new element, we choose the position for insertion, ensuring there's enough space in the array. We then use a loop to input values and store them in the array. After inserting the element, we use another loop to print the array’s contents. This method helps us manage array indices and avoid out-of-bounds errors while ensuring that our array operations are smooth and effective.

Code:

Output: 

Enter 5 Array Elements: 4 6 7 3 5
Enter Element to Insert: 8
The New Array is:
4 6 7 3 5 8

Explanation: 

In the above code example-

  1. Inside the main() function, we declare an integer array arr of size 6, and two integer variables: i for loop iteration and elem to hold the new element we want to insert.
  2. Next, we prompt the user to enter 5 array elements and use a for loop to read these elements from the user and store them in the array arr.
  3. After that, we again ask the user to enter an additional element. We insert this new element into the 6th position of the array (i.e. index 5), which was previously unassigned.
  4. Finally, we print a message indicating the updated array, then use a for loop to print all 6 elements of the array.

C++ Array With Empty Members

An array in C++ can be initialized with some elements while leaving the rest of its members uninitialized. When an array is partially initialized, the elements that are not explicitly initialized are given default values. For built-in types like int, float, or char, the behavior depends on whether the array is a local (automatic) or static array. Local arrays have undefined values in uninitialized positions, whereas static arrays are automatically initialized to zero.

Here’s a small code example demonstrating this-

Code:

Output:

Array elements:
Element 0: 1
Element 1: 2
Element 2: 0
Element 3: 0
Element 4: 0

Explanation:

In the above code example-

  1. Inside the main() function, we declare an integer array arr of size 5, but we only provide two initial values {1, 2}. The remaining empty elements of the array are automatically initialized to 0.
  2. We then use a for loop to print each element of the array. The loop runs from index 0 to 4, covering all the indices of the array.
  3. For each iteration, we print the index and the corresponding element value. Since only the first two elements were explicitly initialized, the rest of the empty elements are 0 by default.
  4. Finally, the main() function returns 0, signaling the successful completion of the program.

Size Of An Array In C++

The size of an array in C++ refers to the total number of elements that the array can hold. This size is fixed at the time of array declaration and cannot be changed during runtime. The size of array determines the number of memory locations allocated for storing its elements, and it's crucial to know this size when performing operations like traversing or accessing elements.

The size can be calculated using the sizeof operator, which returns the total memory occupied by the array in bytes. To determine the number of elements, you can divide the total size of the array by the size of a single element. 

Syntax: 

sizeof(arrayName) / sizeof(arrayName[0])

Here, 

  • sizeof(arrayName): Returns the total size of the array in bytes.
  • sizeof(arrayName[0]): Returns the size of the first element in the array, which is the size of one element of the array type.
  • arrayName: The name of the array whose size is being determined.

Code: 

Output: 

The size of the array is: 5

Explanation: 

In the above code example-

  1. Inside the main() function, we declare and initialize an integer array arr with 5 elements, specifically {10, 20, 30, 40, 50}.
  2. To calculate the size of the array, we use the sizeof operator.
    • The sizeof(arr) gives us the total memory size of the array in bytes, while sizeof(arr[0]) gives us the size of a single element.
    • By dividing these two values, we obtain the number of elements in the array, which we store in the variable size.
  3. We then print the calculated size of the array, which is 5.

How To Pass An Array To A Function In C++?

In C++, you can pass an array to a function by either directly passing the array as an argument or passing a pointer to the array. When you pass an array to a function, the function can access and modify the elements of the array. Here are the two common methods to pass an array to a function:

Method 1: Pass Array As Function Parameter

In this method, you directly pass the array as a function parameter. The array is passed by reference, meaning any modifications made to the array inside the function will affect the original array outside the function. For example:

Code:

Output:

10 20 30 40 50

Method 2: Pass Array As A Pointer

In this method, you pass a pointer to the array as a function parameter. This method is equivalent to passing the array by reference. Again, any changes made to the array inside the function will affect the original array. Look at the example below for a better understanding.

Code:

Output:

10 20 30 40 50

What Does Out Of Bounds Array In C++ Mean?

Accessing elements of an array in C++ outside its defined bounds leads to undefined behavior. It is commonly referred to as an "array out of bounds" or "array index out of range" error in programming. Let's understand what happens when you access elements out of bounds and how to avoid such errors.

Accessing out of bound array in C++

When you access an array element using an index, the C++ compiler does not perform any built-in bounds checking to ensure that the index is within the valid range. Instead, it assumes that you, as the programmer, have provided a valid index, and will proceed to read or write to the memory location corresponding to that index.

Code:

Output:

numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
Attempting to access numbers[10] = 1310551306

Explanation:

  1. In the code above, we first declare an integer array arr with 5 elements. The elements of the array are initialized with the values 10, 20, 30, 40, and 50.
  2. We then use a for loop to access and print each element of the array within its valid bounds, which are indices 0 to 4. The loop iterates over each index, and we output the index along with the corresponding value from the array.
  3. After accessing the elements within bounds, we attempt to access an element outside the bounds of the array by setting an index variable to 10, which is greater than the maximum valid index (4). We then try to access numbers[10] and print its value.
  4. Accessing an element outside the bounds of the array, like numbers[10], is undefined behavior in C++. This can lead to unexpected results or program crashes, as the index is out of the array's valid range.
  5. Note that every time you run the code, the output for index 10, will change.

C++ Array Types

The cpp arrays can be divided into several types depending on their size, storage duration, and how they are created. Listed below are some of the most common types of C++ arrays:

We have already discussed the single-dimensional array in detail in the examples discussed above. Let's look at the other type of arrays in C++:

Two-Dimensional Array In C++

A two-dimensional array is a collection of elements organized in rows and columns. It can be visualized as a grid or a matrix. To access an element in a 2D array, you need to specify both the row and column indices.

Syntax:

type array-Name [ x ][ y ];

Here,

  • The type represents the data type of array elements.
  • The array-Name is the name given to the array.
  • And x and y represent the number of columns and rows, respectively.

Multi-Dimensional Array In C++

Representation of multi-dimensional array in C++

Within the realm of C++, a collection of arrays with numerous dimensions is known as a multidimensional array. It is more commonly referred to as an array of arrays. An array that has more than one dimension can take on various forms, such as a two-dimensional array or 2D array, a three-dimensional array or 3D array, or an N-level dimensional array. In the above forms mentioned, two-dimensional and three-dimensional arrays are usually used in C++.

Syntax of an array of arrays or multi-dimensional array:

type name[size1][size2]...[sizeN];

Here,

  • The type is a valid data type,
  • The name is the name of the array,
  • And size1, size2,..., and sizeN are the sizes of each dimension of the array.

Code:

Output:

1 2 3 4
5 6 7 8
9 10 11 12

13 14 15 16
17 18 19 20
21 22 23 24

Explanation:

In the above code example-

  1. We declare a three-dimensional or 3D array integer array named arr inside the main() function and give a starting value range of 1 to 24.
  2. Then, we access each element of the array and display it on the console using three nested loops.
  3. Due to the array's two layers, the outer loop goes from 0 to 1. There are 3 rows in each layer which is why the center loop goes from 0 to 2.
  4. Since each layer has four columns, the inner loop goes from 0 to 3.
  5. The cout statement is used to display each element of the array inside the innermost loop.
  6. The return statement is then utilized to end the program.

Pseudo-Multidimensional Array In C++

C++ pseudo multidimensional arrays are special arrays composed of just one block of allocated memory, yet they behave as if they were multidimensional due to their use of pointer arithmetic for component access. By utilizing this technique, you could represent even large two-dimensional arrays with just one single-dimensional structure.

When it comes time to retrieve elements from this array, simply rely on the formula: a[i * n + j]. This will enable quick and easy access based on row i and column j.

Code:

Output:

1 2 3
4 5 6

Explanation:

In the code example,

  1. Inside the main() function, we declare and initialize a one-dimensional integer array arr with 6 elements: {1, 2, 3, 4, 5, 6}. This array is used to simulate a pseudo multidimensional array with 2 rows and 3 columns.
  2. We then use nested for loops to print the elements of this pseudo multidimensional array.
  3. The outer loop iterates through the rows (i ranging from 0 to 1), and the inner loop iterates through the columns (j ranging from 0 to 2).
  4. Inside the inner loop, we calculate the index for accessing elements in the one-dimensional array. The index is computed as i * 3 + j, where i represents the current row and j represents the current column. This formula maps the 2D indices to the correct index in the 1D array.
  5. We finally print each element followed by a space to format the output as rows and columns, and then print a newline after each row using cout << endl.

Pointers And Array In C++

Pointers are important variables that point to the location/ memory address of an object. They are especially important when storing an object in any data structure. Hence, the relationship between pointers and arrays is noteworthy.

What is a pointer to an array in C++?

For instance, say the initial element in an array has a pointer that bears similar characteristics as the name of that array. We can then use pointers to gain access to specific items in an array or to keep track of their element addresses. We will explore the relationship between these, but first, lets take a look at the basic syntax for declaring a pointer to an array:

type (*ptr)[size];

Here, type is the data type of array elements, *ptr is the pointer to an array, and size is the number of elements in the array.

Some important points showing how pointers are related to the array are:

  • Array items can be accessed via pointers.
  • The addresses of the array's elements can be stored as pointers.
  • Pointers to arrays can be supplied as parameters to the functions.
  • The array's first element is the same as the pointer to the array's name.

Now let's take a look at an example that represents the relationship between pointers and arrays.

Code:

Output:

First element: 10
Second element: 20
Element 1: 10
Element 2: 20
Element 3: 35
Element 4: 40
Element 5: 50

Explanation:

  1. We declare an integer array numbers with 5 elements and initialize it with values 10, 20, 30, 40, and 50.

  2. Next, we declare a pointer to an integer ptrToArray and assign it the memory address of the first element of the numbers array. Since numbers is the name of the array, it also represents the address of its first element (i.e., numbers[0]).

  3. We can access the elements of the array using the pointer ptrToArray.

  4. In C++, to access the value at the memory address pointed to by a pointer, we use the dereference operator (*). So, *ptrToArray gives us the value of the first element (number[0]), and *ptrToArray + 1 gives us the value of the second element, i.e., number[1], and so on.

  5. We can also modify elements of the array using pointers. For example, we set the value of the third element number[2] to 35 using *ptrToArray + 2.

  6. Finally, we loop through the array using a for loop and a pointer. We also use the std::cout command inside the loop to print the values of all elements.

Other Ways To Declare An Array In C++

While the basic method of declaring an array, such as int arr[5];, is the most commonly used, there are situations where declaring large or dynamic arrays using this method can become cumbersome or impractical. In such cases, C++ offers alternative methods for array declaration and management, particularly through the use of the stack and heap memory. These methods provide more flexibility and control over memory allocation.

Implementation Of Stack Using Arrays In C++

How to implement a stack using array in C++?

In C++, the stack is an abstract data structure that follows the Last-In-First-Out (LIFO) principle. Arrays can be declared within functions as local variables, automatically allocating them on the stack. When a function is called, the stack frame is created, including space for any arrays. Upon returning from the function, the stack frame is deallocated, freeing the array's memory. This method is simple and efficient for small arrays but limited by the stack size, which is typically much smaller than heap memory.

Example: 

void function() {
int stackArray[5] = {1, 2, 3, 4, 5}; // Stack allocation
// Use the array...
} // Automatically deallocated when the function exits

In the above code snippet, an array stackArray is declared within a function, automatically allocated on the stack, and automatically deallocated when the function exits.

Implementation Of Heap Using Arrays In C++

Using array in C++ to implement heap

Heap memory in C++ allows dynamic memory allocation at runtime. It provides more flexibility, especially for larger arrays or when the size is not known at compile time. To allocate an array on the heap, we use the new operator, and to deallocate it, we use delete[]. This approach is crucial when dealing with large data sets, as the heap provides a much larger memory pool than the stack.

Additionally, implementing data structures like binary heaps using arrays involves storing elements in a way that maintains heap properties (e.g., min-heap or max-heap). A binary heap is a binary tree with the following properties:

  1. It is a complete binary tree, meaning all levels are filled except possibly the last level, which is filled from left to right.
  2. For a min-heap, the value of each node is smaller than or equal to the values of its children.
  3. For a max-heap, the value of each node is greater than or equal to the values of its children.

Example: 

int* heapArray = new int[5]; // Heap allocation
// Use the array...
delete[] heapArray; // Manual deallocation

In the above code snippet, an array heapArray is dynamically allocated on the heap using the new operator, and it must be manually deallocated using delete[] to free the memory when no longer needed.

Advantages & Disadvantages Of An Array In C++

Some of the most common advantages and disadvantages of using an array in C++ are:

Advantages Of Arrays In C++

  1. Efficient Access: Arrays provide constant-time access to elements using their index. This allows for quick retrieval and modification of elements, making array access highly efficient.

  2. Contiguous Memory Allocation: Array elements are stored in contiguous memory locations. This layout ensures efficient memory access, reducing cache misses and improving overall performance.

  3. Simple Syntax: The syntax for declaring and accessing elements in an array is straightforward. This simplicity makes arrays easy to understand and use, especially for beginners.

  4. Grouping of Related Data: Arrays allow you to group multiple elements of the same data type under a single variable name. This feature makes it convenient to work with collections of related data.

  5. Compile-Time Determined Size: The size of an array is determined at compile-time. This feature is useful when you know the exact number of elements needed and want to enforce that constraint.

  6. Interoperability: Arrays have a standard memory layout, making them easy to pass between functions and communicate with other parts of a program or external libraries.

Disadvantages Of Arrays In C++

  1. Fixed Size: Arrays have a fixed size specified at the time of declaration, and it cannot be changed during program execution. This limitation can be problematic if you need to handle a dynamic number of elements.

  2. No Built-in Bounds Checking: C++ does not provide automatic bounds checking for array access. If you access an element beyond the valid range, it can lead to undefined behavior, causing crashes or incorrect results.

  3. Inefficient Insertion and Deletion: Inserting or deleting elements in an array can be inefficient. To insert an element, you may need to shift existing elements to make space and to delete an element. You may need to shift elements to fill the gap.

  4. Wasted Memory: If you declare an array with a large size but only use a small portion of it, you may waste memory. This inefficiency becomes more pronounced as the array size increases.

  5. Lack of Flexibility: Due to the fixed size, arrays may not be suitable for scenarios where the number of elements is not known beforehand or needs to change dynamically during program execution.

  6. Copying Overhead: When passing arrays to functions or returning them from functions, the entire array is copied, which can be costly in terms of memory and performance, especially for large arrays.

Conclusion

An array in C++ programming is an essential data structure, offering a convenient way to store and manipulate collections of data. By understanding how to use, declare, initialize, and access array elements, you can effectively work with arrays in your programs. However, it's essential to handle arrays with care, ensuring proper bounds checking to prevent errors and crashes in your programs. With arrays, you have a powerful tool at your disposal for organizing and processing data efficiently in C++. As you become more proficient with C++, you'll find that arrays are the building blocks for more advanced data structures and algorithms, making them a fundamental concept to master on your journey as a C++ developer.

Also read- 51 C++ Interview Questions For Freshers & Experienced (With Answers)

Frequently Asked Questions

Q. How do you declare an array in C++?

To declare an array in C++, first, specify the data type that will be assigned to each of its elements, and then you can assign a name to the array and declare its size within square brackets.

The syntax for array declaration:

data_type array_name[array_size];

Q. Can we add two arrays in C++?

Yes, you can add two arrays in C++. When you add two arrays, the corresponding elements of both arrays are added together to create a new array containing the results.

To add two arrays, they must have the same size (the same number of elements). The addition is performed element-wise, meaning the first element of the first array is added to the first element of the second array, the second element is added to the second element, and so on.

Example of adding two C++ arrays:

Output:

7 9 11 13 15

Explanation:

  1. Two integer arrays, arr1, and arr2, are declared in this code and given starting values of 1 to 5 and from 5 to 10, respectively.
  2. We then initiate a for loop to add the elements of the two arrays, and the result is stored in a new integer array called sum.
  3. The sum of the two arrays is printed lastly using another for loop and the cout command.

Q. How do you initialize an array in C++?

When declaring and creating an array in C++, it can be initialized immediately using the constant expression given below:

data_type arr_name[array_size] = {value1,value2,...,valueN};

Here,

  • The data_type is the type of the elements present in the array.
  • The arr_name represents the name of the array.
  • And value1,value2…..,valueN are the random values that the array holds.

Q. How to sort arrays in C++?

If you're looking to sort a simple array in C++, there are a variety of techniques available. Among these methods, one can utilize the std::sort function found within the Standard Template Library (STL).

Code:

Output:

5

Explanation:

This code block initializes an integer-type array called arr with values of five elements, i.e., 5,3,1,4 and 2.

  • We then use the sizeof() operator to evaluate the number of bytes occupied by this declared array.
  • The array is sorted ascending using the std::sort method.
  • The sorted array is then printed using a for loop and the cout command.

Note- You can also use bubble sort or quick sort algorithm for sorting arrays in C++.

Q. How do you find the length of an array in C++?

In C++, you can find the length of an array using two different methods:

1. Using the sizeof operator:

The sizeof() operator in C++ returns the total size in bytes of the array, which includes all its elements. To find the number of elements in the array, you can divide the total size by the size of a single element.

Here's an example:

int numbers[] = {10, 20, 30, 40, 50};
int size = sizeof(numbers) / sizeof(numbers[0]);
// 'size' will be equal to 5 in this case

Note that this method only works for arrays with a known size at compile time. If you pass the array to a function, the sizeof operator will not give you the correct size within the function, as the array will decay into a pointer.

2. Using std::size (C++17 and later):

C++17 introduced the std::size function in the <iterator> header, which provides a more convenient and safer way to get the size of an array or container.

Here's how you can use it:

#include <iostream>
#include <iterator>
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int size = std::size(numbers);
// 'size' will be equal to 5 in this case
return 0;
}

This method works for both arrays with a known size at compile time, and arrays passed to functions, as it takes care of the array decay issue.

Q. What are the different types of arrays in C++?

Different types of arrays in C++ are:

1. One-Dimensional Arrays: The most basic type of array is a one-dimensional array, which stores elements in a single line or row. Elements in a one-dimensional array are accessed using a single index.

For example: int scores[5] = {85, 90, 78, 95, 88};

2. Multi-Dimensional Arrays: Multi-dimensional arrays are arrays of arrays that allow you to store elements in multiple dimensions, such as rows and columns. The most common type is a two-dimensional array, but you can have arrays with more dimensions as well.

For example:
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

3. Dynamic Arrays (Dynamically Allocated Arrays): In C++, you can allocate arrays dynamically at runtime using pointers and the new operator. Dynamic arrays are not fixed in size and can be resized during program execution. However, it's essential to manage the memory and deallocate it properly using the delete operator to avoid memory leaks.

Here's an example:

int size;
cin >> size;
int* dynamicArray = new int[size];
// Remember to delete the array when it's no longer needed
delete[] dynamicArray;

4. An Array of Pointers: In C++, you can create an array of pointers, where each element of the array holds the address of another variable. This concept of a pointer array in C++ is useful for creating arrays of strings or arrays of dynamically allocated objects.

For example:
int* ptrArray[5]; // C++ Array of 5 integer pointers

Now that you know all about array in C++, do check out the following to learn more:

  1. Storage Classes In C++ & Its Types Explained (With Examples)
  2. Pointer To Object In C++ | Simplified Explanation & Examples!
  3. C++ Type Conversion & Type Casting Demystified (With Examples)
  4. What is Function Prototype In C++ (Definition, Purpose, Examples)
  5. Logical Operators In C++ | Use, Precedence & More (With Examples)
Edited by
Shivani Goyal
Manager, Content

An economics graduate with a passion for storytelling, I thrive on crafting content that blends creativity with technical insight. At Unstop, I create in-depth, SEO-driven content that simplifies complex tech topics and covers a wide array of subjects, all designed to inform, engage, and inspire our readers. My goal is to empower others to truly #BeUnstoppable through content that resonates. When I’m not writing, you’ll find me immersed in art, food, or lost in a good book—constantly drawing inspiration from the world around me.

Tags:
Computer Science Engineering C++ Programming Language

Comments

Add comment
No comments Image No comments added Add comment
Powered By Unstop Logo
Best Viewed in Chrome, Opera, Mozilla, EDGE & Safari. Copyright © 2024 FLIVE Consulting Pvt Ltd - All rights reserved.