Creating an Array: Difference between revisions

From Rosetta Code
Content added Content deleted
mNo edit summary
(Blanked page since people can't / don't read)
 
(153 intermediate revisions by 49 users not shown)
Line 1: Line 1:
{{DeprecatedTask}}
[http://bressanone.romanikki.cn/index.html bressanone] [http://kitmun.cn/yankee-progdvb.html yankee progdvb] [http://wonted.cn/www-villaggioglobale/index.html www villaggioglobale com] [http://wonted.cn/www-mazinga-com/index.html www mazinga com] [http://snailtail.cn/xatzigiannis/index.html xatzigiannis to sagapo] [http://wonted.cn/www-interbus/index.html www interbus it] [http://bittersweetsimphony.fast-road.cn/index.html bitter sweet simphony] [http://brotherspearlharbour.kittiss.cn/index.html brothers pearl harbour] [http://quoits.cn/zingaro-felice.html zingaro felice alex britti] [http://battaglionesanmarco.romanikki.cn/index.html battaglione san marco] [http://kitmun.cn/yu-gy-oh.html yu gy oh su internet] [http://ballatapermaria.romanikki.cn/index.html ballata per maria] [http://bakethalleluja.clung.cn/index.html bak et halleluja] [http://kitmun.cn/yu-gi-of.html yu gi of] [http://wonted.cn/www-unisg/index.html www unisg it] [http://snailtail.cn/yume-no/index.html yume no nnaka e] [http://bastonade.kittiss.cn/index.html bastonade] [http://quoits.cn/amarti.html amarti a new york] [http://knock-knock.cn/www-wwfitalia/index.html www wwfitalia it] [http://snailtail.cn/xman/index.html xman] [http://wonted.cn/www-f3f3-com/index.html www f3f3 com] [http://snailtail.cn/www-superfighetto/index.html www superfighetto] [http://beatifulpharrell.clung.cn/index.html beatiful pharrell] [http://quoits.cn/zaton-mali.html zaton mali] [http://wonted.cn/www-overtechno/index.html www overtechno com] [http://snailtail.cn/xat/index.html xat] [http://knock-knock.cn/www-natisone/index.html www natisone it] [http://quoits.cn/zanfranceschi.html zanfranceschi] [http://kitmun.cn/yann-destal.html yann destal] [http://barbrastreisandmemory.clung.cn/index.html barbra streisand memory] [http://quoits.cn/anno-2020:.html anno 2020: i gladiatori del futuro] [http://britneyspearce.midways.cn/index.html britney spearce] [http://snailtail.cn/xportal/index.html xportal biz] [http://knock-knock.cn/www-viva/index.html www viva gsm com] [http://kitmun.cn/zeljko.html zeljko samardzic ljubavnik] [http://kitmun.cn/youth-of.html youth of the nation] [http://knock-knock.cn/www-podrido/index.html www podrido com mx] [http://quoits.cn/anchorman..html anchorman. la leggenda di ron burgundy] [http://kitmun.cn/yankse-1-4.html yankse 1 4] [http://bregbeheading.romanikki.cn/index.html breg beheading] [http://knock-knock.cn/www-mega-cl/index.html www mega cl] [http://kitmun.cn/yaou-italia.html yaou italia] [http://bunnyteens.fast-road.cn/index.html bunny teens] [http://baboombakar.fast-road.cn/index.html baboomba kar] [http://knock-knock.cn/www-med-unifi/index.html www med unifi it] [http://babybudsuk.clung.cn/index.html babybuds uk] [http://quoits.cn/amburgo.html amburgo squadra omicidi] [http://quoits.cn/zorritas.html zorritas muy calientes] [http://bacitraragazze.fast-road.cn/index.html baci tra ragazze] [http://buddabariii.midways.cn/index.html budda bar iii] [http://bossamidiloops.kittiss.cn/index.html bossa midi loops] [http://quoits.cn/acciuffate-quella.html acciuffate quella donna] [http://wonted.cn/www-tribunaledibrindisi/index.html www tribunaledibrindisi] [http://quoits.cn/amori-pericolosi.html amori pericolosi] [http://kitmun.cn/your-songs.html your songs] [http://kitmun.cn/zucchero-everybody.html zucchero everybody s got to learn sometime] [http://buffoon.kittiss.cn/index.html buffoon] [http://wonted.cn/www-gdp-ch/index.html www gdp ch] [http://snailtail.cn/www-quarterhorse/index.html www quarterhorse it] [http://bornslippy.fast-road.cn/index.html born slippy] [http://snailtail.cn/www-figc-dilettanti/index.html www figc dilettanti er it] [http://boccacioit.fast-road.cn/index.html boccacio it] [http://kitmun.cn/yhe-411.html yhe 411] [http://bacifrauomini.kittiss.cn/index.html baci fra uomini] [http://snailtail.cn/www-shede/index.html www shede libro it] [http://snailtail.cn/xxx-grande-fratello/index.html xxx grande fratello] [http://bezcisnien.kittiss.cn/index.html bez cis nien] [http://wonted.cn/www-recing/index.html www recing live com] [http://wonted.cn/www-uniroma2/index.html www uniroma2 it] [http://kitmun.cn/your-song-moulin.html your song moulin rouge] [http://bettycurtis.kittiss.cn/index.html betty curtis] [http://quoits.cn/a-casa-con.html a casa con i webber] [http://wonted.cn/www-ritrattid/index.html www ritrattid autore it] [http://bennybennassy.romanikki.cn/index.html benny bennassy] [http://kitmun.cn/yolanda-adams.html yolanda adams i believe] [http://snailtail.cn/www-iacp-napoli/index.html www iacp napoli it] [http://kitmun.cn/zie-mignotte.html zie mignotte] [http://wonted.cn/www-aranxaescort/index.html www aranxaescort com] [http://kitmun.cn/yugiho.html yugiho] [http://knock-knock.cn/www-loghi/index.html www loghi] [http://wonted.cn/www-sindacato/index.html www sindacato it] [http://wonted.cn/www-atrevida/index.html www atrevida com br] [http://snailtail.cn/y-yo-sigo/index.html y yo sigo aqui paulina rubio] [http://wonted.cn/www-uefa-com/index.html www uefa com] [http://quoits.cn/zorba-polifonico.html zorba polifonico] [http://snailtail.cn/yeke-yeke-mory/index.html yeke yeke mory kante] [http://wonted.cn/www-porno-gratis/index.html www porno gratis] [http://beyoncacrazyinlove.kittiss.cn/index.html beyonca crazy in love] [http://wonted.cn/www-jaguar-it/index.html www jaguar it] [http://bancadilodianzolaemilia.clung.cn/index.html banca di lodi anzola emilia] [http://wonted.cn/www-cometeuomo/index.html www cometeuomo it] [http://branderoderick.kittiss.cn/index.html brande roderick] [http://kitmun.cn/yu-ghi-oh-mania.html yu ghi oh mania] [http://snailtail.cn/xxxadult/index.html xxxadult] [http://belindamp3.romanikki.cn/index.html belinda mp3] [http://knock-knock.cn/www-vergilio/index.html www vergilio it] [http://buscandoamistades.fast-road.cn/index.html buscando amistades] [http://kitmun.cn/yu-sex.html yu sex] [http://blackbird.romanikki.cn/index.html blackbird] [http://quoits.cn/zacepa.html zacepa] [http://kitmun.cn/you-re-the.html you re the best around] [http://knock-knock.cn/www-consumptiojunction/index.html www consumptiojunction com] [http://bluecurtainfallsmp3.kittiss.cn/index.html blue curtain falls mp3] [http://knock-knock.cn/www-sda-it/index.html www sda it] [http://bradpittaroma.kittiss.cn/index.html brad pitt a roma] [http://knock-knock.cn/www-bertiroberto/index.html www bertiroberto] [http://snailtail.cn/xcel-2000/index.html xcel 2000] [http://knock-knock.cn/www-notte/index.html www notte it] [http://wonted.cn/www-atd-ch/index.html www atd ch] [http://quoits.cn/zs-reticoli.html zs reticoli] [http://quoits.cn/za-za-yacuza.html za za yacuza] [http://knock-knock.cn/www-ip-relay/index.html www ip relay com] [http://snailtail.cn/www-playstatio/index.html www playstatio it] [http://wonted.cn/www-regalbuto/index.html www regalbuto it] [http://wonted.cn/www-farmsex-com/index.html www farmsex com] [http://brincandodemedico.clung.cn/index.html brincando de medico] [http://bible.clung.cn/index.html bible] [http://barbarachapini.romanikki.cn/index.html barbara chapini] [http://kitmun.cn/zharik.html zharik] [http://quoits.cn/amore-al.html amore al primo morso] [http://knock-knock.cn/www-thehun/index.html www thehun] [http://kitmun.cn/your-avon.html your avon com] [http://brianwilson.fast-road.cn/index.html brian wilson] [http://kitmun.cn/zip-sp-elaborati.html zip sp elaborati] [http://blackeyedpeaseshutup.clung.cn/index.html black eyed pease shut up] [http://brotkaten.midways.cn/index.html brotka ten] [http://kitmun.cn/zia-vacca.html zia vacca] [http://kitmun.cn/yhaoo.html yhaoo] [http://bisca99posse.fast-road.cn/index.html bisca 99 posse] [http://wonted.cn/www-galassia/index.html www galassia 303] [http://knock-knock.cn/www-tiscali/index.html www tiscali com] [http://wonted.cn/www-shakira/index.html www shakira con] [http://snailtail.cn/www-gente-e/index.html www gente e motori it] [http://knock-knock.cn/www-francoforte/index.html www francoforte com] [http://snailtail.cn/xalendari/index.html xalendari] [http://basemusicalevivoperlei.kittiss.cn/index.html base musicale vivo per lei] [http://quoits.cn/aiuto--.html aiuto - help!] [http://quoits.cn/zlata-petrovic.html zlata petrovic] [http://knock-knock.cn/www-alessia/index.html www alessia trani it] [http://bestmovie.clung.cn/index.html bestmovie] [http://snailtail.cn/xnview/index.html xnview] [http://knock-knock.cn/webcam-e/index.html webcam e chat sempre aperte senza dailer] [http://bollos.kittiss.cn/index.html bollo s] [http://briargroveelem.romanikki.cn/index.html briargrove elem] [http://knock-knock.cn/www-musicaincontro/index.html www musicaincontro it] [http://snailtail.cn/xexx/index.html xexx] [http://bergnick.romanikki.cn/index.html berg nick] [http://kitmun.cn/ytunnelpro-330.html ytunnelpro 330] [http://billabongbeachtour.clung.cn/index.html billabong beach tour] [http://bellmobility.romanikki.cn/index.html bellmobility] {{task}}
'''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.
==[[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);
//
// or just use the shorthand
var u:Array = [];
var v: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 (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]]==
[[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

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]]==
[[Category: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 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);
myAr
2000
ray3.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 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]]==
[[Category: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']}

==[[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'''''

==[[Common Lisp]]==
[[Category: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)

==[[D]]==
[[Category:D]]
'''Compiler:''' [[DMD]],[[GDC]]

// dynamic array
int[] numbers = new int[5];
// static array
int[5] = [0,1,2,3,4];

==[[E]]==
[[Category:E]]

[] # immutable, empty
[1,9,17] # immutable, 3 elements
[].diverge() # mutable, empty
[].diverge(int) # mutable, integers only

==[[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 throw to MyArray

Dynamic array free:
MyArray free throw
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]]
'''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(! $ %

==[[Toka]]==
[[Category: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

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.