Creating an Array: Difference between revisions
(→[[Java]]: Use Java header instead) |
m (Switch to header template) |
||
Line 4: | Line 4: | ||
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. |
||
== |
=={{header|ActionScript}}== |
||
[[Category:ActionScript]] |
|||
// ActionScript arrays are zero-based |
// ActionScript arrays are zero-based |
||
// |
// |
||
Line 17: | Line 16: | ||
var v:Array = [1,2,3]; |
var v:Array = [1,2,3]; |
||
== |
=={{header|Ada}}== |
||
[[Category:Ada]] |
|||
'''Compiler:''' GCC 4.1.2 |
'''Compiler:''' GCC 4.1.2 |
||
Line 34: | Line 32: | ||
This_Week : Daily_Activities := (Mon..Fri => Work, Others => Fish); |
This_Week : Daily_Activities := (Mon..Fri => Work, Others => Fish); |
||
== |
=={{header|AppleScript}}== |
||
[[Category:AppleScript]] |
|||
AppleScript arrays are called lists: |
AppleScript arrays are called lists: |
||
set empty to {} |
set empty to {} |
||
Line 44: | Line 40: | ||
set any to {1, "foo", 2.57, missing value, ints} |
set any to {1, "foo", 2.57, missing value, ints} |
||
== |
=={{header|BASIC}}== |
||
[[Category:BASIC]] |
|||
'''Interpeter:''' [[QuickBasic]] 4.5, PB 7.1 |
'''Interpeter:''' [[QuickBasic]] 4.5, PB 7.1 |
||
Line 61: | Line 56: | ||
myArray(1,2) = "Item2" |
myArray(1,2) = "Item2" |
||
== |
=={{header|C}}== |
||
[[Category:C]] |
|||
'''Compiler:''' GCC, MSVC, BCC, Watcom |
'''Compiler:''' GCC, MSVC, BCC, Watcom |
||
Line 120: | Line 114: | ||
myArray5.Add(2); |
myArray5.Add(2); |
||
== |
=={{header|C sharp|C#}}== |
||
[[Category:C sharp]] |
|||
Example of array of 10 int types: |
Example of array of 10 int types: |
||
Line 148: | Line 141: | ||
string[,] funny_matrix = new string[2,2]{ {"clowns", "are"} , {"not", "funny"} }; |
string[,] funny_matrix = new string[2,2]{ {"clowns", "are"} , {"not", "funny"} }; |
||
== |
=={{header|Clean}}== |
||
[[Category:Clean]] |
|||
Array denotations are overloaded in Clean, therefore we explicitly specify the types. There are lazy, strict, and unboxed array. |
Array denotations are overloaded in Clean, therefore we explicitly specify the types. There are lazy, strict, and unboxed array. |
||
===Lazy array=== |
===Lazy array=== |
||
Line 170: | Line 162: | ||
array = {x \\ x <- ['a' .. 'z']} |
array = {x \\ x <- ['a' .. 'z']} |
||
== |
=={{header|ColdFusion}}== |
||
[[Category:ColdFusion]] |
|||
Creates a one-dimensional Array |
Creates a one-dimensional Array |
||
<cfset arr1 = ArrayNew(1)> |
<cfset arr1 = ArrayNew(1)> |
||
Line 180: | Line 171: | ||
''ColdFusion Arrays are '''NOT''' zero-based, they begin at index '''1''''' |
''ColdFusion Arrays are '''NOT''' zero-based, they begin at index '''1''''' |
||
== |
=={{header|Common Lisp}}== |
||
[[Category:Common Lisp]] |
|||
Creates a one-dimensional array of length 10. The initial contents are undefined. |
Creates a one-dimensional array of length 10. The initial contents are undefined. |
||
(make-array 10) |
(make-array 10) |
||
Line 189: | Line 179: | ||
(make-array 4 :element-type 'integer :initial-contents '(1 2 3 4) :adjustable t) |
(make-array 4 :element-type 'integer :initial-contents '(1 2 3 4) :adjustable t) |
||
== |
=={{header|D}}== |
||
[[Category:D]] |
|||
'''Compiler:''' [[DMD]],[[GDC]] |
'''Compiler:''' [[DMD]],[[GDC]] |
||
Line 199: | Line 188: | ||
int[5] = [0,1,2,3,4]; |
int[5] = [0,1,2,3,4]; |
||
== |
=={{header|E}}== |
||
[[Category:E]] |
|||
[] # immutable, empty |
[] # immutable, empty |
||
[1,9,17] # immutable, 3 elements |
[1,9,17] # immutable, 3 elements |
||
Line 207: | Line 194: | ||
[].diverge(int) # mutable, integers only |
[].diverge(int) # mutable, integers only |
||
== |
=={{header|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. |
Forth has a variety of ways to allocate arrays of data, though it has no built-in array handling words, favoring pointer manipulation. |
||
Line 230: | Line 215: | ||
0 to MyArray |
0 to MyArray |
||
== |
=={{header|Fortran}}== |
||
[[Category:Fortran]] |
|||
Default case: |
Default case: |
||
Line 248: | Line 231: | ||
== |
=={{header|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. |
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. |
||
Line 274: | Line 255: | ||
String[] s = {"hello" , "World" }; |
String[] s = {"hello" , "World" }; |
||
== |
=={{header|JavaScript}}== |
||
[[Category:JavaScript]] |
|||
var myArray = new Array(); |
var myArray = new Array(); |
||
var myArray2 = new Array("Item1","Item2"); |
var myArray2 = new Array("Item1","Item2"); |
||
Line 283: | Line 263: | ||
10 myArray :array |
10 myArray :array |
||
== |
=={{header|MAXScript}}== |
||
[[Category:MAXScript]] |
|||
'''Interpreter:''' [[3D Studio Max]] 8 |
'''Interpreter:''' [[3D Studio Max]] 8 |
||
myArray = #() |
myArray = #() |
||
myArray2 = #("Item1", "Item2") |
myArray2 = #("Item1", "Item2") |
||
== |
=={{header|mIRC Scripting Language}}== |
||
[[Category:mIRC Scripting Language]] |
|||
'''Interpeter:''' mIRC Script Editor |
'''Interpeter:''' mIRC Script Editor |
||
'''Libraries:''' [[mArray Snippet]] |
'''Libraries:''' [[mArray Snippet]] |
||
alias creatmearray { .echo -a $array_create(MyArray, 5, 10) } |
alias creatmearray { .echo -a $array_create(MyArray, 5, 10) } |
||
== |
=={{header|OCaml}}== |
||
[[Category:OCaml]] |
|||
Using an array literal: |
Using an array literal: |
||
Line 312: | Line 289: | ||
== |
=={{header|Perl}}== |
||
[[Category:Perl]] |
|||
'''Interpreter:''' [[Perl]] 5 |
'''Interpreter:''' [[Perl]] 5 |
||
Line 345: | Line 321: | ||
[qw(! $ % |
[qw(! $ % |
||
== |
=={{header|Pop11}}== |
||
[[Category:Pop11]] |
|||
Pop11 distinguishes between vectors and arrays. Vectors are one |
Pop11 distinguishes between vectors and arrays. Vectors are one |
||
dimensional and the lowest index is 1. There is special shorthand |
dimensional and the lowest index is 1. There is special shorthand |
||
Line 366: | Line 340: | ||
vars a1 = newarray([2 5 -1 1], 0); |
vars a1 = newarray([2 5 -1 1], 0); |
||
== |
=={{header|Python}}== |
||
[[Category:Python]] |
|||
List are mutable arrays. You can put anything into a list, including other lists. |
List are mutable arrays. You can put anything into a list, including other lists. |
||
Line 401: | Line 373: | ||
</pre> |
</pre> |
||
== |
=={{header|Raven}}== |
||
[[Category:Raven]] |
|||
[ 1 2 3.14 'a' 'b' 'c' ] as a_list |
[ 1 2 3.14 'a' 'b' 'c' ] as a_list |
||
a_list print |
a_list print |
||
Line 415: | Line 385: | ||
5 => "c" |
5 => "c" |
||
== |
=={{header|Ruby}}== |
||
[[Category:Ruby]] |
|||
I've used the same examples as the Python-example above. |
I've used the same examples as the Python-example above. |
||
. |
. |
||
Line 426: | Line 395: | ||
anything = [1, 'foo', 2.57, zeros] |
anything = [1, 'foo', 2.57, zeros] |
||
== |
=={{header|Toka}}== |
||
[[Category:Toka]] |
|||
Toka allows creation of an array using is-array. Access to the elements is done using |
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 |
get-element, put-element, get-char-element, and put-char-element functions. You can |
Revision as of 06:01, 13 November 2007
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
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 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
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}
BASIC
Interpeter: QuickBasic 4.5, 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"
C
Compiler: GCC, MSVC, BCC, Watcom
Libraries: Standard 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++
Compiler: GCC, 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#
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 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
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
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
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 myArray2 = new Array("Item1","Item2"); var myArray3 = ["Item1", "Item2"];
LSE64
10 myArray :array
MAXScript
Interpreter: 3D Studio Max 8
myArray = #() myArray2 = #("Item1", "Item2")
mIRC Scripting Language
Interpeter: mIRC Script Editor Libraries: mArray Snippet
alias creatmearray { .echo -a $array_create(MyArray, 5, 10) }
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
Interpreter: 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(! $ %
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]
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