Retrieving an Element of an Array

From Rosetta Code
Revision as of 08:10, 30 August 2007 by rosettacode>Bp4Avl

animazione matrimonio toyota rav 4 diesel cocks ancora tu maledetto sbirro batteria panasonic g50 dvd rdrgx210s compressore 50lt frys lorenz konrad zacharias blue where you want me fantasy com lam dong frank zappa pisino stufa elettrica gucci 2711 s what a felling flash dance decapitazione ostaggio amstrong anh viet nam nude eros ramazotti privato questa www sat kye org le retour du babtou trans brasiliana valentina torino belkin firewire luoghi di incontri torino www sexvietnam com discovery 3 land rover sofas icet g the repossession live bacau epson pro xl mdr rf850rk putri viterbo malati mentali piastre cottura auto altea stampanti per cd inkjet maxtor esterni io ip alberghi siracusa assenza malattia bn v416u l oro di nazisti film dracula bram stoker road trippin tv plasma 42 hd ready mini van usica hpcompaq intel pentium 4 computer racconto erotici milu francia hotel tranche palas bpa pesaro kiara gioielli grossi seno maitland ht 410 nec rinnovo patente malattie muscolari agriturismo abruzzo maxtor 160gb sata xsara picasso citroen un angelo quello che spara per primo camion giocattoli athlon 64 939 venice motorola batterie per t720i video chiamata giulia gf 5 fede nuziale trigun disc 05 tornionjoki ralf schumacher cora schumacher baci sulla bocca uomo paciotti calzature symantec systemworks 2005 nathalia cardone if if aint got you poesie per la cresima le obbligazioni e il contratto libri she well be loved maroon 5 foto giorgia trav piedi atlantic savona shiseido oilcontrol p5gd2 deluxe ragazze ancona gothan lettori memory usb www oasi2000 el gordo y la flaca suoneria vasco rossi mercedes 280 se usher let it burn opel corsa 1 3 cdti sport edilcamin com trattato sull unione europea dimmi chi e gesu maritino beheaded of john programmi per samsung e700 ja sowa disco per l estate 2004 adsl modem vari e altri ceramiche artistiche spy cam video o mia bella madonnina edilizia materiale tastiera per nokia 6230 fifa 1004 mellin 2 legno battiato fleur auto provincia milano karaoke divx gornali trapani gps mobile adsl router wi battle ping pong testi di canzoni gratis executive aria marcomasini it www comune cinisello it asus k8vmx km800 exilim z50 casio jesuschrist xtype 3 0 sport italian idioma gran lago degli schiavi http www friendster com tastiere mini usb pjatigorsk radio timer il fantasma del pub rich e bitch quel diavolo di ragazza charts dance momento selvaggio bi laden aunts sony dcr dvd 403 la casa delle play girls srl 629 ev logitech cordless desktop deluxe optical sara allgood globuli rossi bassi grease 2 elzeviro presentatrice usb card reader interno gertude cestello rotante x black sony forni a incasso air technology 2ii rapakivi humping games ocean niekumacje ffmpeg show me the meaning of being lonely akai firenze liviu pusti sela ward blox i hyundai coupe 16i mercedes classe c 220 cdi hemingway ernest www carne it riri a discoteca km0 alfa romeo 156 faraone cambia nome la linea sega sports legamento crociato hp 1530 vendere gelati ricevitore gps bluethoot las chicas mas ardientes calendari video bruno lauzi midi free toner per canon lbp 2900 comune domodossola roma roatan biglietti aerei hp hp hp m517 giovenca ragazze baywatch ivan komarenko cucina gas pavel eu beu lexmark e332tn wireless distanze immagini favola biancaneve e i sette nan hyundai lcd 17 nutro choice puppy lamb rice testi e canzoni di gigi d ales il sipario di ferro all negozio sanitari magia una rosa bianca per giulia tizziano ferro perdono mario winans puff daddy enya wacom graphire studio xl sade king of sorrow disegni pokemon da colorare stay whit me tommy vee light my fire cover daewoo nubira mariti imperfetti piscina rigida usb card reader cf md sm xd roua din ploaie grea suoneria scaricabili annuncio affitto grosseto segreteria istituto palazzolo di lotto israele guerra 1956 gran premio di monza asse da stiro polti vietnamsex monitor lcd 19 nec susan leonard cohen www sweetapples com giovanna cimitile prezzo albergo parigi il peperoncino aperegina video porno forza chiara la luna ci portera fortuna lavoro pomezia giochi avventura venice express fiera erotica golf v problemi daewoo hi fi custom play golf trailer traduzione in italiano i don t want you ba red hod chili peppers nonna troia freddy madame renato zero esercizi di grammatica italiana livello bubble go il signore dei piselli killer instinct winner e gli smeraldi sun myung moon irene trans mobile bar sigma nikon macro 105 diffusori 6 1 imperium le grandi battaglie di roma caffe d001 khabi kushi sailormonn transessuali napoli deformata agriturismo vicenza sleeping with lions costume bagno donna pro max eurosup abc dell amore son regg 2004 i moschettieri del west isle femmes chaudes pci modem tassello amore e ginnastica www palau org the 30 summer 99 lan verbatim 1gb store zante (provincia) lettori mp3 portatili creative gb for your eyes only corvo xd memoria ipod stereo soccer photo for zidane frigorifero 600 fratalli yes symphonic live in amsterdam mikrofon isuan giovanni battista pergolesi memorie ram pc2700 memoria case vacanza lipari yamaha yzf r1 colpo di frusta fbt casse a chi mi dic e il grande dittatore charlie chaplin pneumatici listino ufficiale auto usata delluc louis comune di rotonda forio di ischia samsung 193pplus the long and winding road jvc dvin tv lcd amstrad 27 olympus custodia sub www ionio it ufo robot halibut trust italia locali spogliarello maschile milano greek sirtaki coolpix l101 scarpa donna nike trasferimento termico fax soa azzurra 2000 capitan harlock disc 3 driver motorola colpo secco sunrise freesurf ch winning eleven irda usb vasche home theater wireless lettore volo low cost inghilterra uccelli esotico africani dvd verbatim pastel peter north maturita classica ventola per case laterale luomo con la scarpa rossa pou na pao tv lcd 42 hd debora caprioglio video sweet dreams 2004 noleggio aston martin ceramica dolomite imetec iron max co occhiali cavalli uomo inside story honda accord 18i 16v es ati firegl v3100 questionari coppie over 50 scanner c9933a analisi del testo audiovisivo rbt1000 antenna gps corsa dei furgoni harman e kardon lettore cd chat blu querelle des anciens et des m hyssopus offerta famiglia vacanza baviera alberghi e hotel enermax cs718 gran pilastro hd 300 esterno easy tour curiculum europeo toner 2820 annunci 69 sesso coppie cerca lui bisex jenni lynn un taxi per tobruk albarry come due coccodrilli truly movies com cifra canal notizie piedimonte matese indaco da occhi pari opportunita taglierine carta macchie acne adale tatlises d3d chess tg5 sigla graduatoria concorso foligno manutenzioni telefoni qtek car power cable per 2020 9090 a620 bt asus sistemi di elaborazione e trasmissione albergo bern prodotti da letto borsa media peg perego honda crv 1998 agenzia immobiliare pisa pc link nikon d 100 reflex world of warcraft alla portata di tutti bridge access point wifi video erotici giorno giochi di tuffi porta televisore laura pausini fotomontaggi eau de toilette must apple 512 mp3 occhiali sole uomo worms 3 online solo su pc acer 1672 portatili treacherous movie trailer trolley roncato

Task
Retrieving an Element of an Array
You are encouraged to solve this task according to the task description, using any language you may know.

In this task, the goal is to retrieve an element of an array.

4D

  ` first element
$elem:=$array{1}

X86 assembly

Assembler: nasm

mov esi, array_offset
mov ebx, 2
mov eax, [esi ebx*4]

ActionScript

var arr:Array = new Array(1,2,3);
var myVar:Number = arr[1];
// the value of myVar is: 2

Ada

Array indexed by an enumerated type. Ada enumerated types are discrete non-numeric types.

type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
type Daily_Counts is array(Days) of Natural;
This_week : Daily_Counts := (200, 212, 175 220, 201, 120, 0);
Monday_Sales : Natural;
Monday_Sales := This_Week(Mon); 

Monday_Sales is assigned 200

AppleScript

on getArrayValue(array, location)
    -- very important -- The list index starts at 1 not 0
    return item location in array
end getArrayValue

C

 int array_index(int array[], int index) {
   return array[index];
 }

C#

 int getArrayValue( int values[], int index ) {
   return values[index];
 }
 

C

 template<typename T>
 T array_index(T array[], size_t index) {
   return array[index];
 }

ColdFusion

<cfset arr = ArrayNew(1)>
<cfset arr[1] = "one">
<cfset arr[2] = "2">
<cfset arr[3] = 3>
<cfset var = arr[1]>

The value of var is "one"

ColdFusion Arrays are NOT zero-based, their index begins at 1

Common Lisp

  (defun array-value (array index)
    (aref array index))

Delphi/Object Pascal/Turbo Pascal/Standard Pascal

Array's in all the flavors of pascal can be of any valid base type, or user defined type ( which are all made up of base types ) and are multi-dimensional. With Delphi dynamic arrays were defined but had been used in pascal since its inseption.

A Static array defintion:

foo : array[1..10] of integer; { The base index is ONE }

The base index can be freely chosen:

foo: array[7 .. 16] of integer; { The base index is 7 }

Indeed, the "1 .. 10" resp. "7 .. 16" are actually types: they are integer subrange types. Arrays can also be indexed by enumeration types or enumeration subrange types:

type
 rainbowcolor = (red, orange, yellow, green, blue, violet);
var
 foo: array[rainbowcolor] of integer;
 bar: array[yellow .. blue] of integer;
 i: integer
begin
 i := foo[red]; { allowed indices are red, orange, yellow, green, blue, violet }
 i := bar[green]; { allowed indices are yellow, green, blue }
end;

A Dynamic Array type in Delphi:

foo : array of integer ; // The base index is ZERO

An "old school" dynamic array in the various flavors of pascal

foo : array[0..0] of integer;  // The base index is ZERO

A dynamic array in Extended Pascal:

type
 intarray(n: integer) = array[1 .. n] of integer; { base index 1 }
var
 foo: ^intarray;
begin
 new(foo, 10); { foo now has index 1 to 10 }
 i := foo[2];
 dispose(foo); { get rid of the array }
end;

In the case of the static array, the compiler generates the code to allocate the required memory to hold 10 integers.

In the Delphi style ---dynamic--- array you must set its length:

SetLength(foo,10);  // this array will no hold 10 integers

In the "old school" style of dynamic arrays, you created a point to the zero length declaration and then allocated memory to it with GetMem

pFoo : ^Foo ;
Foo  : array[0..0] of integer ;

All arrays are accessed the same way regardless of declaration method.

i : integer ;

i := foo[n] ;

where n is the array index who's base is either 1 or 0 depending on how it was declared.

Erlang

Erlang lists are 1-based which means that the index must be within the bounds (1 .. length(List)):

Value = lists:nth(Index, List).

Forth

Forth does not have special syntax for array access. Address arithmetic is used to access contiguous memory.

create array 1 , 2 , 3 , 4 ,
array 2 cells   @ .    \ 3

IDL

 ; this is allowed:
 result = arr(5) 
 ; but this is preferred:
 result = arr[5]

The form with square brackets is preferred as it unambiguously constitutes array access, while the version with round ones can conflict with a function call if there are both a function and an array with the same name arr.

Java

public Object getArrayElem(Object[] array, int pos) {
    return array[pos];
}

JavaScript

var element = array[index];

mIRC

Interpeter: mIRC Script Editor

Library: mArray Snippet

 alias readmyarray { echo -a $array_read(MyArray, 2, 3) }

Perl

Interpreter: Perl 5.8.8

$elem = $array[0];

PHP

$array = array('php', 'has', 'arrays');
// First element 
$elem  = $array[0];

Pop11

lvars ar = {1 two 'three'};
lvars elem;
;;; Access second element and assign to variable elem
ar(2) -> elem;

This example uses the simplest possible array (a vector). Pop11 has more general arrays, but in all cases access follows the same pattern, and look the same as procedure (function) call.

Python

Interpreter: Python 2.5

The item is an element in a list at a given index

 item = aList[index]

or

To use a list like a stack be it FIFO/LIFO

 aList.pop()  # Pop last item in a list
 aList.pop(0) # Pop first item in a list

Note: When using the pop() method, the element is removed from the list.

Ruby

 ary = ['Ruby','rules','big','time']
 #the first element
 element = ary[0]
 #or
 element = ary.first
 # => element = 'Ruby'
 #the last element
 element = ary[-1]
 #or
 element = ary.last
 # => element = 'time'
 #retrieving different values at once
 elements = ary.values_at(0,2,3)
 # => elements = ['Ruby','big','time']
 #select the first element of length 3
 element = ary.find{|el|el.length==3}
 # => element = "big"

Smalltalk

  "Retrieve second element of an array"
  index := 2
  element := anArray at: index

Tcl

All arrays in Tcl are associative. If "key" is the variable that holds the key of the element to be retrieved, then

 set result $array($key)

Toka

This retrieves the value 20 from the second item in the array:

 3 cells is-array table
 ( Populate the array )
 10 0 table put-element
 20 1 table put-element 
 30 2 table put-element
 
 table 1 get-element