Array length
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
Determine the amount of elements in an array.
As an example use an array holding the strings 'apple' and 'orange'.
- Related task
8th
<lang forth> ["apples", "oranges"] a:len . cr </lang>
- Output:
2
Ada
<lang Ada>with Ada.Text_IO;
procedure Array_Length is
type AC is access String; type Strings is array (Natural range <>) of AC; Arr: Strings := (new String'("orange"), new String'("apple"));
begin
for Str of Arr loop Ada.Text_IO.Put(Integer'Image(Str.all'Length)); end loop; Ada.Text_IO.Put_Line(" Array Size:" & Integer'Image(Arr'Length));
end Array_Length;</lang>
- Output:
6 5 Array Size: 2
ALGOL 68
<lang algol68># UPB returns the upper bound of an array, LWB the lower bound # []STRING fruits = ( "apple", "orange" ); print( ( ( UPB fruits - LWB fruits ) + 1, newline ) ) # prints 2 #</lang>
AntLang
<lang AntLang>array: seq["apple"; "orange"] length[array] /Works as a one liner: length[seq["apple"; "orange"]]</lang>
APL
<lang apl>⍴'apple' 'orange'</lang> Output:
2
Apex
<lang apex>System.debug(new String[] { 'apple', 'banana' }.size()); // Prints 2</lang>
AppleScript
<lang AppleScript> set theList to {"apple", "orange"} count theList -- or length of theList -- or number of items in theList </lang>
- Output:
2
No context or goal is provided for this task – sometimes for example, we may simply want to take the last member of an array, and counting the length to derive an index might well not be the best route.
More generally, we may learn more about AppleScript by defining length() ourselves. There are two basic functional approaches to doing that – we can write a simple recursive definition, or, if we have a higher order fold/reduce function (see Catamorphism) we can derive length() as:
fold (λx n -> 1 + n) 0
<lang AppleScript>on run
set xs to ["alpha", "beta", "gamma", "delta", "epsilon", ¬ "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu"] {_length(xs), fold(xs, succ, 0), item 12 of xs, item -1 of xs} --> {12, 12, "mu", "mu"}
end run
-- TWO FUNCTIONAL DEFINITIONS OF LENGTH
-- 1. Recursive definition
on _length(xs)
if xs is [] then 0 else 1 + _length(rest of xs) end if
end _length
-- 2. fold (λx n -> 1 + n) 0
on succ(x)
1 + x
end succ
--[a] - > (a - > b) - > b - > [b] on fold(xs, f, startValue)
script mf property lambda : f end script set v to startValue repeat with x in xs set v to mf's lambda(v, x) end repeat
end fold </lang>
- Output:
{12, 12, "mu", "mu"}
AutoHotkey
<lang AutoHotkey>MsgBox % ["apple","orange"].MaxIndex()</lang>
- Output:
2
AutoIt
<lang AutoIt>Opt('MustDeclareVars',1) ; 1 = Variables must be pre-declared.
Local $aArray[2] = ["Apple", "Orange"] Local $Max = UBound($aArray) ConsoleWrite("Elements in array: " & $Max & @CRLF)
For $i = 0 To $Max - 1 ConsoleWrite("aArray[" & $i & "] = '" & $aArray[$i] & "'" & @CRLF) Next </lang>
- Output:
Elements in array: 2 aArray[0] = 'Apple' aArray[1] = 'Orange'
AWK
The main use of the length()-function is to determine the length of a string.
When used on an array, it returns the number of elements.
Another method to count the elements of the array is by using a variant of for().
<lang awk># usage: awk -f arraylen.awk
function countElements(array) {
for( e in array ) {c++} return c
}
BEGIN {
array[1] = "apple" array[2] = "orange"
print "Array length :", length(array), countElements(array) print "String length:", array[1], length(array[1])
}</lang>
- Output:
Array length : 2 2 String length: apple 5
BASIC
<lang basic>DIM X$(1 TO 2) X$(1) = "apple" X$(2) = "orange" PRINT UBOUND(X$) - LBOUND(X$) + 1</lang>
Brat
<lang brat> p ["apple", "orange"].length </lang>
C
C features two kinds of arrays: static (compile-time, fixed size) and dynamic (allocated at runtime).
The length of a dynamic array cannot be acquired from the array itself - its length must be stored elsewhere.
For static arrays:
<lang c>
- include <stdio.h>
int main() {
const char *fruit[2] = { "apples", "oranges" };
// Acquire the length of the array by dividing the size of all elements (found // with sizeof(fruit)) by the size of the first element.
// Note that since the array elements are pointers to null-terminated character // arrays, the size of the first element is actually the size of the pointer // type - not the length of the string.
// This size, regardless of the type being pointed to, is 8 bytes, 4 bytes, or // 2 bytes on 64-bit, 32-bit, or 16-bit platforms respectively. int length = sizeof(fruit) / sizeof(fruit[0]);
printf("%d\n", length);
return 0;
} </lang>
A C pre-processor macro may be created for ease of use:
<lang c>
- define ARRAY_LENGTH(A) (sizeof(A) / sizeof(A[0]))
</lang>
Note that these arrays become pointers when passed as a parameter to a function. Thus, the length of an array parameter may not be required directly - a dedicated length parameter would be required.
C++
C++ follows the same rules as C regarding static and dynamic arrays.
However, C++ has an additional std::array type (amongst other collections) in its standard library:
<lang cpp>
- include <array>
- include <iostream>
- include <string>
int main() {
std::array<std::string, 2> fruit { "apples", "oranges" }; std::cout << fruit.size(); return 0;
} </lang>
Note that char* or const char* could have been used instead of std::string.
In addition to the std::array type, the C++ standard library also provides dynamically-sized containers to hold arbitrary objects. These all support similar interfaces, though their implementations have different performance characteristics. <lang cpp>
std::vector<std::string> fruitV({ "apples", "oranges" }); std::list<std::string> fruitL({ "apples", "oranges" }); std::deque<std::string> fruitD({ "apples", "oranges" }); std::cout << fruitV.size() << fruitL.size() << fruitD.size() << std::endl;
</lang>
Of these, vector is probably the most widely used.
C#
<lang csharp> using System;
class Program {
public static void Main() { var fruit = new[] { "apple", "orange" }; Console.WriteLine(fruit.Length); }
} </lang>
Note that any of the following array declarations could be used:
<lang csharp> var fruit = new[] { "apple", "orange" }; var fruit = new string[] { "apple", "orange" }; string[] fruit = new[] { "apple", "orange" }; string[] fruit = new string[] { "apple", "orange" }; string[] fruit = { "apple", "orange" }; </lang>
A shorter variant could also have been used:
<lang csharp> using static System.Console;
class Program {
public static void Main() { WriteLine(new[] { "apples", "oranges" }.Length); }
} </lang>
Ceylon
<lang ceylon>shared void run() { value array = ["apple", "orange"]; print(array.size); }</lang>
Clipper/XBase++
<lang Clipper/XBase++>/*
* nizchka: March - 2016 * This is a Clipper/XBase++ of RosettaCode Array_Length */
PROCEDURE MAIN()
LOCAL FRUIT := { "apples","oranges" }
? LEN(FRUIT)
RETURN </lang>
Outputs:
2
nizchka 23:27, 16 March 2016 (UTC)
Clojure
<lang clojure>; using count: (count ["apple" "orange"])
- OR alength if using Java arrays
(alength (into-array ["apple" "orange"]))</lang>
COBOL
Arrays in COBOL are usually referred to as tables. Tables can have fixed or variable (with known maximum) allocations, using a syntax of OCCURS DEPENDING ON. The value of the ODO identifier is the number of active elements in the table.
<lang COBOL> identification division.
program-id. array-length.
environment division. configuration section. repository. function all intrinsic.
data division. working-storage section. 01 table-one. 05 str-field pic x(7) occurs 0 to 5 depending on t1.
77 t1 pic 99.
procedure division. array-length-main. perform initialize-table perform display-table-info goback.
initialize-table. move 1 to t1 move "apples" to str-field(t1)
add 1 to t1 move "oranges" to str-field(t1).
*> add an extra element and then retract table size add 1 to t1 move "bananas" to str-field(t1). subtract 1 from t1 .
display-table-info. display "Elements: " t1 ", using " length(table-one) " bytes" display table-one .
end program array-length.</lang>
- Output:
$ cobc -xjd array-length.cob Elements: 02, using 000000014 bytes apples oranges
ColdFusion
<lang coldfusion> <cfset testArray = ["apple","orange"]> <cfoutput>Array Length = #ArrayLen(testArray)#</cfoutput> </lang>
Outputs:
Array Length = 2
Mike Knapp 15:57, 26 May 2016 (UTC)
Common Lisp
<lang Lisp> (print (length #("apple" "orange"))) </lang>
D
<lang d> import std.stdio;
int main() {
auto fruit = ["apple", "orange"]; fruit.length.writeln; return 0;
} </lang>
Or a somewhat shorter... <lang d> import std.stdio;
void main() {
["apple", "orange"].length.writeln;
} </lang>
DWScript
<lang delphi> var a := ['apple', 'orange']; PrintLn(a.Length); </lang>
EchoLisp
<lang scheme> (length '("apple" "orange")) ;; list
→ 2
(vector-length #("apple" "orange")) ;; vector
→ 2
</lang>
Ela
<lang ela>length [1..10]</lang>
Elm
<lang elm> import Array import Html
main : Html.Html main =
["apple", "orange"] |> Array.fromList |> Array.length |> Basics.toString |> Html.text
</lang>
Emacs Lisp
<lang Lisp>(length ["apple" "orange"]) => 2</lang>
length
also accepts a list or a string.
Elena
<lang elena>
- var a := ("apple", "orange").
- var length := a length.
</lang>
Elixir
<lang elixir>iex(1)> length( ["apple", "orange"] ) # List 2 iex(2)> tuple_size( {"apple", "orange"} ) # Tuple 2</lang>
Frink
<lang frink> a = ["apple", "orange"] println[length[a]] </lang>
Forth
The philosophy of Chuck Moore, the creator of Forth was that he did not want to write code for something he may never use. General purpose code was never optimal for him. So Forth has very few pre-fab data structures. His solution was to distill his language into a large set of very simple routines that control the hardware directly. This is a cardinal error by conventional thinking but Forth makes it simple and the freedom is eye-opening.
By separating the return stack from the parameter stack Forth allows seamless concatenation of these simple routines into higher level functions. The stack management sounds tricky, but in fact, factoring allows you to manage only 2 or 3 parameters per function.
So this demonstration to show ARRAY Length must build "arrays" from scratch. In Forth, like in Assembler, you can do this any way you want. This demonstration adds new words to Forth that make a syntax to create simple variable length string arrays. Each string is a counted string with no trailing zero.
In this example we are configuring memory directly. There are no "pointers". They are just addresses in memory. The code is heavily commented to explain what is going on for those unfamiliar with Forth.
<lang>: STRING, ( addr len -- ) \ allocate space & compile string into memory
here over 1+ allot place ;
- ," ( -- ) [CHAR] " PARSE STRING, ; \ Parse input to " and compile to memory
\ array delimiter words
- [[ 0 c, ; \ compile 0 as char into memory for start of array
- ]] [[ ; \ same, but for end of array
\ list operator words
- nth ( n list-addr -- addr) \ returns address of the Nth item in the array
swap 0 do count + loop ;
- items ( list-addr -- n ) \ returns the number of strings in the array
0 \ create an accumulator on the stack begin 1+ 2dup swap nth C@ \ inc. counter, fetch length byte of each item 0= until \ loop until we hit a zero length (end of list) nip \ remove 2nd item from stack (list-addr) leaving the accumulator 1- ; \ decrement the accumulator
\ use our new string array words to create some lists
create q ," Apples" ," Oranges"
create w ," This" ," has" ," more" ," items" ," in the array" </lang>
Test code at Forth console
Q items . 2 ok W items . 5 ok
Fortran
Early fortrans offered no protocol for ascertaining the length (or dimensionality) of arrays, though the compiler has this information. Thus a statement such as PRINT A
would print all the elements of a variable A
according to its definition. A subprogram that received a parameter would have no access to these details, so its parameter might be declared as A(12345)
simply to signify that it was an array (rather than an ordinary variable) and the programmer would rely on other data to know the upper bound to employ, for instance via an additional parameter. Any mistakes would cause crashes! On the other hand, with heavy computational tasks, it was common to take advantage of the opportunities. Thus, a subprogram might regard its array parameter as one-dimensional even though the actual parameter was not. Carefully-programmed routines might thusly process a sequence of elements via 1-D indexing, far faster than the 2-D or higher order indexing of the original. Success at this game required understanding how array elements were arranged in multidimensional arrays.
Later fortrans allowed A(*)
to signify an array parameter of unstated upper bound, but there was still a problem with higher dimensions. All but the last dimension has to be stated correctly if a multi-dimensional array parameter is to be indexed correctly.
With Fortran 90, a new protocol was introduced, whereby the parameter might be declared as A(:)
signifying an array of one dimension, of bounds unstated. A 2-D array would have A(:,:)
and so on. Further, arrays could have arbitrary lower bounds as well, as in A(-7:12)
but if no colon appeared for a dimension, the lower bound would be assumed to be one so A(2)
means an array of two elements, as before. And as before, a bound could be explicitly stated, perhaps via an explicit parameter such as N
, but now with the : scheme, the compiler is passing secret additional parameters to the subprogram giving the bounds of the array, and these can be accessed via the library functions LBOUND and UBOUND. For multi-dimensional arrays there are multiple bounds, and an invocation might be UBOUND(A,DIM = 2)
but in the example only a one-dimensional array is involved. These facilities are available only if the new MODULE protocol is employed.
The task is in terms of an array holding the texts "Apple" and "Orange", so a CHARACTER*6 element size will do; the subprogram receives yet another secret parameter specifying the size of CHARACTER parameters. This size can be accessed via the LEN function, and, since in principle the index span is arbitrary, no constant index is sure to be a valid index of some single element: thus the LBOUND function is used to finger one that is.
For a simple example, the WRITE(6,*) suffices: write to standard output (the 6), in free-format (the *).
<lang Fortran>
MODULE EXAMPLE CONTAINS SUBROUTINE ABOUND(A) CHARACTER*(*) A(:) !One dimensional array, unspecified bounds. WRITE (6,*) "Lower bound",LBOUND(A),", Upper bound",UBOUND(A) WRITE (6,*) "Element size",LEN(A(LBOUND(A))) WRITE (6,*) A END SUBROUTINE ABOUND END MODULE EXAMPLE
PROGRAM SHOWBOUNDS USE EXAMPLE CHARACTER*6 ARRAY(-1:1) ARRAY(-1) = "Apple" ARRAY(0) = "Orange" ARRAY(1) = "" CALL ABOUND(ARRAY) WRITE (6,*) "But, when it is at home..." WRITE (6,*) "L. bound",LBOUND(ARRAY),", U. bound",UBOUND(ARRAY) END
</lang>
Output:
Lower bound 1 , Upper bound 3 Element size 6 Apple Orange But, when it is at home... L. bound -1 , U. bound 1
Notice that the subprogram sees the array as an old-style array starting with index one!
FurryScript
<lang furryscript>THE_LIST( <apple> <orange> ) COUNT[ 0 SW ~| COUNT_STEP# 0 SW SU ] COUNT_STEP[ DR 1 SU ]
`THE_LIST COUNT# +<></lang>
F#
<lang fsharp>[|1;2;3|].Length |> printfn "%i"</lang> Or: <lang fsharp>[|1;2;3|] |> Array.length |> printfn "%i"</lang>
Futhark
The shape
builtin returns the shape of an array as an array of integers. The length is element 0 of the shape:
<lang Futhark> fun length(as: []int): int = (shape as)[0] </lang>
Go
<lang Go>package main
import "fmt"
func main() { arr := [...]string{"apple", "orange", "pear"}
fmt.Printf("Length of %v is %v.\n", arr, len(arr)) }</lang>
Groovy
<lang Groovy> def fruits = ['apple','orange'] println fruits.size() </lang>
FutureBasic
<lang futurebasic> include "ConsoleWindow"
dim as CFArrayRef array dim as Str255 s dim as CFStringRef fruits, tempStr dim as CFIndex ubound, i
fruits = @"apples,bananas,cherries,dates,grapes,lemon,lime,orange,peach,pear,pineapple,strawberries,watermelon" array = fn CFStringCreateArrayBySeparatingStrings( _kCFAllocatorDefault, fruits, @"," )
ubound = fn CFArrayGetCount( array ) for i = 0 to ubound - 1
tempStr = fn CFArrayGetValueAtIndex( array, i ) fn CFStringGetPascalString( tempStr, @s, 256, _kCFStringEncodingMacRoman ) CFRelease( tempStr ) print "Fruit"; i; " = "; s
next </lang> Output:
Fruit 0 = apples Fruit 1 = bananas Fruit 2 = cherries Fruit 3 = dates Fruit 4 = grapes Fruit 5 = lemon Fruit 6 = lime Fruit 7 = orange Fruit 8 = peach Fruit 9 = pear Fruit 10 = pineapple Fruit 11 = strawberries Fruit 12 = watermelon
Haskell
<lang Haskell>-- Char -> Int length ["apple", "orange"]</lang>
I
In I, strings need to be hashed in order to be stored in an array. <lang i>software { var a = ["apple"#255, "orange"#255] print(len(a)) }</lang>
Idris
<lang Idris>length ["apple", "orange"]</lang>
J
Tally (#
) returns the length of the leading dimension of an array (or 1 if the array has no dimensions). Shape Of ($
) returns the length of each dimension of an array.
<lang j> # 'apple';'orange'
2
$ 'apple';'orange'
2</lang> For the list array example given, the result appears to be the same. The difference is that the result of Tally is a scalar (array of 0 dimensions) whereas the result of Shape Of is a list (1 dimensional array), of length 1 in this case. <lang j> $#'apple';'orange'
$$'apple';'orange'
1</lang> This might be a clearer concept with a few more examples. Here's an array with two dimensions: <lang j> >'apple';'orange' apple orange
$>'apple';'orange'
2 6
#>'apple';'orange'
2</lang> And, here's an array with no dimensions: <lang> 9001 9001
#9001
1
$9001
</lang>
You can count the number of dimensions of an array (the length of the list of lengths) using #$array
:
<lang j>
#$9001
0
#$'apple';'orange'
1
#$>'apple';'orange'
2</lang>
Java
<lang java>public class ArrayLength {
public static void main(String[] args) { System.out.println(new String[]{"apple", "orange"}.length); }
}</lang>
JavaScript
<lang javascript>console.log(['apple', 'orange'].length);</lang>
However, determining the length of a list, array, or collection may simply be the wrong thing to do.
If, for example, the actual task (undefined here, unfortunately) requires retrieving the final item, while it is perfectly possible to write last in terms of length
<lang JavaScript>function last(lst) {
return lst[lst.length - 1];
}</lang>
using length has the disadvantage that it leaves last simply undefined for an empty list.
We might do better to drop the narrow focus on length, and instead use a fold (reduce, in JS terms) which can return a default value of some kind.
<lang JavaScript>function last(lst) {
return lst.reduce(function (a, x) { return x; }, null);
}</lang>
Alternatively, rather than scanning the entire list to simply get the final value, it might sometimes be better to test the length:
<lang JavaScript>function last(list, defaultValue) {
return list.length ?list[list.length-1] :defaultValue;
}</lang>
Or use other built-in functions – this, for example, seems fairly clear, and is already 100+ times faster than unoptimised tail recursion in ES5 (testing with a list of 1000 elements):
<lang JavaScript>function last(list, defaultValue) {
return list.slice(-1)[0] || defaultValue;
}</lang>
jq
<lang jq>["apple","orange"] | length</lang> Output: <lang sh>2</lang>
Note that the length filter is polymorphic, so for example the empty string (""), the empty list ([]), and null all have length 0.
Julia
<lang Julia> a = ["apple","orange"] length(a) </lang>
Kotlin
<lang Kotlin> fun main(args: Array<String>) {
println(arrayOf("apple", "orange").size)
} </lang>
Liberty BASIC
When a one or two dimensional array, A$, with subscript(s) of 10 or less is referenced (either by assigning or reading), the compiler does an implicit DIM A$(10) or DIM A$(10,10). Before referencing an array with any subscript numbered higher than 10, or arrays of three dimensions or more, the programmer must first issue an explicit DIM statement.
There is no function in Liberty Basic to directly read the size of an array. This program uses error trapping loops to, first, determine the number of dimensions of the array. Then, second, again uses error trapping loops to determine the number of elements in each dimension. Finally, it prints the DIM statement that was used to define the array.
I suppose the implicit DIM feature makes it a bit quicker to write short, simple programs. One or two dimension arrays may be resized with REDIM. Three dimension or more arrays can not be resized. All arrays may be cleared with REDIM. Keep in mind that A$(n) and A$(n,m) are the same array. You must refer to it with the correct arguments or get an error.
NOTE -- This program runs only under LB Booster version 3.05 or higher because of arrays with more than two dimensions, passed array names to functions and subroutines as a parameter, and structured error trapping syntax. Get the LBB compiler here: http://lbbooster.com/
<lang lb> FruitList$(0)="apple" 'assign 2 cells of a list array FruitList$(1)="orange" dimension=dimension(FruitList$()) 'first get the dimension of the array if dimension>3 then
print "Sorry, program only written for array dimensions of 3 or less." end
end if call elements FruitList$(), dimension 'next get the size of each dimension end
function dimension(array$())
for dimension=1 to 4 select case dimension case 1 try: x$=array$(0) catch: goto [TryNext] end try exit for case 2 try: x$=array$(0,0) catch: goto [TryNext] end try exit for case 3 try: x$=array$(0,0,0) catch: goto [TryNext] end try exit for case 4 exit for end select [TryNext] next dimension if dimension<4 then print "array dimension = "; dimension ArraySize(0)=dimension
end function
sub elements array$(), dimension
select case dimension case 1 try do x$=array$(a) a+=1 loop catch: elements=a end try ArraySize(1)=elements-1 print "dimension 1 has "; elements; " elements (cells), "_ "numbered 0 to "; ArraySize(1) case 2 try do x$=array$(a,0) a+=1 loop catch: elements=a end try ArraySize(1)=elements-1 print "dimension 1 has "; elements; " elements (cells), "_ "numbered 0 to "; ArraySize(1) elements=0 try do x$=array$(0,b) b+=1 loop catch: elements=b end try ArraySize(2)=elements-1 print "dimension 2 has "; elements; " elements (cells), "_ "numbered 0 to "; ArraySize(2) case 3 try do x$=array$(a,0,0) a+=1 loop catch: elements=a end try ArraySize(1)=elements-1 print "dimension 1 has "; elements; " elements (cells), "_ "numbered 0 to "; ArraySize(1) elements=0 try do x$=array$(0,b,0) b+=1 loop catch: elements=b end try ArraySize(2)=elements-1 print "dimension 2 has "; elements; " elements (cells), "_ "numbered 0 to "; ArraySize(2) elements=0 try do x$=array$(0,0,c) c+=1 loop catch: elements=c end try ArraySize(3)=elements-1 print "dimension 3 has "; elements; " elements (cells), "_ "numbered 0 to "; ArraySize(3) end select 'print the explicit or implied DIMension statement for this array print "DIM array$("; a-1; if b>0 then print ","; b-1; if c>0 then print ","; c-1; print ")"
end sub </lang>
- Output:
array dimension = 1 dimension 1 has 11 elements (cells), numbered 0 to 10 DIM array$(10)
Little
<lang C>string fruit[] = {"apples", "oranges"}; puts(length(fruit));</lang>
LiveCode
<lang LiveCode>put "apple","orange" into fruit split fruit using comma answer the number of elements of fruit</lang>
Lua
<lang Lua> -- For tables as simple arrays, use the # operator: fruits = {"apple", "orange"} print(#fruits)
-- Note the # symbol does not work for non-integer-indexed tables: fruits = {fruit1 = "apple", fruit2 = "orange"} print(#fruits)
-- For this you can use this short function: function size (tab) local count = 0 for k, v in pairs(tab) do count = count + 1 end return count end
print(size(fruits)) </lang>
- Output:
2 0 2
Maple
<lang maple>a := Array(["apple", "orange"]); numelems(a);</lang>
- Output:
a := [ "apple" "orange" ] 2
Mathematica
<lang Mathematica>Length[{"apple", "orange"}]</lang>
MATLAB / Octave
<lang Matlab>length({'apple', 'orange'})</lang> For arrays with more than one dimension, length reports the length of the larges dimension. The number of elements in a multi-dimensional array can be obtained with numel. <lang Matlab>numel({'apple', 'orange'; 'pear', 'banana'})</lang>
Neko
<lang neko>var fruit = $array("apple", "orange");
$print($asize(fruit));</lang>
NGS
<lang NGS>echo(len(['apple', 'orange']))
- same
echo(['apple', 'orange'].len())</lang>
Nim
<lang nim> let fruit = ["apple", "orange"] echo "The length of the fruit array is ", len(fruit) </lang>
- Output:
The length of the fruit array is 2
Oberon-2
<lang oberon2> MODULE ArrayLength; IMPORT
Strings, Out;
TYPE
String = POINTER TO ARRAY OF CHAR;
VAR
a: ARRAY 16 OF String;
PROCEDURE NewString(s: ARRAY OF CHAR): String; VAR
str: String;
BEGIN
NEW(str,Strings.Length(s) + 1);COPY(s,str^); RETURN str
END NewString;
PROCEDURE Length(a: ARRAY OF String): LONGINT; VAR
i: LONGINT;
BEGIN
i := 0; WHILE (a[i] # NIL) DO INC(i) END; RETURN i;
END Length;
BEGIN
a[0] := NewString("apple"); a[1] := NewString("orange"); Out.String("length: ");Out.Int(Length(a),0);Out.Ln
END ArrayLength. </lang>
- Output:
length: 2
Objeck
<lang objeck> class Test {
function : Main(args : String[]) ~ Nil { fruit := ["apples", "oranges"]; fruit->Size()->PrintLine(); }
}</lang>
OCaml
<lang OCaml> Array.length [|"apple"; "orange"|];; </lang>
Oforth
<lang Oforth>[ "apple", "orange" ] size</lang>
Onyx
<lang onyx>[`apple' `orange'] length # leaves 2 on top of the stack</lang>
ooRexx
<lang oorexx> /* REXX */ a = .array~of('apple','orange') say a~size 'elements' Do e over a
say e End
Say "a[2]="a[2]</lang>
- Output:
2 elements apple orange a[2]=orange
PARI/GP
<lang parigp>array = ["apple", "orange"] length(array) \\ == 2
- array \\ == 2</lang>
The #
syntax is a handy shorthand. It usually looks best just on variables but it works on expressions too, possibly with parens to control precedence.
Both forms work on column vectors too, and also on strings and matrices. (For a matrix it is the number of columns.)
Pascal
<lang Pascal>
- !/usr/bin/instantfpc
//program ArrayLength;
{$mode objfpc}{$H+}
uses SysUtils, Classes;
const
Fruits : array[0..1] of String = ('apple', 'orange');
begin
WriteLn('Length of Fruits by function : ', Length(Fruits)); WriteLn('Length of Fruits by bounds : ', High(Fruits) - Low(Fruits) + 1);
END. </lang>
- Output:
./ArrayLength.pas Length of Fruits by function : 2 Length of Fruits by bounds : 2
Perl
The way to get the number of elements of an array in Perl is to put the array in scalar context.
<lang perl>my @array = qw "apple orange banana", 4, 42;
scalar @array; # 5 0 + @arrray; # 5 . @array; # "5" my $elems = @array; # $elems = 5
scalar @{ [1,2,3] }; # [1,2,3] is a reference which is already a scalar
my $array_ref = \@array; # a reference scalar @$array_ref;
- using subroutine prototypes, not generally recommended
- and not usually what you think they are
sub takes_a_scalar ($) { my ($a) = @_; return $a }
takes_a_scalar @array;
- the built-ins can also act like they have prototypes</lang>
A common mistake is to use length
which works on strings not arrays.
So using it on an array, as a side-effect, actually gives you a number which represents the order of magnitude.
<lang perl6>length . @array; # 1 length @array; # 1
print '0.', scalar @array, 'e', length @array, "\n"; # 0.5e1
@array = 1..123; print '0.', scalar @array, 'e', length @array, "\n"; # 0.123e3
print 'the length of @array is on the order of '; print 10 ** (length( @array )-1); # 100 print " elements long\n";</lang>
Perl 6
To get the number of elements of an array in Perl 6 you put the array in a coercing Numeric context, or call elems
on it.
<lang perl6> my @array = <apple orange banana>;
say @array.elems; # 3 say elems @array; # 3 say +@array; # 3 say @array + 1; # 4 </lang>
Watch out for infinite/lazy arrays though. You can't get the length of those.
<lang perl6>my @infinite = 1 .. Inf; # 1, 2, 3, 4, ...
say @infinite[5000]; # 5001 say @infinite.elems; # Throws exception "Cannot .elems a lazy list" </lang>
Phix
<lang Phix>constant fruits = {"apple","orange"} ?length(fruits)</lang>
- Output:
2
PHP
<lang php>print count(['apple', 'orange']); // Returns 2</lang>
PicoLisp
<lang PicoLisp>: (length '(apple orange)) -> 2
- </lang>
Pike
<lang pike>void main() {
array fruit = ({ "apple", "orange" }); write("%d\n", sizeof(fruit));
}</lang>
- Output:
2
PL/I
<lang pli> p: Proc Options(main);
Dcl a(2) Char(6) Init('apple','orange'); Put Edit('Array a has',(hbound(a)-lbound(a)+1),' elements.') (Skip,a,f(2),a); Put Skip Data(a); End;</lang>
- Output:
Array a has 2 elements. A(1)='apple ' A(2)='orange';
Potion
<lang potion>("apple", "orange") length print</lang>
PowerShell
<lang PowerShell> $Array = @( "Apple", "Orange" ) $Array.Count $Array.Length</lang>
- Output:
2 2
Prolog
<lang Prolog>| ?- length(["apple", "orange"], X).
X = 2
yes</lang>
PureBasic
<lang PureBasic> EnableExplicit Define Dim fruit$(1); defines array with 2 elements at indices 0 and 1 fruit$(0) = "apple" fruit$(1) = "orange" Define length = ArraySize(fruit$()) + 1; including the element at index 0 If OpenConsole()
PrintN("The length of the fruit array is " + length) PrintN("") PrintN("Press any key to close the console") Repeat: Delay(10) : Until Inkey() <> "" CloseConsole()
EndIf </lang>
Python
<lang python>>>> print(len(['apple', 'orange'])) 2 >>> </lang>
R
<lang R> a <- c('apple','orange') # create a vector containing "apple" and "orange" length(a) </lang>
- Output:
[1] 2
Racket
<lang racket>#lang racket/base (length '("apple" "orange")) ;; list (vector-length #("apple" "orange")) ;; vector</lang>
- Output:
2 2
REXX
<lang rexx>/* REXX ----------------------------------------------
- The compond variable a. implements an array
- By convention, a.0 contains the number of elements
- ---------------------------------------------------*/
a.=0 /* initialize the "array" */ call store 'apple' Call store 'orange' Say 'There are' a.0 'elements in the array:' Do i=1 To a.0
Say 'Element' i':' a.i End
Exit store: Procedure Expose a. z=a.0+1 a.z=arg(1) a.0=z Return</lang>
- Output:
There are 2 elements in the array: Element 1: apple Element 2: orange
Ring
<lang ring>See len(['apple', 'orange']) # output = 2 </lang>
Ruby
<lang ruby>puts ['apple', 'orange'].length # or .size</lang>
Rust
By default arrays are immutable in rust.
<lang rust> fn main() {
let array = ["foo", "bar", "baz", "biff"]; println!("the array has {} elements", array.len());
} </lang>
Scala
<lang scala> println(Array("apple", "orange").length) </lang>
SETL
<lang haskell> arr := ["apple", "orange"]; print(# arr); -- '#' is the cardinality operator. Works on strings, tuples, and sets. </lang>
Sidef
<lang ruby>var arr = ['apple', 'orange']; say arr.len; #=> 2 say arr.end; #=> 1 (zero based)</lang>
Smalltalk
<lang smalltalk> a := #('apple' 'orange'). a size</lang>
SNOBOL4
<lang SNOBOL4> ar = ARRAY('2,2')
ar<1,1> = 'apple' ar<1,2> = 'first' ar<2,1> = 'orange' ar<2,2> = 'second' OUTPUT = IDENT(DATATYPE(ar), 'ARRAY') PROTOTYPE(ar)
end</lang>
- Output:
2,2
SQL
<lang sql>SELECT COUNT() FROM (VALUES ('apple'),('orange'));</lang>
Standard ML
<lang sml>let
val a = Array.fromList ["apple", "orange"]
in
Array.length a
end;</lang>
Swift
<lang Swift>import Cocoa //include Cocoa library (standard in OS X)
let fruits = ["apple", "orange"] //declare constant array literal let fruitsCount = fruits.count //declare constant array length (count)
print(fruitsCount) //print array length to output window</lang>
- Output:
2
Tcl
<lang tcl>;# not recommanded: set mylistA {apple orange} ;# actually a string set mylistA "Apple Orange" ;# same - this works only for simple cases
set lenA [llength $mylistA] puts "$mylistA : $lenA"
- better: to build a list, use 'list' and/or 'lappend':
set mylistB [list apple orange "red wine" {green frog}] lappend mylistB "blue bird"
set lenB [llength $mylistB] puts "$mylistB : $lenB" </lang>
- Output:
Apple Orange : 2 apple orange {red wine} {green frog} {blue bird} : 5
TI-83 BASIC
Use function dim()
.
<lang ti83b>{1,3,–5,4,–2,–1}→L1
dim(L1)</lang>
- Output:
6
Ursa
> decl string<> stream > append "two" "strings" stream > out (size stream) endl console 2 > out (size "test string") endl console 11 >
VBA
<lang vb>Debug.Print "Array Length: " & UBound(Array("apple", "orange")) + 1</lang>
- Output:
Array Length: 2
VBScript
<lang vb>arr = Array("apple","orange") WScript.StdOut.WriteLine UBound(arr) + 1</lang>
- Output:
2
Wren
<lang wren>var arr = [1,2,3] var length = arr.count </lang>
XLISP
<lang lisp>(vector-length #("apple" "orange"))</lang>
zkl
zkl doesn't support arrays natively, use lists instead. <lang zkl>List("apple", "orange").len().println() //-->2, == L("apple", "orange") T("apple", "orange").len().println() //-->2, read only list (ROList) </lang>
- Programming Tasks
- Solutions by Programming Task
- Simple
- 8th
- Ada
- ALGOL 68
- AntLang
- APL
- Apex
- AppleScript
- AutoHotkey
- AutoIt
- AWK
- BASIC
- Brat
- C
- C++
- C sharp
- Ceylon
- Clipper/XBase++
- Clojure
- COBOL
- ColdFusion
- Common Lisp
- D
- DWScript
- EchoLisp
- Ela
- Elm
- Emacs Lisp
- Elena
- Elixir
- Frink
- Forth
- Fortran
- FurryScript
- F Sharp
- Futhark
- Go
- Groovy
- FutureBasic
- Haskell
- I
- Idris
- J
- Java
- JavaScript
- Jq
- Julia
- Kotlin
- Liberty BASIC
- Little
- LiveCode
- Lua
- Maple
- Mathematica
- MATLAB
- Octave
- Neko
- NGS
- Nim
- Oberon-2
- Objeck
- OCaml
- Oforth
- Onyx
- OoRexx
- PARI/GP
- Pascal
- Perl
- Perl 6
- Phix
- PHP
- PicoLisp
- Pike
- PL/I
- Potion
- PowerShell
- Prolog
- PureBasic
- Python
- R
- Racket
- REXX
- Ring
- Ruby
- Rust
- Scala
- SETL
- Sidef
- Smalltalk
- SNOBOL4
- SQL
- Standard ML
- Swift
- Tcl
- TI-83 BASIC
- Ursa
- VBA
- VBScript
- Wren
- XLISP
- Zkl