Creating an Array
You are encouraged to solve this task according to the task description, using any language you may know.
This task is about numeric arrays. For hashes or associative arrays, please see Creating an Associative Array.
In this task, the goal is to create an array. Mention if the array base begins at a number other than zero.
ActionScript
// ActionScript arrays are zero-based // // creates an empty array var arr1:Array = new Array(); // creates an array with 3 numerical values var arr2:Array = new Array(1,2,3); // // or just use the shorthand var u:Array = []; var v:Array = [1,2,3];
Ada
Compiler: GCC 4.1.2
Ada array indices may begin at any value, not just 0 or 1 <Ada>
type Arr is array (Integer range <>) of Integer; Uninitialized : Arr (1 .. 10); Initialized_1 : Arr (1 .. 20) := (others => 1); Initialized_2 : Arr := (1 .. 30 => 2); Const : constant Arr := (1 .. 10 => 1, 11 .. 20 => 2, 21 | 22 => 3); Centered : Arr (-50..50) := (0 => 1, Others => 0);
</ada> Ada arrays may be indexed by enumerated types, which are discrete non-numeric types <ada>
type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun); type Activities is (Work, Fish); type Daily_Activities is array(Days) of Activities; This_Week : Daily_Activities := (Mon..Fri => Work, Others => Fish);
</ada>
ALGOL 68
As with all ALGOL 68 declarations the programmer has the choice of using the full declaration syntax, or using syntactic sugar - c.f. "sugared" variables below.
Example of array of 10 integer types:
REF []INT numbers = HEAP [1:10] INT; HEAP [1:10]INT sugared hnumbers; # from global memory # LOC [1:10]INT sugared lnumbers1; # from the stack # [10]INT sugared lnumbers2; # from the stack - LOC scope is implied #
Note that the array can be taken from the heap, or stack.
Example of array of 3 string types:
[]STRING cwords = ( "these", "are", "arrays" ); # array is a constant and read-only (=) # [3]STRING vwords := ( "these", "are", "arrays" ); # array is a variable and modifiable (:=) #
You can also declare the size of the array and initialize the values at the same time:
REF []INT more numbers = LOC [3]INT := ( 21, 14 ,63 ); []INT sugared more cnumbers = ( 21, 14 ,63 ); [3]INT sugared more vnumbers := ( 21, 14 ,63 );
For Multi-Dimensional arrays you declare them the same except for a comma in the type declaration. The following creates a 3x2 int matrix
REF [][]INT number matrix = LOC [3][2] INT; [3,2]INT sugared number matrix1; # an matrix of integers # [3][2]INT sugared number matrix2; # an array of arrays of integers #
As with the previous examples you can also initialize the values of the array, the only difference being each row in the matrix must be enclosed in its own braces.
[][]STRING string matrix = ( ("I","swam"), ("in","the"), ("freezing","water") );
or
REF [][] STRING funny matrix = LOC [2][2]STRING := ( ("clowns", "are") , ("not", "funny") ); [2][2] STRING sugared funny matrix := ( ("clowns", "are") , ("not", "funny") );
Further, the arrays can start at any number:
[-10:10] INT balanced; # for example -10 #
If the array is expected to change size in future, then the programmer can also declare it FLEX.
FLEX [-10:10] INT flex balanced;
This next piece of code creates an array of references to integers. The value of each integer "pointed at" is the square of it's index in the array.
[-10:10] REF INT array of pointers to ints; FOR index FROM LWB array of pointers to ints TO UPB array of pointers to ints DO array of pointers to ints[index] := HEAP INT := i*i # allocate global memory # OD
AppleScript
AppleScript arrays are called lists:
set empty to {} set ints to {1, 2, 3}
Lists can contain any objects including other lists:
set any to {1, "foo", 2.57, missing value, ints}
Bold text
BASIC
REM Force index to start at 1..n OPTION BASE 1
REM Force index to start at 0..n OPTION BASE 0
REM Specify that the array is dynamic and not static '$DYNAMIC DIM SHARED myArray(-10 TO 10, 10 TO 30) AS STRING REDIM SHARED myArray(20, 20) AS STRING myArray(1,1) = "Item1" myArray(1,2) = "Item2"
C
Dynamic
#include <stdlib.h> /* for malloc */ #include <string.h> /* for memset */ int n = 10 * sizeof(int); int *myArray = (int*)malloc(n); if(myArray != NULL) { memset(myArray, 0, n); myArray[0] = 1; myArray[1] = 2; free(myArray); myArray = NULL; }
Static
int myArray2[10] = { 1, 2, 0}; /* 3..9 := 0 */
C++
Using dynamically-allocated (i.e. Heap) memory:
const int n = 10; int* myArray = new int[n]; if(myArray != NULL) { myArray[0] = 1; myArray[1] = 2; delete[] myArray; myArray = NULL; }
Using fixed (i.e. Stack) memory:
int myArray2[10] = { 1, 2, 0}; /* 3..9 := 0 */
// STL std::vector<int> myArray3(10); myArray3.push_back(1); myArray3.push_back(2);
// Qt QVector<int> myArray4(10); myArray4.push_back(1); myArray4.push_back(2);
// MFC CArray<int,int> myArray5(10); myArray5.Add(1); myArray5.Add(2);
C#
Example of array of 10 int types:
int[] numbers = new int[10];
Example of array of 3 string types:
string[] words = { "these", "are", "arrays" };
You can also declare the size of the array and initialize the values at the same time:
int[] more_numbers = new int[3]{ 21, 14 ,63 };
For Multi-Dimensional arrays you declare them the same except for a comma in the type declaration.
The following creates a 3x2 int matrix
int[,] number_matrix = new int[3,2];
As with the previous examples you can also initialize the values of the array, the only difference being each row in the matrix must be enclosed in its own braces.
string[,] string_matrix = { {"I","swam"}, {"in","the"}, {"freezing","water"} };
or
string[,] funny_matrix = new string[2,2]{ {"clowns", "are"} , {"not", "funny"} };
Clean
Array denotations are overloaded in Clean, therefore we explicitly specify the types. There are lazy, strict, and unboxed array.
Lazy array
Create a lazy array of strings using an array denotation.
array :: {String} array = {"Hello", "World"}
Create a lazy array of floating point values by sharing a single element.
array :: {Real} array = createArray 10 3.1415
Create a lazy array of integers using an array (and also a list) comprehension.
array :: {Int} array = {x \\ x <- [1 .. 10]}
Strict array
Create a strict array of integers.
array :: {!Int} array = {x \\ x <- [1 .. 10]}
Unboxed array
Create an unboxed array of characters, also known as String.
array :: {#Char} array = {x \\ x <- ['a' .. 'z']}
ColdFusion
Creates a one-dimensional Array
<cfset arr1 = ArrayNew(1)>
Creates a two-dimensional Array in CFScript
<cfscript> arr2 = ArrayNew(2); </cfscript>
ColdFusion Arrays are NOT zero-based, they begin at index 1
Common Lisp
Creates a one-dimensional array of length 10. The initial contents are undefined.
(make-array 10)
Creates a two-dimensional array with dimensions 10x20.
(make-array '(10 20))
make-array may be called with a number of optional arguments.
(make-array 4 :element-type 'integer :initial-contents '(1 2 3 4) :adjustable t)
D
// dynamic array int[] numbers = new int[5]; // static array int[5] = [0,1,2,3,4];
E
[] # immutable, empty [1,9,17] # immutable, 3 elements [].diverge() # mutable, empty [].diverge(int) # mutable, integers only
Forth
Forth has a variety of ways to allocate arrays of data, though it has no built-in array handling words, favoring pointer manipulation.
Static array of 200 cells, uninitialized:
create MyArray 200 cells allot here MyArray - cell / constant MyArraySize
Static array containing the numbers 1 to 5
create MyArray 1 , 2 , 3 , 4 , 5 , here MyArray - cell / constant MyArraySize
Dynamic array allocation:
0 value MyArray 200 cells allocate throw to MyArray
Dynamic array free:
MyArray free throw 0 to MyArray
Fortran
In ANSI FORTRAN 77 or later, this is a default-indexing array declaration:
integer a(10)
This array will have ten elements. Counting starts at 1.
If a zero-based array is needed, declare like this:
integer a(0:9)
This mechanism can be extended to any numerical indices, and any of the up-to-seven-allowed number of dimensions (and of course to other data types than integers). For example:
real a(25:29,12)
will be an two-dimensional, 5x12-array of type REAL, where the first dimension can be addressed numerically as 25, 26, 27, 28 or 29 (and the second dimension as 1 .. 12).
In ISO Fortran 95 or later, arrays can also be initialized using a robust set of array constructors and array intrinsic functions.
program arrays real :: a(100) = 0 ! entire array initialized to ZERO real :: b(9) = (/ 1,2,3,4,5,6,7,8,9 /) ! array constructor real :: c(10) = (/ (2**i, i=1, 10) /) ! array constructor with "implied do loop" ! An array constructor is a literal definition of a ONE-DIMENSIONAL array only. ! In order to initialize multidimensional arrays, you need to use the RESHAPE instrinsic ! function: real :: d(2, 5) = reshape( (/ (2**i,i=1,10) /), (/ 2, 5 /) ) ! ^^^^^^^^^^^^^^^^^^^source array ^^^^^^^^^^ dimension shape ! Fills the array in COLUMN MAJOR order. That is, traverse the first dimension first, ! second dimension second, etc. ! In order to fill a matrix in ROW MAJOR order, merely specify as before, ! but TRANSPOSE the result real :: e(4, 4) = transpose( reshape( & (/ 1, 2, 3, 4, & 5, 6, 7, 8, & 9, 10, 11, 12, & 13, 14, 15, 16 /), (/ 4, 4 /) ) ) print *, b print * print *, c print * print '(5F7.0)', d(1,:) ! print row 1 print '(5F7.0)', d(2,:) ! print row 2 print * do i = 1, 4 print '(4F7.0)', e(i,:) ! print row I end do end program arrays
Output:
1. 2. 3. 4. 5. 6. 7. 8. 9. 2. 4. 8. 16. 32. 64. 128. 256. 512. 1024. 2. 8. 32. 128. 512. 4. 16. 64. 256. 1024. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16.
Here is a more interesting example showing a function that creates and returns a square identity matrix of order N:
module matrixUtil contains function identity(n) integer, intent(in) :: n integer :: i, j real, pointer :: identity(:,:) allocate(identity(n,n)) ! the MERGE intrinsic is like a C ternary (if-then-else) operator, except that the logical condition ! comes at the end, it is a logical ARRAY, and the function result is an array of the same size and shape identity = merge (1.0, 0.0, reshape( (/ ( (i==j, i=1,n), j=1,n) /), (/ n, n /) ) ) ! ^^^ if-TRUE-value ^^^ if-FALSE-value ^^<-NxN logical array, true only on the diagonal->^^ ! The TVALUE and FVALUE must be "conformable" to the logical array, meaning that each is either: ! -- an array of the same size and shape as the logical array ! -- a scalar end function identity end module matrixUtil
program muTest use matrixUtil integer :: n real, pointer :: i(:,:) read (*,*) n i => identity(n) do j=1, size(i,1) print *, i(j,:) end do deallocate(i) end program muTest
Example run:
$ g95 -o mu matrixUtil.f95 muTest.f95 $ ./mu 15 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. $
Haskell
Arrays are initialized either by a list of index-value-pairs or by a list of values:
import Data.Array a = array (1,3) [(1,42),(2,87),(3,95)] a' = listArray (1,3) [42,87,95]
Lower and upper bounds (here 1 and 3) are arbitrary values of any type that is an instance of Ix. If not all initial values are given, the corresponding index is left undefined.
There are several flavours of arrays in Haskell, but creation looks very similar for the others.
IDL
IDL doesn't really distinguish between scalars and arrays - the same operations that can create the one can usually create the other as well.
a = 3 help,a A INT = 3 print,a^2 9
a = [3,5,8,7] help,a A INT = Array[4] print,a^2 9 25 64 49
J
"Creating an array" is topic seldom discussed in J as every verb takes array argument(s) and returns an array result (that is, everything creates an array). For example:
a=: 3 4 $ 3 1 4 1 5 9 2 6 5 3 5 8 NB. make a 3-by-4 table a NB. display a 3 1 4 1 5 9 2 6 5 3 5 8 b=: 10 20 30 NB. make a 3-element list a + b NB. add corresponding items of a and b 13 11 14 11 25 29 22 26 35 33 35 38 ] c=: 3 4 $ 'eleemosynary' NB. make a 3-by-4 character table and display it elee mosy nary |."1 c NB. reverse each item of c eele ysom yran
Both the a+band the |."1 c expressions create arrays.
Java
For example for an array of 10 int values:
int[] intArray = new int[10];
Creating an array of Strings:
String[] s = {"hello" , "World" };
JavaScript
var myArray = new Array(); var myArray1 = new Array(5); // gotcha: preallocated array with five empty elements, not [ 5 ]. var myArray2 = new Array("Item1","Item2"); var myArray3 = ["Item1", "Item2"];
Logo
array 5 ; default origin is 1 (array 5 0) ; custom origin
LSE64
10 myArray :array
MAXScript
myArray = #() myArray2 = #("Item1", "Item2")
mIRC Scripting Language
alias creatmearray { .echo -a $array_create(MyArray, 5, 10) }
Nial
To create an array of 5 elements with values from 1 to 5
| count 5 1 2 3 4 5
Assign it to a variable
| myarr := count 5
Use an array literal instead
| newarr := [2 4 6]
Oberon-2
Create an array of 10 integers. Initial values are undefined.
VAR a: ARRAY 10 OF INTEGER;
Oberon-2 has no array constructor syntax.
FOR i := 0 TO LEN(a) - 1 DO a[i] := i + 1; END;
OCaml
Using an array literal:
let array = [| 1; 2; 3; 4; 5 |];;
To create an array of five elements with the value 0:
let num_items = 5 and initial_value = 0;; let array = Array.make num_items initial_value
To create an array with contents defined by passing each index to a callback (in this example, the array is set to the squares of the numbers 0 through 4):
let callback index = index * index;; let array = Array.init 5 callback
Perl
my @empty; my @empty_too = ();
my @populated = ('This', 'That', 'And', 'The', 'Other'); print $populated[2]; # And my $aref = ['This', 'That', 'And', 'The', 'Other']; print $aref->[2]; # And
# having to quote like that really sucks, and that's why we got syntactic sugar my @wakey_wakey = qw(coffee sugar cream); push @wakey_wakey, 'spoon'; # add spoon to right-hand side my $cutlery = pop @wakey_wakey; # remove spoon unshift @wakey_wakey, 'cup'; # add cup to left-hand side my $container = shift @wakey_wakey; # remove cup
my @multi_dimensional = ( [0, 1, 2, 3], [qw(a b c d e f g)], [qw(! $ %
PHP
<?php $array = array(); /* Blank Array */ $array[] = "Moo"; /* Sticks Moo in the next index */ $array2 = array(1 => "A", 2=> "B", 3=>"C", 4=>"Moo"); /* Creates an Array with Values */ print_r($array); /* Array(0=>"Moo") */ print_r($array2); /* Array( 1 => A 2 => B 3 => C 4 => Moo */ print($array2[5]); // Undefined Index ?>
Pop11
Pop11 distinguishes between vectors and arrays. Vectors are one dimensional and the lowest index is 1. There is special shorthand syntax to create vectors:
;;; General creation of vectors, create initialized vector. lvars v1 = consvector(1, 'a', "b", 3); ;;; Shorthand notation lvars v2 = {1 'a' b}; ;;; Create vector filled with word undef (to signal that elements ;;; are uninitialized) lvars v3 = initv(3)
Pop11 arrays may have arbitrary lower and upper bounds:
;;; Create array with first index ranging from 2 to 5 and second ;;; index from -1 to 1, initialized with 0 vars a1 = newarray([2 5 -1 1], 0);
Python
List are mutable arrays. You can put anything into a list, including other lists.
empty = [] numbers = [1, 2, 3, 4, 5] zeros = [0] * 10 anything = [1, 'foo', 2.57, None, zeros] digits = range(10) # 0, 1 ... 9 evens = range(0,10,2) # 0, 2, 4 ... 8 evens = [x for x in range(10) if not x % 2] # same using list comprehension words = 'perl style'.split()
Tuples are immutable arrays. Note hat tuples are defined by the "," - the parenthesis are optional:
empty = () numbers = (1, 2, 3, 4, 5) zeros = (0,) * 10 anything = (1, 'foo', 2.57, None, zeros)
Both lists and tuples can be created from other iterateables:
>>> list('abc') ['a', 'b', 'c'] >>> tuple('abc') ('a', 'b', 'c') >>> list({'a': 1, 'b': 2, 'c': 3}) ['a', 'c', 'b'] >>> open('file', 'w').write('1\n2\n3\n') >>> list(open('file')) ['1\n', '2\n', '3\n']
Raven
[ 1 2 3.14 'a' 'b' 'c' ] as a_list a_list print
list (6 items) 0 => 1 1 => 2 2 => 3.14 3 => "a" 4 => "b" 5 => "c"
Ruby
I've used the same examples as the Python-example above. .
empty = [] #or: empty = Array.new numbers = [1, 2, 3, 4, 5] zeros = [0] * 10 anything = [1, 'foo', 2.57, zeros]
Scheme
Lists are more often used in Scheme than vectors.
Using an array literal:
#(1 2 3 4 5)
To create an array of five elements:
(make-vector 5)
To create an array of five elements with the value 0:
(make-vector 5 0)
Toka
Toka allows creation of an array using is-array. Access to the elements is done using get-element, put-element, get-char-element, and put-char-element functions. You can not initialize the values automatically using the core array functions.
100 cells is-array foo 100 chars is-array bar
Visual Basic .NET
Implicit Size
' An empty array of integers. Dim empty() AS Integer = {} ' An array of integers. Dim numbers() AS Integer = {1, 2, 3, 4, 5} ' An array of strings Dim string() AS String = {"String","foo","etc."}
Explicit Size
' An empty array of integers. Dim empty(0) AS Integer = {} ' An array of integers. Dim numbers(4) AS Integer = {1, 2, 3, 4, 5} ' An array of strings Dim String(2) AS String = {"String","foo","etc."}
Resize An Array
' An empty array of integers. Dim empty() As Integer = {} Private Sub ReDimension() ' Resize (And keep all elements intact) ReDim Preserve empty(1) ' Resize (Erase all elements) ReDim empty(1) End Sub
Splitting strings into arrays
Dim words() AS String = 'perl style'.split(" "c) ' You must tell VB that the space is a character by denoting c after the " "