From the course: Computer Science Principles: Programming

Changing arrays

From the course: Computer Science Principles: Programming

Start my 1-month free trial

Changing arrays

- Once you've created an array, you'll probably want to change it later on. Changing a simple variable means you adjust of change the value inside the variable but with a container, it is more complex since you have more than one value. If we go back the our egg cart an example, we know that each of the items in the collection has an element index number and each slot can contain a value. A collection using these can be modified in three primary ways. The simplest is the access of specific item, and using its element index number, change the value that is stored within it. You need to know the index number that you want to change. Next, is if you want to add items to an array. When you create an array, you can first define it using a number of values but when you want to add more values after it, the number of values might vary. One array might have three items, while another has nine. So, adding item to the end isn't as straightforward. With an array, you can add an item to the end by pushing an item to the end of the array. This works no matter how many values are stored in the array allowing an array to push a value will always add it to the end giving it a unique index number that is after the last value. The last way you can adjust an array is to shorten it. For instance, you might want the first three items or three in the middle or three at the end. The way you do this is to section off or slice away the section that you want to keep. You first want to identify the first item you want to keep and then count off the number of items you want. Using these two numbers, you can select a sequence of values from the array. These are three basic methods to work with and modify values within an array collection.

Contents