Creating an Array: Difference between revisions

From Rosetta Code
Content added Content deleted
m (→‎{{header|Tcl}}: formatting)
(Blanked page since people can't / don't read)
 
(69 intermediate revisions by 22 users not shown)
Line 1: Line 1:
{{DeprecatedTask}}
{{task|Basic language learning}}
'''Please do not add new code, and merge existing code to the [[Arrays]] task.'''
This task is about [[numeric arrays]]. For '''hashes''' or '''associative arrays''', please see [[Creating an Associative Array]].

This task is about numerically-indexed 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.
In this task, the goal is to create an [[array]]. Mention if the [[array base]] begins at a number other than zero.
In addition, demonstrate how to initialize an array variable with data.

=={{header|ActionScript}}==
<lang 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];
</lang>

=={{header|Ada}}==
'''Compiler:''' [[GCC]] 4.1.2

Ada array indices may begin at any value, not just 0 or 1
<lang 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);
</lang>
Ada arrays may be indexed by enumerated types, which are discrete non-numeric types
<lang 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);
</lang>

=={{header|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

=={{header|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'''

=={{header|AWK}}==
"Numeric" arrays coincide with hashes in awk. Indices begin at 1.
$ awk 'BEGIN{split("this and that",a);for(i in a)print i":"a[i]}'
1:this
2:and
3:that

=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
{{works with|PB|7.1}}
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"

=={{header|C}}==
{{works with|gcc}}
{{works with|MSVC}}
{{works with|BCC}}
{{works with|Watcom}}
Dynamic
<lang c> #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;
}</lang>

Static

<lang c> int myArray2[10] = { 1, 2, 0}; /* 3..9 := 0 */</lang>

=={{header|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. [[System stack|Stack]]) memory:
int myArray2[10] = { 1, 2, 0}; /* 3..9 := 0 */

{{libheader|STL}}
// STL
std::vector<int> myArray3(10);
myArray3.push_back(1);
myArray3.push_back(2);

{{libheader|Qt}}
// Qt
QVector<int> myArray4(10);
myArray4.push_back(1);
myArray4.push_back(2);

{{libheader|MFC}}
// MFC
CArray<int,int> myArray5(10);
myArray5.Add(1);
myArray5.Add(2);

=={{header|C sharp|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"} };

=={{header|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 <tt>String</tt>.
array :: {#Char}
array = {x \\ x <- ['a' .. 'z']}

=={{header|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'''''

=={{header|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))
<tt>make-array</tt> may be called with a number of optional arguments.
(make-array 4 :element-type 'integer :initial-contents '(1 2 3 4) :adjustable t)

=={{header|D}}==
{{works with|DMD}}
{{works with|GDC}}
// dynamic array
int[] numbers = new int[5];
// static array
int[5] = [0,1,2,3,4];

=={{header|E}}==
[] # immutable, empty
[1,9,17] # immutable, 3 elements
[].diverge() # mutable, empty
[].diverge(int) # mutable, integers only

=={{header|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

=={{header|Fortran}}==
In ANSI FORTRAN 77 or later, this is a default-indexing array declaration:

<lang fortran> integer a(10)</lang>

This array will have ten elements. Counting starts at 1.

If a zero-based array is needed, declare like this:

<lang fortran> integer a(0:9)</lang>

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:

<lang fortran> real a(25:29,12)</lang>

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).

Fortran 90 and later can use also the syntax

<lang fortran>real, dimension(20) :: array</lang>

Dynamic array (in Fortran 90 and later) can be declared as:

<lang fortran>integer, dimension(:), allocatable :: array
real, dimension(:,:), allocatable :: multidim_array</lang>

and then the space can be allocated/deallocated with:

<lang fortran>allocate(array(array_dimension))
allocate(multidim_array(20,20))
!...
deallocate(array)
deallocate(multidim_array)</lang>

where <tt>array_dimension</tt> is an integer.

Dimension of array can be inspected with <tt>size</tt> intrinsic, and bounds with <tt>ubound</tt> and <tt>lbound</tt>:

<lang fortran> real :: array(20:30), another(10,0:19)

print *, size(another) ! 10 elements for the first "column", 20 for the second,
! we obtain 200
print *, size(array) ! from 20 to 30, we can hold 11 values
print *, size(another, 1) ! "column" 1 has 10 elements, from 1 to 10
print *, size(another, 2) ! "column" 2 has 20 elements, from 0 to 19
print *, lbound(array) ! lower bound is 20
print *, ubound(array) ! upper bound is 30
print *, lbound(another,1) ! is 1
print *, lbound(another,2) ! is 0
print *, lbound(another) ! return an array, (/ 1, 0 /)
print *, ubound(another,1) ! is 10
print *, ubound(another,2) ! is 19
print *, ubound(another) ! return an array, (/ 10, 19 /) </lang>

Outputs

<pre> 200
11
10
20
20
30
1
0
1 0
10
19
10 19</pre>

Array can be initialized also using "implied do loop"

<lang fortran> 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"</lang>

There's no way to initialize a matrix, but reshaping it properly:

<lang fortran> 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 /) ) )</lang>

=={{header|Groovy}}==
In Groovy "arrays" are synonymous with "lists", and are thus not of a fixed size. Ranges are also a type of list.
<lang groovy>
def myArray1 = [] // empty list (content may be added as desired)
def myArray2 = [1, 2, 3] // 3-element (for now) list containing first 3 integers
def myArray3 = 1..3 // the same 3-element list expressed as a range.
def myArray4 = ["xx"]*20 // 20-element (for now) list, each element of which is currently the string "xx"
</lang>

=={{header|Haskell}}==

Arrays are initialized either by a list of index-value-pairs or by a list of values:

<pre>
import Data.Array

a = array (1,3) [(1,42),(2,87),(3,95)]
a' = listArray (1,3) [42,87,95]
</pre>

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.

=={{header|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

=={{header|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 <tt>a+b</tt>and the <tt>|."1 c</tt> expressions create arrays.

=={{header|Java}}==
For example for an array of 10 int values:
<lang java>int[] intArray = new int[10];</lang>
Creating an array of Strings:
<lang java>String[] s = {"hello" , "World" };</lang>
Creating an array of Objects:
<lang java>Object[] obs = new Object[size];</lang>

=={{header|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"];

=={{header|Logo}}==
array 5 ; default origin is 1
(array 5 0) ; custom origin

=={{header|LSE64}}==
10 myArray :array

=={{header|MAXScript}}==
{{works with|3D Studio Max|8}}
myArray = #()
myArray2 = #("Item1", "Item2")

=={{header|mIRC Scripting Language}}==
{{works with|mIRC Script Editor}}
{{works with|mArray Snippet}}
alias creatmearray { .echo -a $array_create(MyArray, 5, 10) }

=={{header|Modula-3}}==
Modula-3 arrays include their range in the declaration.
<pre>
VAR a: ARRAY [1..10] OF INTEGER;
</pre>
Defines an array of 10 elements, indexed 1 through 10.

Arrays can also be giving initial values:
<pre>
VAR a := ARRAY [1..10] OF INTEGER {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
</pre>

Modula-3 also offers "open arrays" just like Oberon-2.

Multi-dimensional arrays can be defined as:
<pre>
VAR a: ARRAY [1..10], [1..10] OF INTEGER;
</pre>
Which creates a 2 dimensional array of 10 integers each.

=={{header|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]

=={{header|Oberon-2}}==
Create an array of 10 integers. Initial values are undefined. All arrays are zero-indexed.
<pre>
VAR a: ARRAY 10 OF INTEGER;
</pre>

Oberon-2 has no array constructor syntax.
<pre>
FOR i := 0 TO LEN(a) - 1 DO
a[i] := i + 1;
END;
</pre>

Oberon-2 also has dynamically allocated arrays, called "open arrays". It's size is based on how it is initialized.
<pre>
VAR a: ARRAY OF INTEGER;
</pre>

Multi-dimensional arrays can be defined as:
<pre>
VAR a: ARRAY 10, 10, 10 OF INTEGER;
</pre>
creates a 3 dimensional array of 10 integers each.

=={{header|OCaml}}==
Using an array literal:

let array = [| 1; 2; 3; 4; 5 |];;

Converting from a list:

let array = Array.of_list some_list

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

=={{header|Pascal}}==
=== Using a fixed length array as global or stack variable (all Pascal versions) ===
<lang pascal>
var
a: array[2..10] of integer;
</lang>
The array base is the first number given in the square brackets, the second number gives the largest valid index. Actually the part between the square brackets is a type, therefore also the following works:
<lang pascal>
type
byte: 0..255;
var
a: array[byte] of integer; { same as array[0..255] of integer }
</lang>

=== Dynamically allocating a fixed length array on the heap (all Pascal versions) ===
<lang pascal>
type
arraytype = array[1..25] of char;
arrayptr = ^arraytype;
var
a: arrayptr;
begin
new(a); { allocate the array }
a^[1] := 'c'; { use it }
dispose(a) { get rid of it }
end
</lang>

=== Defining a variable-length array (Extended Pascal) ===
<lang pascal>
type
arraytype(size: integer) = array [1 .. size] of real;
arrayptr = ^arraytype;
var
i: integer;
a: arraytype;
begin
readln(i); { get size from user }
new(a, i); { create array }
a^[1] := 3.14; { use it }
if a^.size = i { access the size }
then
writeln('I expected that.');
else
writeln('Get a better compiler!');
dispose(a) { get rid of it }
end
</lang>
Note that also the lower index may be given as dynamic argument.

=== Defining a variable-length array (Delphi) ===
<lang pascal>
var
i: integer;
a: array of integer;
begin
readln(i);
SetLength(a, i); { create array }
a[0] := 2; { use it }
if high(a) = i
then
writeln('I expected that.');
else
writeln('Get a better compiler!');
finalize(a);
end
</lang>
Delphi dynamic arrays have base 0 index.

=={{header|Perl}}==
{{works with|Perl|5}}
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(! $ % & *)],
];
print $mdref->[1][3];
# d

=={{header|PHP}}==

For a single dimension array with 10 elements:
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) //$array[3] == 3
$array = array("a", "b", "c", "d", "e", "f", "g", "h", "i", "j") //$array[3] == "c"

For a multi-dimension array:
$array = array(
array(0, 0, 0, 0, 0, 0),
array(1, 1, 1, 1, 1, 1),
array(2, 2, 2, 2, 2, 2),
array(3, 3, 3, 3, 3, 3)
);
#You would call the array by this code. This will call the 3rd 1 on the second list
echo $array[1][3];

More:
<pre>
<?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
?>
</pre>

=={{header|Pike}}==
For a single dimension int array:
array(int) x = ({ 1, 2, 3 });

For a single dimension of any type you declare array(mixed) instead of array(int), or just array:
array x = ({ "a", 1, 5.2 });

For a multi-dimension array, you build an array of arrays:
mixed x = ({ ({ 5 }),({ 3, 2 }), ({ 1, 8 }) });

Note that inner arrays can be of different sizes, as are simply values of the outer array.

=={{header|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);

=={{header|Python}}==
List are mutable arrays. You can put anything into a list, including other lists.

<lang python>
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()
</lang>

Tuples are immutable arrays. Note that tuples are defined by the "," - the parenthesis are optional (except to disambiguate when creating an empty or single-element tuple):

<lang python>
empty = ()
numbers = (1, 2, 3, 4, 5)
numbers2 = 1,2,3,4,5 # same as previous
zeros = (0,) * 10
anything = (1, 'foo', 2.57, None, zeros)
</lang>

Both lists and tuples can be created from other iterateables:

<lang python>
>>> 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']
</lang>

Note: In Python 2.6 the ''collections.namedtuple'' factory was added to the standard libraries. This can be used to create classes of lightweight objects (c.f. the Flyweight design pattern) which are tuples that can additionally support named fields.

=={{header|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"

=={{header|Ruby}}==

my_array = Array.new
# This is the most basic way to create an empty one-dimensional array in Ruby.

my_array = 1, 2, 3, 4, 5
# Ruby treats comma separated values on the right hand side of assignment as array. You could optionally surround the list with square bracks
# my_array = [ 1, 2, 3, 4, 5 ]

array = [
[0, 0, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 1],
[2, 2, 2, 2, 2, 2],
[3, 3, 3, 3, 3, 3]
]
# You would call the array by this code. This will call the 4th 1 on the second list
array[1][3]

# You can also create a sequential array from a range using the 'splat' operator:
array = [*0..3]
# or use the .to_a method for Ranges
array = (0..3).to_a
#=> [0,1,2,3]
# This lets us create the above programmatically:
array = [*0..3].map {|i| [i] * 6}
# or use the .map (.collect which is the same) method for Ranges directly
# note also that arrays of length 6 with a default element are created using Array.new
array = (0..3).map {|i| Array.new(6,i)}
# you can also do the first map using Array.new too
array = Array.new(4) {|i| Array.new(6,i)}
#=> [[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3]]

=={{header|Scala}}==
val array = new Array[int](10) // a 10 element array
val stringArray = new Array[String](20) // a 20 element string array
List("Elwood", "Madeline", "Archer").toArray
(List(1,2,3) ::: List(4,5,6)).toArray
(1 :: 2 :: 3 :: 4 :: 5 :: Nil).toArray

=={{header|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)
=={{header|Script3D}}==
Script3D has dynamic arrays allowing to store any datatype and a special type for storing vectors of floating point values, typically used in 3D applications.

var myArray = { "a string" , 1, true, "mixed", Void, 1.5}; // array from list
var myArray = Array(10); // 10 elements array

var myVector = [1,2,3,4];
var myVector = Vector(2000); // 2000 elements vector of floats

=={{header|Smalltalk}}==
<lang smalltalk>|array|
"creates an array that holds up to 20 elements"
array := Array new: 20 .
"access the first element: array base is 1"
(array at: 1) displayNl.
"put 100 as second value; you can put any object,
in particular SmallInteger"
array at: 2 put: 100.
"initialize an array from a 'constant' given array"
array := Array withAll: #('an' 'apple' 'a' 'day' 'keeps' 'the' 'doctor' 'away').
"Replacing apple with orange"
array at: 2 put: 'orange'.</lang>

=={{header|Standard ML}}==
Converting from a list:

val array = Array.fromList [1,2,3,4,5]

To create an array of five elements with the value 0:

val num_items = 5 and initial_value = 0;
val array = Array.array (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):

fun callback index = index * index;
val array = Array.tabulate (5, callback)

In addition to arrays, the Standard ML library also has "vectors", which are immutable arrays. Most implementations support the following syntax for a vector literal, although it is not standard:

val vector = #[1,2,3,4,5]

=={{header|Tcl}}==

Tcl uses the <tt>list</tt> for what many other languages call "array". A list is an ordered, numerically indexable collection of values in a single variable. Each list entry itself can be a list.

<lang tcl>set a [list 5 hello {} [expr 3*5]]</lang>

this creates a list with the name <tt>a</tt> and four elements - the number 5, the word "hello", an empty list, and the result of the expression "3*5".

Tcl does have an "<tt>array</tt>", though, which is really an "associative array":

<lang tcl>array set b {foo 12 bar hello}</lang>

this creates an array with the name <tt>b</tt> with two elements. The keys of the elements are "foo" and "bar" and the values are <tt>b(foo) == 12</tt> and <tt>b(bar) == hello</tt>.

=={{header|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

=={{header|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 " "

=={{header|VBScript}}==

Dim myArray(2)
myArray(0) = "Hello"
myArray(1) = "World"
myArray(2) = "!"

Latest revision as of 15:07, 29 November 2019

Creating an Array was a programming task. It has been deprecated for reasons that are discussed in its talk page.

Please do not add new code, and merge existing code to the Arrays task.

This task is about numerically-indexed 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. In addition, demonstrate how to initialize an array variable with data.