Retrieving an Element of an Array

From Rosetta Code
Revision as of 00:34, 20 August 2007 by rosettacode>Bp4Avl

rima 1 hard disk maxtor 80 gb costco com carnielli gymstar letterina ayca yikiliyo risorsa playstation 2 foto peni barzellette michael jackson telefonia 3g earth wind and fire film dvd f secure ramones mp3 scarica generale vasco www melito it testo della canzone stasera la luna case vacanza londra pacman world ps1 trucchi fanny bravo pornostar batterie per auto syndicate of low motorola driver ati x600 pci express storia del quirinale b w asw650 nightrain hp p1200 agriturismo montepulciano zurigo - brindisi found lost grande fratello svezia teppisti dei sogni calandro bdsm pics venus spa stagione invernale per cuba condizionatori classe a senza unita firenze lavorazione alluminio dvd recorder pioneer dvr 433 stampanti ink jet formato a2 canon minidv mvx300 maurizio merli film dvd terra amata ventola hdd infermiere sexy memento dvd puma cat low future dado dodo di magia ingegneri palermo lavoro roadmate 700 punta arabi song tsalikis le tre moschettiere spartiti musicali mina kingston - memoria - 1024 mb benedetto sia l giorno parafrasi sitecom forex broker ricambi yamaha virago 250 janssen, zacharias english latvian vocabulary polignano decoder dreambox 7020 pazza modellismo ferrari hot wheels mercedes sl pagoda malattie reumatiche e sport fiat panda anno 2000 lg c2200 nuove immagini per advance wars ds shokwave biaggio antonaci sommerlove est (provincia del camerun) siti per ragazzi de grenet nuda la sirenetta film dvd hp 5110 il segreto della spada programmi per chat felpe north sails uomo abbigliamento jackie chan collection. vol. 1 milano citta del messico sexy boom silp audio analogue toshiba a80 pompe tv japan giochi onlaine marghe eminem lose yourself vinicius il film rossso torna il conflitto coreano desktop prima comunione citroen zx 1.4i break avantage batteria per moto grazia deledda black sex clips lotteria go home nonno supermen amd 64 athlon fx vdata 512mb h b 430 rex rt 200a sidea nuovi capolavori del cinema italiano modelos argentinas life for rent mary s boy child www scienze com memories of me annunci smart frankys colonne sonore il gladiatore toner tn-7300 incontri a ischia xbox360 vdo dayton navigatore ipasvi ap xio xao www sinudyne it athene lettori inovix acer gps navman sabor e menta b c i nuova mercedes a canon power shot a520 televisione crt 32 the letter senso vasco sorin copilul de aur mama craigdavid la ragazza dalla pelle di corallo r i p shut up kizzuwatna sony dav s300 una vita non basta kit tuning vaio portatile ezzolied dimm ddr400 256mb hi-tech www pornocoppie com nania 9 36 studio progettazione amazom com usb 2 0 pcmcia-card peschiera segreteria libero it gpl riscaldamento alta marea magi roberto dogmas marianos gilda c vidor leatherman micra prenotazione hotel bibione dimm 512 pc133 kvr133x64c2 chiedere una tesi aeron torino letto per bambino jvc gz-mg50 deborah kara unger gay messina bmw nuova 525 letizia lezza foto valeria parini dana am nimic fara tine quik your lates trick donna 50 anni olbia fate animate rex incasso a frigoriferi vipsports stampante 1200 mary nel mio cuore giuseppe verdi. nabucco harman kardon sinto-amplificatori prov. latina martial arts prezioso stanza www tuttomoto it tagli di capelli per donna vecchie nude selphy ds700 accesso universale prefettura cosenza haruka replay di un omicidio impianto vivavoce bologna praga containers bed breakfast germania discoteca la villa gli incredibili bazaar progettazione segreteria telecom libretto asics calzature uomo

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