Back to C++
2026-01-078 min read

How to insert and print array elements? (C++)

Learn How to insert and print array elements? (C++) step by step with clear examples and exercises.

Title: Mastering Array Manipulation in C++: Insert and Print Elements

Why This Matters

You'll learn how to insert and print array elements in C++. This skill is crucial for solving complex programming problems that require manipulating data structures efficiently. Understanding arrays and their operations can help you excel in coding interviews and real-world projects.

Arrays are a fundamental data structure in C++, allowing us to store multiple values of the same type in a single variable. Manipulating array elements, such as inserting and printing, is an essential skill for any C++ programmer.

Prerequisites

Before diving into the core concept, make sure you have a good understanding of:

  • Basic C++ syntax
  • Variables and data types
  • Control structures (if...else, for loop)
  • Standard Template Library (STL) concepts like iterators and containers (optional but recommended)
  • Understanding pointers and dynamic memory allocation (optional but recommended)

Core Concept

Arrays in C++

An array is a collection of elements of the same data type stored at contiguous memory locations. To declare an array, you need to specify its data type and size. Here's an example of declaring an integer array:

int arr[5]; // Declare an array with 5 integers

You can access individual elements using their index (starting from 0). For example, to assign a value to the first element, you would use:

arr[0] = 10; // Assign 10 to the first array element

Inserting Elements in an Array

In C++, arrays have a fixed size, so you cannot dynamically add elements during runtime. However, there are workarounds to achieve this using techniques like resizing the array or using dynamic data structures like vectors. For simplicity, we will focus on inserting elements at specific positions within the array.

To insert an element into an existing array, you can shift the elements from the target position and its subsequent indices towards the end of the array. Here's a step-by-step example:

void insertAt(int arr[], int n, int index, int x) {
if (index >= 0 && index <= n) {
for (int i = n; i > index; i--) {
arr[i] = arr[i - 1];
}
arr[index] = x;
n++; // Update array size
}
}

In this function, arr[] is the input array, n is its current size, index is the position where we want to insert the new element, and x is the value of the new element. The function first checks if the specified index is valid (i.e., within the array bounds). If so, it shifts the elements from the target position towards the end and inserts the new element at the desired location.

Printing Array Elements

To print all elements of an array, you can use a simple for loop:

void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
}

In this function, arr[] is the input array and n is its current size. The function iterates through each element and prints it to the console.

Multi-dimensional Arrays

C++ also supports multi-dimensional arrays, which can be thought of as arrays of arrays. To print all elements of a multi-dimensional array, you can use nested for loops to iterate through each dimension. Here's an example:

void print2DArray(int arr[][3], int rows) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl; // Print a newline after each row
}
}

In this function, arr[][] is the input 2D array, and rows is the number of rows in the array. The function uses nested for loops to iterate through each element and print it to the console.

Dynamic Memory Allocation

To dynamically allocate memory for an array in C++, you can use the new[] operator:

int* arr = new int[5]; // Dynamically allocate an array with 5 integers
arr[0] = 10; // Assign a value to the first element

When you're done using the array, don't forget to deallocate the memory using delete[]:

delete[] arr; // Deallocate the dynamically allocated array

Resizing Arrays

To resize an array in C++, you can create a new array with the desired size and copy the elements from the old array to the new one. Here's an example:

void resizeArray(int arr[], int& n, int newSize) {
int* newArr = new int[newSize]; // Allocate a new array with the desired size
for (int i = 0; i < n && i < newSize; i++) {
newArr[i] = arr[i]; // Copy elements from old array to new array
}
delete[] arr; // Deallocate the old array
arr = newArr; // Assign the new array to the original pointer
n = newSize; // Update the array size
}

In this function, arr[] is the input array, and n is a reference to its current size. The function creates a new array with the specified size, copies the elements from the old array to the new one, deallocates the old array, assigns the new array to the original pointer, and updates the array size.

Worked Example

Let's create an example program that demonstrates inserting and printing elements in a 1D and a 2D array, as well as dynamically allocating memory for an array:

#include <iostream>
using namespace std;

void insertAt(int arr[], int& n, int index, int x) {
if (index >= 0 && index <= n) {
for (int i = n; i > index; i--) {
arr[i] = arr[i - 1];
}
arr[index] = x;
n++;
}
}

void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
}

void print2DArray(int arr[][3], int rows) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < 3; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}

void resizeArray(int arr[], int& n, int newSize) {
int* newArr = new int[newSize]; // Allocate a new array with the desired size
for (int i = 0; i < n && i < newSize; i++) {
newArr[i] = arr[i]; // Copy elements from old array to new array
}
delete[] arr; // Deallocate the old array
arr = newArr; // Assign the new array to the original pointer
n = newSize; // Update the array size
}

int main() {
int arr1[5] = {1, 2, 3, 4, 5};
printArray(arr1, 5); // Output: 1 2 3 4 5

insertAt(arr1, 5, 2, 7);
printArray(arr1, 6); // Output: 1 2 7 3 4 5

int arr2[2][3] = {{1, 2, 3}, {4, 5, 6}};
print2DArray(arr2, 2); // Output: 1 2 3
// 4 5 6

int* arr3 = new int[7]; // Dynamically allocate an array with 7 integers
for (int i = 0; i < 7; i++) {
arr3[i] = i * 2 + 1; // Assign values to the dynamically allocated array
}
printArray(arr3, 7); // Output: 1 3 5 7 9 11 13

resizeArray(arr3, n, 8); // Resize the dynamically allocated array to 8 elements
arr3[7] = 15; // Assign a value to the newly added element
printArray(arr3, 8); // Output: 1 3 5 7 9 11 13 15

delete[] arr3; // Deallocate the dynamically allocated array

return 0;
}

Common Mistakes

  1. Index out of bounds: Ensure that the specified index is within the array's size range (i.e., between 0 and n - 1, where n is the array size).
  2. Forgetting to update the array size: Don't forget to increment the array size when inserting a new element, as shown in the insertAt() function example.
  3. Incorrect use of the for loop: Make sure you initialize the loop counter correctly and check if it is less than the array size before accessing elements.
  4. Missing semicolons: Always remember to end your statements with a semicolon in C++.
  5. Not defining functions properly: Ensure that you define functions (like insertAt() and printArray()) outside of any other function or the main function, as shown in the worked example.
  6. Memory leaks: Don't forget to deallocate dynamically allocated memory using delete[].
  7. Not handling array resizing: Make sure you handle cases where the new size is smaller than the current size when resizing an array.

Subheadings under Common Mistakes:

  • Index out of bounds errors
  • Forgetting to update array size
  • Incorrect use of for loops
  • Missing semicolons
  • Not defining functions properly
  • Memory leaks
  • Not handling array resizing

Practice Questions

  1. Write a function to delete an element at a specific index in an array.
  2. Modify the insertAt() function to handle duplicate elements by either overwriting existing values or shifting the subsequent elements towards the end of the array.
  3. Implement a function that reverses the order of elements in an array.
  4. Write a function to find the second largest element in an array.
  5. Create a program that reads integers from the user and dynamically allocates memory for the array using new[].
  6. Modify the resizeArray() function to handle cases where the new size is smaller than the current size.
  7. Write a function that concatenates two arrays of the same data type by creating a new array with the combined elements.
  8. Implement a function that sorts an array using bubble sort algorithm.
  9. Create a program that reads a multi-dimensional array from the user and prints its transpose (i.e., rows become columns, and columns become rows).
  10. Write a function that finds the sum of all even numbers in an array.

FAQ

  1. Why can't I add elements dynamically to an array in C++?
  • In C++, arrays have a fixed size at runtime. However, you can use dynamic data structures like vectors or resize the array using techniques like reallocation (not covered in this tutorial).
  1. What is the best way to handle duplicate elements when inserting into an array?
  • You can either overwrite existing values at the target position or shift subsequent elements towards the end of the array, as shown in the Common Mistakes section.
  1. How do I print all elements of a multi-dimensional array in C++?
  1. What is the difference between dynamic memory allocation using new[] and malloc()?
  • new[] is a C++ operator that automatically manages memory, including handling exceptions when memory allocation fails. malloc() is a C function from the standard library that only allocates memory without managing it. In C++, it's recommended to use new[] instead of malloc().
  1. How do I find the maximum element in an array?
  • You can implement this using a simple for loop and a variable to keep track of
How to insert and print array elements? (C++) | C++ | XQA Learn