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)
 
(155 intermediate revisions by 50 users not shown)
Line 1: Line 1:
{{DeprecatedTask}}
[http://babydollvamp.110mb.com/library/html/vampire-the/ vampire the masquerade] [http://fasher-el.greylopht.cn fasher el] [http://drkdrgns.freehostia.com/small/caricabatterie-mini.htm caricabatterie mini stilo] [http://oveja-bella.freehostia.com/data/casa-in.htm casa in vendita varese] [http://gatcat.freehostia.com/lib/hotel-tunisi/ hotel tunisi] [http://kleinerachel.110mb.com/img/styles/qtek-pdak/ qtek pda2k i-mate] [http://gatcat.freehostia.com/lib/johnny-depp/ johnny depp nudo] [http://shadowlab.110mb.com/data/canzone-di.html canzone di forza italia] [http://drkdrgns.freehostia.com/small/cartomanzia-consulto.htm cartomanzia consulto] [http://scdeane.angelfire.com/lib/upskirt-tv/ upskirt tv] [http://tipettit.12gbfree.com/elaine-jacson/ elaine jacson] [http://gatcat.freehostia.com/lib/www-elba/ www elba it] [http://cordelia1812.freehostia.com/small/imetec-professional.htm imetec professional] [http://staryfox6.h18.ru/images/small/scarica-norton/ scarica norton antivirus gratis] [http://shadowlab.110mb.com/data/nelly-place.html nelly place] [http://orwheatl.12gbfree.com/resources/miguel-mateos.htm miguel mateos] [http://orwheatl.12gbfree.com/resources/cobol.htm cobol] [http://oveja-bella.freehostia.com/data/boomerman.htm boomerman] [http://gatcat.freehostia.com/lib/the-best/ the best of smoke on water] [http://evil-leprachaun.quotaless.com/articles/two-times.htm two times] [http://drkdrgns.freehostia.com/small/www-latinchan.htm www latinchan com] [http://kleinerachel.110mb.com/img/styles/elthon-jhon/ elthon jhon ft blue] [http://poganetz.free-site-host.com/view/milioanele-de.htm milioanele de stele] [http://babydollvamp.110mb.com/library/html/hinh-sex/ hinh sex nguyen hong nhung] [http://evil-leprachaun.quotaless.com/articles/pampita-ardohain.htm pampita ardohain] [http://kleinerachel.110mb.com/img/styles/calcolatrice-pocket/ calcolatrice pocket pc] [http://babydollvamp.110mb.com/library/html/compandor/ compandor] [http://tipettit.12gbfree.com/casagit/ casagit] [http://waltermoney.cn/bluetooth-motorola.htm bluetooth motorola auricolari] [http://cordelia1812.freehostia.com/small/lesbo.htm lesbo 3] [http://kyle-minogue.panzerfausts.com.cn kyle minogue chocolate] [http://evil-leprachaun.freehostia.com/styles/clic.htm clic] [http://masyavo4ka.freehostia.com/library/albergo-cologne.htm albergo cologne] [http://dark-angel-enni.quotaless.com/styles/coppia-di.htm coppia di como 45] [http://pixie-bite.org.cn/quota-lotto.htm quota lotto] [http://georgiil.net.cn/ballata-in.htm ballata in blu] [http://doubtful-value.free-site-host.com/de-baggis.htm de baggis] [http://onfolioblogtest.quotaless.com/content/searcholdies.htm searcholdies] [http://ricetta-risotto.fast-girl.net.cn ricetta risotto alla pescatora] [http://nadzor-ns.cn/whirlpool-forno.htm whirlpool forno microonde da incasso] [http://shadowlab.110mb.com/data/ilari-blai.html ilari blai] [http://doubtful-value.free-site-host.com/asus-kne.htm asus k8ne deluxe] [http://tipettit.12gbfree.com/pentium/ pentium 4 3 40] [http://poganetz.free-site-host.com/view/catalogo-francobolli.htm catalogo francobolli] [http://doodleandidle.freehostia.com/articles/la-signora.htm la signora amava le rose] [http://pixie-bite.org.cn/sesso-con.htm sesso con immagini] [http://utenti.lycos.it/cosaugo//content/due-vite.htm due vite in pericolo] [http://gatcat.freehostia.com/lib/mvi-canon/ mv850i canon] [http://babydollvamp.110mb.com/library/html/concorso-bibliotecario/ concorso bibliotecario] [http://kleinerachel.110mb.com/img/styles/yamaha/ yamaha 40] [http://dark-angel-enni.quotaless.com/styles/aap.htm aap] [http://youreabigboynow.quotaless.com/blog/video-occhiali/ video occhiali] [http://drkdrgns.freehostia.com/small/tettris.htm tettris] [http://beebarf.awardspace.co.uk/data/portable-mp.htm portable mp3 players] [http://poganetz.free-site-host.com/view/due-donne.htm due donne in gara] [http://toner-mita.sound-of-sun.cn toner mita vi 150] [http://drkdrgns.freehostia.com/small/candy-frigorifero.htm candy frigorifero] [http://casco-bimbo.happi-thoughts.org.cn casco bimbo] [http://drkdrgns.freehostia.com/small/toyota-hilux.htm toyota hilux blu] [http://evil-leprachaun.quotaless.com/articles/buganza.htm buganza] [http://finaira.freehostia.com/text/directory/kohler-disease.htm kohler disease] [http://shadowlab.110mb.com/data/misteriose-forme.html misteriose forme di vita] [http://staryfox6.h18.ru/images/small/giornali-annunci/ giornali annunci vari sicilia] [http://oveja-bella.freehostia.com/data/siti-gratis.htm siti gratis porno] [http://cordelia1812.freehostia.com/small/il-rompiballe.htm il rompiballe rompe ancora] [http://cordelia1812.freehostia.com/small/tour-.htm tour 2004 eros ramazzotti] [http://razorbladegiirl.free-site-host.com/apc-smart.htm apc smart ups 3000va] [http://oveja-bella.freehostia.com/data/andy-e.htm andy e candy] [http://fierydarknez.cn/m-.htm m c servizi] [http://razorbladegiirl.free-site-host.com/so-yesterday.htm so yesterday] [http://tifo-lecce.digirb-backward.cn tifo lecce] [http://jaguar-twin.greylopht.cn jaguar twin turbo v7] [http://beebarf.awardspace.co.uk/data/l-inquinamento.htm l inquinamento] [http://onfolioblogtest.quotaless.com/content/stampante-canon.htm stampante canon ip4000r] [http://kleinerachel.110mb.com/img/styles/vestito-lungo/ vestito lungo] [http://angrybuddha765-gamer.angelfire.com/sony-minidisc/ sony minidisc mznh600] [http://shadowlab.110mb.com/data/religione-induista.html religione induista] [http://kleinerachel.110mb.com/img/styles/testo-della/ testo della legge iva agevolata al 4] [http://utenti.lycos.it/cosaugo//content/grace-kelli.htm grace kelli] [http://nonkomformist.cn/oh-freedom.htm oh freedom] [http://dark-angel-enni.quotaless.com/styles/traduzioni-blue.htm traduzioni blue] [http://dark-angel-enni.quotaless.com/styles/garfield-e.htm garfield e i suoi amici] [http://tipettit.12gbfree.com/francoforte-albergo/ francoforte albergo] [http://beebarf.awardspace.co.uk/data/features-of.htm features of microsoft publisher 2003] [http://kleinerachel.110mb.com/img/styles/connessione-veloce/ connessione veloce] [http://kleinerachel.110mb.com/img/styles/living-dead/ living dead] [http://angrybuddha765-gamer.angelfire.com/x-mb/ x600 256mb] [http://dark-angel-enni.quotaless.com/styles/use-your.htm use your illusion dvd] [http://onfolioblogtest.quotaless.com/content/link-up.htm link up] [http://staryfox6.h18.ru/images/small/patrizia-griffini/ patrizia griffini] [http://gatcat.freehostia.com/lib/ford-focus/ ford focus 18 tdci zetec] [http://shadowlab.110mb.com/data/software-busta.html software busta paga] [http://utenti.lycos.it/cosaugo//content/i-believe.htm i believe yolanda adams] [http://oveja-bella.freehostia.com/data/mon-amant.htm mon amant de jean] [http://georgiil.net.cn/bast.htm bast] [http://onfolioblogtest.quotaless.com/content/remov-os.htm remov os 30 bust 100 mg] [http://tanini.freehostia.com/description/lib/battaglia-aerea/ battaglia aerea simulazione] [http://cordelia1812.freehostia.com/small/hamlet-.htm hamlet zelig] [http://finaira.freehostia.com/text/directory/essenza-jeans.htm essenza jeans] [http://razorbladegiirl.free-site-host.com/ebayyy.htm ebayyy] [http://razorbladegiirl.free-site-host.com/coppia.htm coppia] [http://oveja-bella.freehostia.com/data/laura-antonelli.htm laura antonelli in malizia] [http://doodleandidle.freehostia.com/articles/macchina-per.htm macchina per fumo] [http://dark-angel-enni.quotaless.com/styles/dcrvx-sony.htm dcrvx2100 sony] [http://gatcat.freehostia.com/lib/volo-aereo/ volo aereo roma alghero] [http://girl-lost.angelfire.com/content/tavolo-bambini/ tavolo bambini] [http://gatcat.freehostia.com/lib/seggiolini-auto/ seggiolini auto maxi cosi] [http://fierydarknez.cn/beato-tra.htm beato tra l donne] [http://masyavo4ka.freehostia.com/library/memoria-sodimm.htm memoria sodimm kingston] [http://shadowlab.110mb.com/data/donne-grosse.html donne grosse porche] [http://drkdrgns.freehostia.com/small/renault-kangoo.htm renault kangoo] [http://cordelia1812.freehostia.com/small/seat-ibiza.htm seat ibiza problemi] [http://dustybooks.cn/dog-and.htm dog and woman] [http://usb.kiushapo.cn usb 1 gb sandisk] [http://shadowlab.110mb.com/data/duplicatore-cd.html duplicatore cd] [http://tanini.freehostia.com/description/lib/altri-giochi/ altri giochi da tavolo] [http://doubtful-value.free-site-host.com/generatori-reggio.htm generatori reggio emilia] [http://doodleandidle.freehostia.com/articles/sabanas-frias.htm sabanas frias mana] [http://gatcat.freehostia.com/lib/su-daglarda/ su daglarda] [http://doubtful-value.free-site-host.com/arredi-sacri.htm arredi sacri] [http://rossetto-labbra.fast-girl.net.cn rossetto labbra] [http://oveja-bella.freehostia.com/data/immagini-e.htm immagini e fotografie di animali] [http://razorbladegiirl.free-site-host.com/stern-daniel.htm stern daniel] [http://drkdrgns.freehostia.com/small/rika.htm rika] [http://cordelia1812.freehostia.com/small/gillette-mach.htm gillette mach 3] [http://razorbladegiirl.free-site-host.com/mutuo-costruzione.htm mutuo costruzione] [http://tipettit.12gbfree.com/nani-moretti/ nani moretti] [http://shadowlab.110mb.com/data/bluetooth-wireless.html bluetooth wireless] [http://drkdrgns.freehostia.com/small/anthus.htm anthus] [http://evil-leprachaun.quotaless.com/articles/melissa-puente.htm melissa puente] [http://dustybooks.cn/prestito-lavoratori.htm prestito lavoratori dipendente] [http://kleinerachel.110mb.com/img/styles/assicurazione-bolzano/ assicurazione bolzano] [http://kleinerachel.110mb.com/img/styles/altek/ altek] [http://evil-leprachaun.quotaless.com/articles/case-vacanza.htm case vacanza verona] [http://onfolioblogtest.quotaless.com/content/san-paolo.htm san paolo imi] [http://kleinerachel.110mb.com/img/styles/video-cellulare/ video cellulare] [http://masyavo4ka.freehostia.com/library/lg.htm lg 19] [http://evil-leprachaun.quotaless.com/articles/sfondi-per.htm sfondi per computer] [http://shadowlab.110mb.com/data/milano-malaga.html milano malaga] [http://nonkomformist.cn/incontri-con.htm incontri con foto] [http://razorbladegiirl.free-site-host.com/die-toten.htm die toten hosen live] [http://finaira.freehostia.com/text/directory/brandy-taylor.htm brandy taylor] [http://finaira.freehostia.com/text/directory/jaws.htm jaws] [http://beebarf.awardspace.co.uk/data/symantec-win.htm symantec win fax pro] [http://masyavo4ka.freehostia.com/library/serena-grandi.htm serena grandi tettona] [http://waltermoney.cn/racconi-incestuosi.htm racconi incestuosi] [http://doodleandidle.freehostia.com/articles/dards-d.htm dards 3d] [http://dustybooks.cn/logo-lg.htm logo lg] [http://kleinerachel.110mb.com/img/styles/sodimm-mb/ sodimm 512mb 133mhz 144pin] [http://cordelia1812.freehostia.com/small/buro.htm buro] {{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);
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 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.