Creating an Array: Difference between revisions

Blanked page since people can't / don't read
(→‎[[C]]: Added syntax highlighting)
(Blanked page since people can't / don't read)
 
(216 intermediate revisions by 60 users not shown)
Line 1:
{{taskDeprecatedTask}}
'''Please do not add new code, and merge existing code to the [[Arrays]] task.'''
<div class="messagebox">This task is about [[numeric arrays]]. For '''hashes''' or '''associative arrays''', please see [[Creating an Associative Array]].</div>
 
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.
==[[ActionScript]]==
In addition, demonstrate how to initialize an array variable with data.
[[Category: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);
 
==[[Ada]]==
[[Category:Ada]]
'''Compiler:''' GCC 4.1.2
 
Ada array indices may begin at any value, not just 0 or 1
type Arr is array (Positive 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 arrays may be indexed by enumerated types, which are discrete non-numeric types
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);
 
==[[AppleScript]]==
[[Category:AppleScript]]
AppleScript supports "arrays" as "lists," and they are not limited by a single type.
set array1 to {}
set array2 to {1, 2, 3, 4, "hello", "world"}
 
==[[BASIC]]==
[[Category:BASIC]]
'''Interpeter:''' [[QuickBasic]] 4.5, PB 7.1
 
' $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]]==
[[Category:C]]
'''Compiler:''' GCC, MSVC, BCC, Watcom
 
'''Libraries:''' Standard
Dynamic
<highlightSyntax language=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;
}
</highlightSyntax>
Static
<highlightSyntax language=C>
int myArray2[10] = { 1, 2, 0}; /* 3..9 := 0 */
</highlightSyntax>
 
==[[C plus plus|C++]]==
[[Category:C plus plus]]
'''Compiler:''' [[GCC]], [[Visual C plus plus|Visual C++]], [[BCC]], [[Watcom]]
 
 
Using dynamically-allocated 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 memory:
int myArray2[10] = { 1, 2, 0}; /* 3..9 := 0 */
 
'''Libraries:''' [[STL]]
// STL
std::vector<int> myArray3(10);
myArray3.push_back(1);
myArray3.push_back(2);
 
'''Libraries:''' [[Qt]]
// Qt
QVector<int> myArray4(10);
myArray4.push_back(1);
myArray4.push_back(2);
 
'''Libraries:''' [[Microsoft Foundation Classes]]
// MFC
CArray<int,int> myArray5(10);
myArray5.Add(1);
myArray5.Add(2);
 
==[[C sharp|C#]]==
[[Category:C sharp]]
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-Deminsional arrays you delcare 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"} };
 
==[[ColdFusion]]==
[[Category: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'''''
 
==[[D]]==
[[Category:D]]
'''Compiler:''' [[DMD]],[[GDC]]
 
// dynamic array
int[] numbers = new int[5];
// static array
int[5] = [0,1,2,3,4];
 
==[[Forth]]==
[[Category: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 to MyArray
 
Dynamic array free:
MyArray free
0 to MyArray
 
==[[Fortran]]==
[[Category:Fortran]]
 
Default case:
 
integer a(10)
 
this 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 allowed number of dimensions (and of course to other data types than integers). For example
 
real*8 (25:29,12)
 
will be an two-dimensional, 5x12-array of 8-byte floats, where the first dimension can be addressed numerically as 25, 26, 27, 28 or 29 (and the second dimension as 1 .. 12).
 
 
==[[IDL]]==
[[Category:IDL]]
 
IDL doesn't really distinguish between scalars and arrays - the same operations that can create the one can <i>usually</i> 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
 
==[[Java]]==
[[Category: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]]==
[[Category:JavaScript]]
var myArray = new Array();
var myArray2 = new Array("Item1","Item2");
var myArray3 = ["Item1", "Item2"];
 
==[[MAXScript]]==
[[Category:MAXScript]]
'''Interpreter:''' [[3D Studio Max]] 8
myArray = #()
myArray2 = #("Item1", "Item2")
 
==[[mIRC Scripting Language]]==
[[Category:mIRC Scripting Language]]
'''Interpeter:''' mIRC Script Editor
'''Libraries:''' [[mArray Snippet]]
alias creatmearray { .echo -a $array_create(MyArray, 5, 10) }
 
==[[OCaml]]==
[[Category: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]]==
[[Category:Perl]]
'''Interpeter:''' [[Perl]]
 
use vars qw{ @Array };
 
@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 3rd 1 on the second list
print $Array[1][3];
 
# Alternative:
my @array_using_qw = qw/coffee sugar cream/;
 
# Alternative:
my @Array3 = ();
push @Array3, "Item1";
push @Array3, "Item2";
$Array3[2] = "Item3";
$Array3[3][0] = "Item4";
 
@Array = ('This', 'That', 'And', 'The', 'Other');
 
$ArrayRef = ['This', 'That', 'And', 'The', 'Other'];
print $ArrayRef->[2]; # would print "And"
 
==[[PHP]]==
[[Category: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];
 
==[[Python]]==
[[Category:Python]]
'''Interpeter:''' Python 2.3, 2.4, 2.5
 
A Python list() is implemented as a dynamical array.
<pre>
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]]
</pre>
You would call the array by this code. This will call the 3rd 1 on the second list:
 
array[1][3]
 
Alternatively you can create it programmatically with a list comprehension:
 
array = [[i]*6 for i in xrange(4)]
 
Create an empty array:
 
array = []
 
==[[Ruby]]==
[[Category: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)}
#=> [[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3]]
 
==[[Scala]]==
[[Category: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
 
 
==[[Smalltalk]]==
[[Category:Smalltalk]]
array := Array withAll: #('an' 'apple' 'a' 'day' 'keeps' 'the' 'doctor' 'away').
 
"Access the first element of the array"
elem := array at: 1.
 
"Replace apple with orange"
array at: 2 put: 'orange'.
 
==[[Tcl]]==
[[Category: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.
 
set a [list 5 hello {} [expr 3*5]]
 
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":
 
array set b {foo 12 bar hello}
 
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>.
 
==[[Visual Basic .NET]]==
[[Category:Visual Basic .NET]]
'''Compiler:''' [[Visual Basic .NET]] 2005
Dim myArray() as String = New String() {"Hello", "World", "!"}
 
==[[VBScript]]==
[[VBScript]]
 
Dim myArray(2)
myArray(0) = "Hello"
myArray(1) = "World"
myArray(2) = "!"
10,327

edits