Think of an array like a line-up of connected bins, each with its own home address (called an index). The individual values (or boxes) are called elements. Let's say you need to store ten random integers for a guessing game. You would not want to declare ten individual integer variables. Instead, you could declare one array variable of size 10 to hold the numbers.
You can store or retrieve each number by calling its address (index), typically using square brackets [ ]. Javascript shown here, other syntaxes shown in Example 1:
x[0] =7; // Store 7 in the first "bin"let valueOfBin3 = x[2]; // Retrieve the value in the third "bin"
Note: A string is actually an array of char variables.
Declaring (Creating) an Array
Since Javascript does not have types like C++, we just make an array of variables. Javascript also has some great built-in methods that allow us to concatenate, join, search, and sort arrays (among other things). Note - in Javascript there is no need to declare empty arrays with an initial size.
// Let's declare an array, there are two ways to do itlet someArray =newArray(); // Bad way :(let otherArray = []; // Good way! :)/* While both methods above work, it is considered proper form to use the second method. */// Let's declare and put some values into arrayslet someIntegers = [40,100,1,5,25,10];let someLetters = ['a','c',"q",`k`];let someBooleans = [true,false,false,false,true,false];let someStrings = ["Hello","Goodbye","Some words","Other words"];// Javascript is such a loosely-typed language that// your array can be mixed (not recommended)let notRecommended = [6,-3,true,"Something in text",false,'X'];// You can create arrays on-the-fly as wellconsole.log( [6,5,4,9,8,7] );// Output will be: [6, 5, 4, 9, 8, 7]
C++ is a strongly typed language. This means you must declare the type of variable in order to allocate the appropriate amount of memory. Furthermore, you also need to declare the number of elements (length) of the array at the time of declaration. Arrays in C++ can become confusing when you start to think about memory space and pointers. Let's keep it simple and look at declaring some arrays:
// Declare an empty array of integers, size 20intarrayOfInts[20];// Declare an empty array of single characters, size 10chararrayOfChars[10];// Another way to declare and intialize (this creates an array of size 4double arrayOfDoubles[] = {13.2,10.0,2.16,32.75};// Print a single value:std::cout <<arrayOfDoubles[ 3 ] << std::endl; // Will output 32.75
Java works in a similar fashion to C++ but the syntax is different.
C++: type name[size];
Java: type[] name = new type[optional size];
// Declare an empty integer arrayint[] intArray =newint[20]; // Here's one way to put values into the intArrayfor (int i =0; i <intArray.length; i++) { intArray[i] = i * (i +1); // some math... }// Here's another way to declare an array, initializing as we godouble[] dblArray =newdouble[]{ 1.1,2.0,3.6,10.5 };
Note: The C++ syntax will work in Java but it was only implemented as a way to help C++ developers. It is not the preferred method. The examples above are the preferred methods.
Python has a more versatile 'array' type called a sequence. The most basic sequence is a list. Lists in Python act very similar to arrays in Javascript. They can be modified, contain any type of variable or object, and they have many built-in methods for utilization.
# Let's create two listslistOne = ['Iron Man','Thor',1980,2018];listTwo = [1,'second',3,4,"fifth",6,7];# As you can see, Python is loosely typed (like Javascript) and allows for # any mixture of element type in the sequence
Aside from Lists, Python also has Tuples and Dictionaries. Read more about all of Python's types.
Iterating Through Elements
Iterating is the process of going through each (or every nth) element in an array.
You can retrieve the information of a single element by calling the index:
x[5]; // Retrieve the element at index 5 (the 6th element)
In this same manner, you can loop through, or iterate through all the elements in an array.
This example prints the elements of an array. We could
// Let's put some values into an arraylet someIntegers = [40,100,1,5,25,10];// Let's print out our array (Javascript has about 5 ways to do that)for (let i =0; i <someIntegers.length; i++) {console.log(someIntegers[i]);}// Using the for...of methodfor (let value of someIntegers) {console.log(value);}
Notice the use of someIntegers.length on line 5, above. In many languages you can retrieve the number of elements in this or similar ways. It is crucial to understand, however, that the value representing length is 1 higher than the last index in the array. For example, the following array has 8 elements but the last index is 7 because indexes start at zero.
let someValues = [45,24,3,54,245,45,-6,15];// Length is 8let arrayLength =someValues.length;// There is no element at that locationconsole.log( someValues[arrayLength] );// Output will most likely say "undefined" but could throw an exception as well
As with Javascript and other languages, you can use a for loop or other type of loop to go through the elements of an array. The one large difference is the lack of a .length property. You must either know the length of the array or use the size of memory space to find the length... yuck!
double arrayOfDoubles[] = {13.2,10.0,2.16,32.75};// Print the elementsfor (int x =0; x <4; x++) { std::cout <<arrayOfDoubles[ x ] << std::endl;}// For discussion purposes, this would get you the length of the array// But it won't work on all arrays (in fact, it doesn't work on very many)int arrayLength =sizeof(arrayOfDoubles)/sizeof(*arrayOfDoubles);
Java works similarly to C++ but it has a .length property for arrays because it treats arrays as objects. In that way, it is also like Javascript...
// Declare an arraydouble[] dblArray =newdouble[]{ 1.1,2.0,3.6,10.5 }; // Print the elements of the arrayfor (int i =0; i <dblArray.length; i++) {System.out.println("Element at index "+ i +" : "+ dblArray[i]);} // Could also print the value of a single elementSystem.out.println(dblArray[3]);// That would print the value of the 4th array element: 10.5
Python's lists (or sequences as I'm known to call them) can be referenced, retrieved, and modified in many interesting ways. If you are interested in Python, I highly recommend you read this website instead of mine!
# Let's create two listslistOne = ['Iron Man','Thor',1980,2018];listTwo = [1,'second',3,4,"fifth",6,7];# Print the second item of listOne: Thorprint listOne[1]# Print items 2 through 6 (inclusive) of listTwo: ['second', 3, 4, 'fifth']print listTwo[1:5]# Print all the items in listTwo# Method 1, use the len(listTwo) to get the lengthfor x inrange(0, len(listTwo)):print listTwo[x]# Method 2, use the iterative methodfor item in listTwo:print item# Python has tons of awesome ways to interact with lists, you might# be better off researching them on other sites
Modifying Arrays
Adding and removing elements from an array is memory-intensive. It is quite a process at the lowest-level, involving new memory space if growing your array and copying elements over. It can really slow down the program if doing this many thousands of times for large amounts of data.
Adding Elements
In Javascript, adding an element to the end of an array is very simple - you use the push() function.
someArray.push(5) // Add integer 5 onto the end of the array
someArray.push(7, 3, -9) // You can push multiple items in one command
The push() function returns a number representing the new length of the array.
If you want to insert a new element inside an existing array (or at the front), you need to utilize the splice() function. It is defined as myArray.splice(insertAt, 0, itemToInsert);
The splice function takes the parameters of where to insert the new item, how many items to delete (in this case, zero), and the item to insert. You can insert many items in one command.
Removing Elements
Removing the last element from the end of an array is done using the pop() function.
someArray.pop() // Remove the last element
The pop() function returns the element it is removing.
Deleting elements within an array also uses the splice() function, similar to adding elements. The parameters you would use are the location and number of elements to remove:
someArray.splice(5, 4) // Starting at index 5 remove 4 elements
Again, it will return a value representing the new length of the array.
How much time do you have? Sit down and grab a coffee. Then research adding and deleting elements from an array in C++. It is not a simple answer or task. There is something called a vector that is much more suited to this task.
Since an array in C++ is a pointer to a location in memory, where the memory has been statically allocated, you cannot simply ask for more memory - the memory next to your array might be in use.
The short answer is that you must declare a new array of proper length and copy the old array elements into this new array, plus whatever new elements you want to add.
It would be worthwhile researching linked lists to see another way of creating arrays that allow for dynamic manipulation.
Java has a primitive array type as well as some special types like ArrayList, Collections, and other similar objects. It is very typical for a Java developer to use ArrayList over a primitive array.
There are libraries you can add which have some utilities:import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;
To add elements to an array without those utilities requires a similar technique to C++ or other strongly typed languages. You will need to make a new array of a larger length and copy all the elements to the new array, deleting the old array to save memory. This is computationally intensive.
To remove elements, you will need to shift the contents to fill the gap, leaving null or 0 at the end. The better method would be similar to adding where you create a new, shorter array and copy the contents over. This becomes computationally intensive, however.
Highly recommended you read the page on TutorialsPoint. Essentially, Python has the following methods (functions) for lists:
append() - add element to the end of the list
insert() - insert an element at a given index
pop() - remove and return the last item from the list (or a particular object in the list)
remove() - delete a given object from the list
A list is very different from a primitive array. It is worth doing proper research on specific Python tutorial websites. Don't get me wrong, I like Python, I'm just not going to curate the information on this site.
Modifying the values in-place within an array for a strongly-typed language is much less memory intensive since each index simply points to a location in memory. Loosely-typed languages, like Javascript and Python, require much more memory-intensive work to modify an element, especially if changing the type (for example, swapping an integer for a large string of text).
Javascript:
let someIntegers = [ 5,3,1,9,7,5 ];// Let's print it:console.log(someIntegers);// Change the value at index 4someIntegers[4] =456;// Print it againconsole.log(someIntegers);// OUTPUT:// [ 5, 3, 1, 9, 7, 5 ]// [ 5, 3, 1, 9, 456, 5 ]
Strings are Arrays
In programming, a string is actually an array of chars. Well, in reality a string is an object but I won't get into that here.
The string "Hello" is actually a char array of size 5 where char[0] = 'H', char[1] = 'e', char[2] = 'l', etc.
Most languages allow you to manipulate a string using the indexes of the characters. Also, when you append to a string or concatenate multiple strings together the computer must allocate a new chunk of memory that is the specific size of the new char array and individually assign each index the appropriate letter.
Multi-Dimensional Arrays
Simple arrays, as discussed in these sections, are called one dimensional arrays. They are linear in the sense that there is a beginning & end, and the indexes in-between have an element on either side, like links in a chain.
Arrays can be two dimensional as well (or even more). A 2D array has two indexes, [x, y], such that each element in the first index is, itself, an array.
You can also chain arrays into a 3D array. The idea there is that each element points to a 2D array of arrays. You can create all sorts of amazing combinations in this fashion.