Retrieving an Element of an Array: Difference between revisions

From Rosetta Code
Content added Content deleted
m (Spelling/grammar/aesthetics, corrected Java, alphabetized)
(blanked page since people can't / don't read)
 
(62 intermediate revisions by 27 users not shown)
Line 1: Line 1:
{{DeprecatedTask}}
{{task}}In this task, the goal is to retrieve an element of an [[array]].


'''Please do not add new code, and merge existing code to the [[Arrays]] task.'''
=={{header|4D}}==
` first element
$elem:=$array{1}


In this task, the goal is to retrieve an element of an [[array]].
=={{header|ActionScript}}==
var arr:Array = new Array(1,2,3);
var myVar:Number = arr[1];
// the value of myVar is: 2

=={{header|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

=={{header|AppleScript}}==
on getArrayValue(array, location)
-- very important -- The list index starts at 1 not 0
return item location in array
end getArrayValue

=={{header|C}}==
int array_index(int array[], int index) {
return array[index];
}

=={{header|C sharp|C#}}==
int getArrayValue( int values[], int index ) {
return values[index];
}

=={{header|C++}}==

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

=={{header|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'''''

=={{header|Common Lisp}}==
(defun array-value (array index)
(aref array index))

=={{header|Delphi}}/{{header|Object Pascal}}/Standard {{header|Pascal}}==

Arrays 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 inception.

A Static array definition:
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.

=={{header|Erlang}}==
{{incorrect|Erlang}}
:''This is a linked list, not an array. An array should be used, perhaps based on an ETS table.''
Erlang lists are 1-based which means that the index must be within the bounds (1 .. length(List)):

Value = lists:nth(Index, List).

Note that lists are implemented as linked-lists, hence this is operation is O(N).

=={{header|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

=={{header|Groovy}}==
Define an array
arr = ['groovy', 'is', 'a', 'great', 'language']

First element
arr[0] // *** 'groovy'

Last element, negative indexes
arr[-1] // *** 'language'

Ranges
arr[-3..-1] // *** ['a', 'great', 'language']

Mix n Match
arr[0..2, -1] // *** ['groovy', 'is', 'a', 'language']

=={{header|Haskell}}==

Arrays can have arbitrary bounds (not restricted to integer values, any instance of ''Ix'' will do):

import Data.Array
example = listArray (2,5) ["This", "is", "an", example"]
result = example ! 4

Here, ''result'' will be equal to "an". It should be noted that in Haskell lists are often used instead of arrays.

=={{header|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 <tt>arr</tt>.

=={{header|J}}==

Arrays are the only way J handles data, so every program that produces a portion of a given array is relevant here. In these few examples emphasis is on the primary verb <code>{</code> ("from").

The natural unit of access in J is the item. (Every non-empty noun may be treated as one or more items.)
NB. Define example one-axis array, in which each item is an atom
]ex1=: 10+ i. 6 NB. ] means display the full array (after =: defines it)
10 11 12 13 14 15
4 { ex1 NB. Single specific item
14
_1 { ex1 NB. Last item, using negative indexing
15
{: ex1 NB. {: is another way to specify the final item
15
0 5 2 { ex1 NB. Multiple specific items
10 15 12
NB. Two-axis array, in which each item is a one-axis array
]ex2=: 4 6 $ 10+i. 24
10 11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27
28 29 30 31 32 33
3 0 { ex2 NB. Item selection is the same as in prior examples
28 29 30 31 32 33
10 11 12 13 14 15
(<3 4) { ex2 NB. Atom selection (index list length equals array shape length)
32
NB. Four-axis array, shaped 5 by 3 by 2 by 2
ex4=: 5 3 2 2 $ i. 60
(<2 1) { ex4 NB. Subarray selection: table at given indexing of top two axes
28 29
30 31

=={{header|Java}}==
Object element = array[index];

=={{header|JavaScript}}==
var element = array[index];

=={{header|LSE64}}==
10 array :array
array 5 [] @ # contents of sixth cell in array

=={{header|MAXScript}}==
item = arr[index]

=={{header|mIRC Scripting Language}}==
'''Interpeter:''' mIRC Script Editor

'''Library:''' [[mArray Snippet]]

[[Category:mArray Snippet]]

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

=={{header|Perl}}==
'''Interpreter:''' [[Perl]] 5.8.8
$elem = $array[0];

=={{header|PHP}}==
$array = array('php', 'has', 'arrays');
// First element
$elem = $array[0];

=={{header|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.

=={{header|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.

=={{header|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"

=={{header|Smalltalk}}==
#($a $b $c) at: 2

=={{header|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)

=={{header|Toka}}==
This retrieves the value 20 from the second item in the array:

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

=={{header|X86 assembly}}==
'''Assembler:''' nasm
mov esi, array_offset
mov ebx, 2
mov eax, [esi+ebx*4]

Latest revision as of 15:06, 29 November 2019

Retrieving an Element of 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.

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