How to append something to an Array – With Codes In C++/Python/Java

What is an Array?

An array is a data structure that stores a collection of elements of the same data type. The elements in an array are stored in a contiguous block of memory, and each element is accessed using an index, which is a numerical value that corresponds to the position of the element in the array.

How to Append

Here is how you can append an element to an array in C++, Python, and Java:

In C++

In C++, you can use the push_back function of the std::vector class to append an element to an array:

#include <vector>

int main() {
  std::vector<int> arr;
  arr.push_back(1);  // Append 1 to the end of the array
  arr.push_back(2);  // Append 2 to the end of the array
  return 0;
}

You can also use the insert function to insert an element at a specific position in the array:

#include <vector>

int main() {
  std::vector<int> arr {1, 2, 3};
  arr.insert(arr.begin() + 1, 4);  // Insert 4 at index 1
  return 0;
}

In Python

In Python, you can use the append function of a list to append an element to the end of the list:

arr = [1, 2, 3]
arr.append(4)  # Append 4 to the end of the list

You can also use the insert function to insert an element at a specific position in the list:

arr = [1, 2, 3]
arr.insert(1, 4)  # Insert 4 at index 1

In Java

In Java, you can use the add function of the ArrayList class to append an element to the end of the list:

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> arr = new ArrayList<>();
    arr.add(1);  // Append 1 to the end of the list
    arr.add(2);  // Append 2 to the end of the list
  }
}

You can also use the add function with an index argument to insert an element at a specific position in the list:

import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<Integer> arr = new ArrayList<>();
    arr.add(1);
    arr.add(2);
    arr.add(1, 3);  // Insert 3 at index 1
  }
}

Leave a Comment