Adding/Removing from an Array
Adding and Removing from an Array Arrays on the CodeHS platform are mutable, meaning we can add and remove elements with ease. The key functions you will need to know are push()
, pop()
, and remove()
.
Adding Elements Thepush()
function adds an element to the end of an array. Suppose we have an array fruit
.
Output:
Inserting an element at any position other than the last will require looping through the array, which you will learn in the coming sections.
Removing Elements The function remove(int i)
removes the element at index i. Additionally, this function updates the positions of all elements with indices greater than i.
Output:
Another function you can use to remove elements is pop()
. This removes the last element in the array.
Output:
Last updated
Was this helpful?