Array length: Difference between revisions

→‎Forth: use forth highlighting
(→‎Forth: use forth highlighting)
(41 intermediate revisions by 30 users not shown)
Line 1:
{{task}}
[[Category:Simple]]
{{task}}
 
;Task:
Line 13:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">print([‘apple’, ‘orange’].len)</langsyntaxhighlight>
{{out}}
<pre>
Line 21:
=={{header|360 Assembly}}==
Array length is computed at compilation time with the formula : (AEND-A)/L'A
<langsyntaxhighlight lang="360asm">* Array length 22/02/2017
ARRAYLEN START
USING ARRAYLEN,12
Line 32:
AEND DC 0C
PG DC CL25'Array length=' buffer
END ARRAYLEN</langsyntaxhighlight>
{{out}}
<pre>
Line 40:
{{trans|360 Assembly}}
Array length is computed at compilation time with the formula: (Array_End-Array). Even though the labels Array and Array_End are both 16-bit values, if their difference fits into 8 bits the assembler will allow you to load it into a register.
<langsyntaxhighlight lang="6502asm">start:
LDA #(Array_End-Array) ;evaluates to 13
RTS
Line 47:
byte "apple",0
byte "orange",0
Array_End:</langsyntaxhighlight>
 
=={{header|68000 Assembly}}==
Array length is computed at compilation time with the formula: (Array_End-Array). The "bit width" of this value is the bit width of the result, not the bit width of the inputs. In other words, even though code labels are 32-bit memory addresses, if their difference is 8 or 16-bit you can use a <code>.B</code> or <code>.W</code> instruction or directive on them without a compile-time error.
{{trans|360 Assembly}}
 
Array length is computed at compilation time with the formula: (Array_End-Array). Even though the labels Array and Array_End are both 32-bit memory addresses, if their difference is small enough it can fit into a 16-bit or even an 8-bit instruction operand.
The biggest limitation to the (Array_End-Array) method is that it always measures in total bytes. So if your array elements are of a different type you'll have to adjust accordingly. For an array strings, you should instead construct an array of pointers to strings and divide the result of the difference by 4 to get the total number of "strings" in the array.
<lang 68000devpac>start:
 
MOVE.B #(Array_End-Array) ;evaluates to 14
 
<syntaxhighlight lang="68000devpac">start:
MOVE.B #(MyArray_End-MyArray)/4 ;evaluates to 2
RTS
 
Apple:
Array:
DC.B "apple",0
even
Orange:
DC.B "orange",0
even
 
Array_End:</lang>
MyArray:
DC.L Apple
DC.L Orange
MyArray_End:</syntaxhighlight>
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
["apples", "oranges"] a:len . cr
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 74 ⟶ 82:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program lenAreaString64.s */
Line 139 ⟶ 147:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
 
=={{header|ABAP}}==
The concept of arrays does not exist in ABAP, instead internal tables are used. Since ABAP Version 7.40 they can be accessed with the common index notation. Note that the index starts at 1 and out of bound access raises an exception. The built-in function "lines" returns the number of records.
 
<syntaxhighlight lang="abap">
<lang ABAP>
report z_array_length.
 
Line 150 ⟶ 158:
 
write: internal_table[ 1 ] , internal_table[ 2 ] , lines( internal_table ).
</syntaxhighlight>
</lang>
 
{{out}}
Line 159 ⟶ 167:
=={{header|Ada}}==
 
<syntaxhighlight lang="ada">
<lang Ada>with Ada.Text_IO; use Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with System;
 
procedure Array_Length is
 
Fruits : constant array (Positive range <>) of access constant String
:= (new String'("orange"),
new String'("apple"));
 
Memory_Size : constant Integer := Fruits'Size / System.Storage_Unit;
 
begin
Put_Line ("Number of elements : " & Fruits'Length'Image);
for Fruit of Fruits loop
Put_Line ("Array memory Size : " & Memory_Size'Image & " bytes" );
Ada.Text_IO.Put (Integer'Image (Fruit'Length));
Put_Line (" " & Integer'Image (Memory_Size * System.Storage_Unit / System.Word_Size) & " words" );
end loop;
end Array_Length;</syntaxhighlight>
 
Ada.Text_IO.Put_Line (" Array Size : " & Integer'Image (Fruits'Length));
end Array_Length;</lang>
 
{{out}}
<pre>
<pre> 6 5 Array Size: 2</pre>
Number of elements : 2
Array memory Size : 32 bytes
4 words
</pre>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight 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 #</langsyntaxhighlight>
 
=={{header|AntLang}}==
<langsyntaxhighlight AntLanglang="antlang">array: seq["apple"; "orange"]
length[array]
/Works as a one liner: length[seq["apple"; "orange"]]</langsyntaxhighlight>
 
=={{header|Apex}}==
<langsyntaxhighlight lang="apex">System.debug(new String[] { 'apple', 'banana' }.size()); // Prints 2</langsyntaxhighlight>
 
=={{header|APL}}==
<syntaxhighlight lang ="apl">⍴'apple' 'orange'</langsyntaxhighlight>
Output:
<pre>2</pre>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">
<lang AppleScript>
set theList to {"apple", "orange"}
count theList
Line 203 ⟶ 218:
-- or
number of items in theList
</syntaxhighlight>
</lang>
''Strictly speaking, 'items in' can be omitted from the last example, since 'number of' does essentially the same as 'length of'. The additional stage of extracting theList's 'items' is inefficient.''
{{out}}
Line 214 ⟶ 229:
<pre>fold (λx n -> 1 + n) 0</pre>
 
<langsyntaxhighlight AppleScriptlang="applescript">on run
set xs to ["alpha", "beta", "gamma", "delta", "epsilon", ¬
Line 255 ⟶ 270:
end repeat
end fold
</syntaxhighlight>
</lang>
 
{{Out}}
Line 263 ⟶ 278:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program lenAreaString.s */
Line 399 ⟶ 414:
.Ls_magic_number_10: .word 0x66666667
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">fruit: ["apple" "orange"]
 
print ["array length =" size fruit]</langsyntaxhighlight>
{{out}}
Line 412 ⟶ 427:
 
=={{header|ATS}}==
<syntaxhighlight lang="ats">
<lang ATS>
#include
"share/atspre_staload.hats"
Line 425 ⟶ 440:
 
implement main0((*void*)) = ((*void*))
</syntaxhighlight>
</lang>
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % ["apple","orange"].MaxIndex()</langsyntaxhighlight>
{{Out}}<pre>2</pre>
 
=={{header|AutoIt}}==
<langsyntaxhighlight AutoItlang="autoit">Opt('MustDeclareVars',1) ; 1 = Variables must be pre-declared.
 
Local $aArray[2] = ["Apple", "Orange"]
Line 441 ⟶ 456:
ConsoleWrite("aArray[" & $i & "] = '" & $aArray[$i] & "'" & @CRLF)
Next
</syntaxhighlight>
</lang>
{{Out}}
<pre>Elements in array: 2
Line 451 ⟶ 466:
Using Avail's tuples and the `|_|` method:
 
<langsyntaxhighlight Availlang="avail">|<"Apple", "Orange">|</langsyntaxhighlight>
 
=={{header|AWK}}==
Line 460 ⟶ 475:
Another method to count the elements of the array is by using a variant of for().
 
<langsyntaxhighlight lang="awk"># usage: awk -f arraylen.awk
#
function countElements(array) {
Line 474 ⟶ 489:
print "String length:", array[1], length(array[1])
}</langsyntaxhighlight>
 
{{out}}
Line 484 ⟶ 499:
=={{header|BaCon}}==
BaCon knows three types of arrays, the UBOUND function can query all.
<langsyntaxhighlight lang="bacon">' Static arrays
 
DECLARE fruit$[] = { "apple", "orange" }
Line 501 ⟶ 516:
meat$("first") = "chicken"
meat$("second") = "pork"
PRINT UBOUND(meat$)</langsyntaxhighlight>
 
=={{header|Bash}}==
 
<langsyntaxhighlight lang="bash">
fruit=("apple" "orange" "lemon")
echo "${#fruit[@]}"</langsyntaxhighlight>
 
=={{header|BASIC}}==
<langsyntaxhighlight lang="basic">DIM X$(1 TO 2)
X$(1) = "apple"
X$(2) = "orange"
PRINT UBOUND(X$) - LBOUND(X$) + 1</langsyntaxhighlight>
 
==={{header|Applesoft BASIC}}===
<langsyntaxhighlight lang="basic">10 DIM A$(2)
20 A$(1) = "ORANGE"
30 A$(2) = "APPLE"
Line 549 ⟶ 564:
170 L$ = L$ + STR$ ( FN P(I))
180 L$ = L$ + " ": NEXT I
190 RETURN</langsyntaxhighlight>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">
<lang BASIC256>
fruta$ = {"apple", "orange", "pear"}
Line 559 ⟶ 574:
print fruta$[1]
end
</syntaxhighlight>
</lang>
<pre>
3
Line 565 ⟶ 580:
orange
</pre>
 
==={{header|Chipmunk Basic}}===
{{works with|Chipmunk Basic|3.6.4}}
Unless modified with OPTION BASE 1 or MAT ORIGIN 1, the lower limit of an array is 1.
<syntaxhighlight lang="qbasic">10 dim fruta$(2)
20 read fruta$(0),fruta$(1),fruta$(2)
30 data "apple","orange","lemon"
40 print "The length of the array 'fruit$' is ";ubound(fruta$)+1
50 end</syntaxhighlight>
 
==={{header|Commodore BASIC}}===
Commodore BASIC has no way within the language to query an array for its length, but you can dive into the implementation to get that information. On a C-64 in particular, this works:
{{works with|Commodore BASIC|2.0 on C-64}}
<langsyntaxhighlight lang="basic">10 DIM A$(1):REM 1=LAST -> ROOM FOR 2
20 A$(0) = "ORANGE"
30 A$(1) = "APPLE"
Line 579 ⟶ 603:
90 IF T=128 THEN N$=N$+"$": REM STRING
100 L=PEEK(AT+6): REM FIRST INDEX SIZE
110 PRINT N$" HAS"L"ELEMENTS."</langsyntaxhighlight>
 
{{Out}}
<pre>A$ HAS 2 ELEMENTS.</pre>
 
==={{header|IS-BASIC}}===
<syntaxhighlight lang="is-basic">100 STRING X$(1 TO 2)
110 LET X$(1)="apple":LET X$(2)="orange"
120 PRINT "The length of the array 'X$' is";SIZE(X$)</syntaxhighlight>
 
==={{header|True BASIC}}===
<langsyntaxhighlight lang="qbasic">DIM fruta$(2)
DIM fruta$(2)
READ fruta$(1), fruta$(2)
DATA "apple", "orange"
Line 593 ⟶ 621:
 
PRINT "La longitud del array fruta$ es" ; tamano
END</syntaxhighlight>
END
</lang>
 
{{out}}
<pre> La longitud del array fruta$ es 2 </pre>
Line 602 ⟶ 628:
True BASIC's arrays are not fixed in length and, although True BASIC is a compiled-language, the number of elements can be changed during runtime using such functions as the MAT REDIM (matrix re-dimension) function. Although the starting index of 1 is in implicit, it can be changed by setting the lower and upper bounds (eg. fruit(0 to 3)) when declaring the array. Also, the example below uses the MAT READ function to read in the data elements into the array without having to explicitly list each variable-array index. The example also uses the SIZE function vs the bounds method to determine the length of the array. Finally, in this example the SIZE function was not assigned to a separate variable and instead is used within the PRINT function itself.
 
<syntaxhighlight lang="qbasic">DIM fruit$(2)
<lang qbasic>
DIM fruit$(2)
MAT READ fruit$
DATA "apple", "orange"
 
PRINT "The length of the array 'fruit$' is "; SIZE(fruit$)
END</syntaxhighlight>
END
{{out}}
</lang>
<pre> The length of the array 'fruit$' is 2 </pre>
 
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="qbasic">PROGRAM "Array length"
VERSION "0.0000"
 
DECLARE FUNCTION Entry ()
 
FUNCTION Entry ()
DIM F$[2]
F$[0] = "apple"
F$[1] = "orange"
F$[2] = "pear"
 
PRINT "The length of the fruit array is "; UBOUND(F$[])
PRINT F$[1]
END FUNCTION
END PROGRAM</syntaxhighlight>
{{out}}
<pre> The length of the fruit array 'fruit$' is 2 </pre>2
orange</pre>
 
=={{header|Batch File}}==
While batch files don't support arrays in the traditional sense, sets of variables forming somewhat of a pseudo-array are extremely useful. They are usually in the form of <code>%name{number}%</code>. The below code gives an example of how to create an array from a list stored in a variable, and how to acquire the amount of entries in the array.
 
<langsyntaxhighlight lang="dos">
@echo off
 
Line 647 ⟶ 690:
set /a arraylength+=1
goto loop
</syntaxhighlight>
</lang>
{{in}}
<pre>
Line 659 ⟶ 702:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> DIM array$(1)
array$() = "apple", "orange"
PRINT "Number of elements in array = "; DIM(array$(), 1) + 1
PRINT "Number of bytes in all elements combined = "; SUMLEN(array$())
END</langsyntaxhighlight>
{{Out}}
 
<pre>Number of elements in array = 2
Number of bytes in all elements combined = 11</pre>
 
=={{header|Beef}}==
<syntaxhighlight lang="csharp">using System;
 
namespace ArrayLength
{
class Program
{
public static void Main()
{
var array = new String[]("apple", "orange");
Console.WriteLine(array.Count);
delete(array);
}
}
}
</syntaxhighlight>
 
=={{header|Brat}}==
<langsyntaxhighlight lang="brat">
p ["apple", "orange"].length
</syntaxhighlight>
</lang>
 
=={{header|Binary Lambda Calculus}}==
 
BLC has no arrays, so here's a function to compute the length of a given list (as a church numeral) instead, corresponding to https://github.com/tromp/AIT/blob/master/lists/length.lam :
 
<pre>010001101000000101100000000000011100101010111111110111111101111011010000010</pre>
 
=={{header|BQN}}==
 
<code>≠</code> gives the length of an array in BQN.
<langsyntaxhighlight lang="bqn">≠ 1‿"a"‿+</langsyntaxhighlight>
<syntaxhighlight lang ="bqn">3</langsyntaxhighlight>
[https://mlochbaum.github.io/BQN/try.html#code=4omgIDHigL8iYSLigL8r Try It!]
 
Line 689 ⟶ 755:
For static arrays:
 
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
 
Line 711 ⟶ 777:
return 0;
}
</syntaxhighlight>
</lang>
 
A C pre-processor macro may be created for ease of use:
 
<syntaxhighlight lang="c">
<lang c>
#define ARRAY_LENGTH(A) (sizeof(A) / sizeof(A[0]))
</syntaxhighlight>
</lang>
 
Note that these arrays become pointers when passed as a parameter to a function.
Line 736 ⟶ 802:
</p>
====Solution====
<langsyntaxhighlight Clang="c">#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings
#define _CRT_NONSTDC_NO_WARNINGS // enable old-gold POSIX names in MSVS
 
Line 811 ⟶ 877:
 
return EXIT_SUCCESS;
}</langsyntaxhighlight>
{{output}}
<pre>There are 2 elements in an array with a capacity of 10 elements:
Line 819 ⟶ 885:
 
====An example why sizeof(A)/sizeof(E) may be a bad idea in C====
<langsyntaxhighlight Clang="c">#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings
#define _CRT_NONSTDC_NO_WARNINGS // enable old-gold POSIX names in MSVS
 
Line 930 ⟶ 996:
 
return 0;
}</langsyntaxhighlight>
<p>
As we can see the ''sizeof(ArrayType)/sizeof(ElementType)'' approach mostly fail.
Line 997 ⟶ 1,063:
=={{header|C sharp|C#}}==
 
<langsyntaxhighlight lang="csharp">
using System;
 
Line 1,008 ⟶ 1,074:
}
}
</syntaxhighlight>
</lang>
 
Note that any of the following array declarations could be used:
 
<langsyntaxhighlight lang="csharp">
var fruit = new[] { "apple", "orange" };
var fruit = new string[] { "apple", "orange" };
Line 1,018 ⟶ 1,084:
string[] fruit = new string[] { "apple", "orange" };
string[] fruit = { "apple", "orange" };
</syntaxhighlight>
</lang>
 
A shorter variant could also have been used:
 
<langsyntaxhighlight lang="csharp">
using static System.Console;
 
Line 1,032 ⟶ 1,098:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
Line 1,040 ⟶ 1,106:
However, C++ has an additional <code>std::array</code> type (amongst other collections) in its standard library:
 
<langsyntaxhighlight lang="cpp">#include <array>
#include <iostream>
#include <string>
Line 1,049 ⟶ 1,115:
std::cout << fruit.size();
return 0;
}</langsyntaxhighlight>
 
Note that <code>char*</code> or <code>const char*</code> could have been used instead of <code>std::string</code>.
Line 1,055 ⟶ 1,121:
In addition to the <code>std::array</code> 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.
<langsyntaxhighlight 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;</langsyntaxhighlight>
 
Of these, vector is probably the most widely used.
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">shared void run() {
value array = ["apple", "orange"];
print(array.size);
}</langsyntaxhighlight>
 
=={{header|Clipper/XBase++}}==
 
<syntaxhighlight lang="clipper/xbase++">/*
<lang Clipper/XBase++>/*
* nizchka: March - 2016
* This is a Clipper/XBase++ of RosettaCode Array_Length
Line 1,080 ⟶ 1,146:
? LEN(FRUIT)
RETURN
</syntaxhighlight>
</lang>
Outputs:<pre>2</pre>
[[User:nizchka|nizchka]] 23:27, 16 March 2016 (UTC)
Line 1,086 ⟶ 1,152:
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="clojure">; using count:
(count ["apple" "orange"])
 
; OR alength if using Java arrays:
(alength (into-array ["apple" "orange"]))</langsyntaxhighlight>
 
=={{header|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.
 
<langsyntaxhighlight COBOLlang="cobol"> identification division.
program-id. array-length.
 
Line 1,134 ⟶ 1,200:
.
 
end program array-length.</langsyntaxhighlight>
{{out}}
<pre>$ cobc -xjd array-length.cob
Line 1,143 ⟶ 1,209:
=={{header|ColdFusion}}==
 
<langsyntaxhighlight lang="coldfusion">
<cfset testArray = ["apple","orange"]>
<cfoutput>Array Length = #ArrayLen(testArray)#</cfoutput>
</syntaxhighlight>
</lang>
Outputs:<pre>Array Length = 2</pre>
[[User:grandnegus|Mike Knapp]] 15:57, 26 May 2016 (UTC)
 
=={{header|Common Lisp}}==
<syntaxhighlight lang="lisp">
<lang Lisp>
(print (length #("apple" "orange")))
</syntaxhighlight>
</lang>
===Alternate solution===
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]
 
<langsyntaxhighlight lang="lisp">
;; Project : Array length
 
Line 1,166 ⟶ 1,232:
(length my-array)
(terpri)
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,174 ⟶ 1,240:
=={{header|Component Pascal}}==
{{works with|BlackBox Component Builder}}
<langsyntaxhighlight lang="oberon2">
MODULE AryLen;
IMPORT StdLog;
Line 1,207 ⟶ 1,273:
 
END AryLen.
</syntaxhighlight>
</lang>
Execute: ^Q AryLen.Do
{{out}}
Line 1,216 ⟶ 1,282:
=={{header|Crystal}}==
 
<langsyntaxhighlight lang="ruby">
puts ["apple", "orange"].size
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,226 ⟶ 1,292:
 
=={{header|D}}==
<syntaxhighlight lang="d">
<lang d>
import std.stdio;
 
Line 1,235 ⟶ 1,301:
return 0;
}
</syntaxhighlight>
</lang>
 
Or a somewhat shorter...
<syntaxhighlight lang="d">
<lang d>
import std.stdio;
 
Line 1,245 ⟶ 1,311:
["apple", "orange"].length.writeln;
}
</syntaxhighlight>
</lang>
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">
arrLength(arr) {
return arr.length;
Line 1,258 ⟶ 1,324:
}
 
</syntaxhighlight>
</lang>
 
=={{header|DataWeave}}==
<langsyntaxhighlight DataWeavelang="dataweave">var arr = ["apple", "orange"]
sizeOf(arr)
</syntaxhighlight>
</lang>
 
=={{header|Delphi}}==
<langsyntaxhighlight lang="delphi">
showmessage( length(['a','b','c']).ToString );
</syntaxhighlight>
</lang>
 
=={{header|Diego}}==
<langsyntaxhighlight lang="diego">set_namespace(rosettacode)_me();
 
me_msg()_array()_values(apple,orange)_length();
reset_namespace[];</langsyntaxhighlight>
{{out}}
Line 1,282 ⟶ 1,348:
 
=={{header|Dragon}}==
<langsyntaxhighlight lang="dragon">select "std"
 
a = ["apple","orange"]
Line 1,288 ⟶ 1,354:
 
show b
</syntaxhighlight>
</lang>
 
=={{header|dt}}==
<syntaxhighlight lang="dt">[ "apple" "orange" ] len</syntaxhighlight>
 
=={{header|Dyalect}}==
<syntaxhighlight lang="dyalect">var xs = ["apple", "orange"]
 
print(xs.Length())</syntaxhighlight>
<lang dyalect>var xs = ["apple", "orange"]
print(xs.Length())</lang>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="text">fruit$[] = [ "apples" "oranges" ]
print len fruit$[]</langsyntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(length '("apple" "orange")) ;; list
→ 2
(vector-length #("apple" "orange")) ;; vector
→ 2
</syntaxhighlight>
</lang>
 
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">String[] array = ["apple", "orange"];
Int length = array.size;</syntaxhighlight>
 
=={{header|Ela}}==
<syntaxhighlight lang ="ela">length [1..10]</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 5.0 :
<langsyntaxhighlight lang="elena">
var array := new string[]{"apple", "orange"};
var length := array.Length;
</syntaxhighlight>
</lang>
 
=={{header|Elixir}}==
<langsyntaxhighlight lang="elixir">iex(1)> length( ["apple", "orange"] ) # List
2
iex(2)> tuple_size( {"apple", "orange"} ) # Tuple
2</langsyntaxhighlight>
 
=={{header|Elm}}==
<langsyntaxhighlight lang="elm">
import Array
import Html
Line 1,333 ⟶ 1,405:
|> Array.fromList
|> Array.length
|> BasicsString.toStringfromInt
|> Html.text
</syntaxhighlight>
</lang>
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight Lisplang="lisp">(length ["apple" "orange"])
=> 2</langsyntaxhighlight>
 
<code>length</code> also accepts a list or a string.
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
writeLine(text["apple", "orange"].length)
</syntaxhighlight>
 
=={{header|Erlang}}==
<syntaxhighlight lang="erlang">
<lang Erlang>
1> length(["apple", "orange"]). %using a list
2
1> tuple_size({"apple", "orange"}). %using a tuple
2
</syntaxhighlight>
</lang>
 
 
=={{header|Euphoria}}==
<syntaxhighlight lang="euphoria">
<lang Euphoria>
sequence s = {"apple","orange",2.95} -- Euphoria doesn't care what you put in a sequence
 
Line 1,373 ⟶ 1,450:
1 -- 2.95 is an atomic value
 
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">[|1;2;3|].Length |> printfn "%i"</langsyntaxhighlight>
Or:
<langsyntaxhighlight lang="fsharp">[|1;2;3|] |> Array.length |> printfn "%i"</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">
{ "apple" "orange" } length
</syntaxhighlight>
</lang>
 
=={{header|Fennel}}==
<syntaxhighlight lang="fennel">(length [:apple :orange])</syntaxhighlight>
 
=={{header|Forth}}==
Line 1,391 ⟶ 1,471:
The code is commented to explain what is going on for those unfamiliar with Forth.
 
<syntaxhighlight lang="forth">: STRING, ( caddr len -- ) \ Allocate space & compile string into memory
HERE OVER CHAR+ ALLOT PLACE ;
 
Line 1,417 ⟶ 1,497:
REPEAT
DROP
R> ; \ return counter to data stack </langsyntaxhighlight>
Test code at Forth console
<langsyntaxhighlight lang="forth">CREATE Q { " Apples" " Oranges" } q {len} . 2 ok</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 1,432 ⟶ 1,512:
For a simple example, the WRITE(6,*) suffices: write to standard output (the 6), in free-format (the *).
 
<syntaxhighlight lang="fortran">
<lang Fortran>
MODULE EXAMPLE
CONTAINS
Line 1,453 ⟶ 1,533:
WRITE (6,*) "L. bound",LBOUND(ARRAY),", U. bound",UBOUND(ARRAY)
END
</syntaxhighlight>
</lang>
 
Output:
Line 1,467 ⟶ 1,547:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim fruit(1) As String = {"apple", "orange"}
Line 1,474 ⟶ 1,554:
Print
Print "Press any key to quit the program"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,482 ⟶ 1,562:
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">
a = ["apple", "orange"]
println[length[a]]
</syntaxhighlight>
</lang>
 
=={{header|FurryScript}}==
<langsyntaxhighlight lang="furryscript">THE_LIST( <apple> <orange> )
COUNT[ 0 SW ~| COUNT_STEP# 0 SW SU ]
COUNT_STEP[ DR 1 SU ]
 
`THE_LIST COUNT# +<></langsyntaxhighlight>
 
=={{header|Futhark}}==
Line 1,498 ⟶ 1,578:
The <code>shape</code> builtin returns the shape of an array as an array of integers. The length is element 0 of the shape:
 
<syntaxhighlight lang="futhark">
<lang Futhark>
fun length(as: []int): int = (shape as)[0]
</syntaxhighlight>
</lang>
 
=={{header|FutureBasic}}==
NSUInteger count = fn ArrayCount( ''array'' ). Example:
<langsyntaxhighlight lang="futurebasic">
window 1
print fn ArrayCount( @[@"apple",@"orange",@"cherry",@"grape",@"lemon"] )
HandleEvents
</syntaxhighlight>
</lang>
 
We can also use FB's len() function to get the length of an array.
<syntaxhighlight lang="futurebasic">
void local fn DoIt
CFArrayRef array = @[@"apple",@"orange",@"cherry",@"grape",@"lemon"]
print len(array)
end fn
 
fn DoIt
 
HandleEvents
</syntaxhighlight>
 
{{out}}
<pre>
Line 1,516 ⟶ 1,609:
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Array_length}}
Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation &mdash;i.e. XML, JSON&mdash; they are intended for storage and transfer purposes more than visualization and edition.
 
'''Solution'''
 
The cardinality expression reduces to the number of subexpressions the given expression has, including if the expressions is a list:
 
[[File:Fōrmulæ - Array length 01.png]]
Programs in Fōrmulæ are created/edited online in its [https://formulae.org website], However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edite/d, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.
 
[[File:Fōrmulæ - Array length 02.png]]
In '''[https://formulae.org/?example=Array_length this]''' page you can see the program(s) related to this task and their results.
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=2a452c807c7030eb64a2f1d60d31a830 Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim siList As Short[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
 
Print siList.Count
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,536 ⟶ 1,633:
 
=={{header|Genie}}==
<langsyntaxhighlight lang="genie">[indent=4]
/* Array length, in Genie */
init
arr:array of string = {"apple", "orange"}
stdout.printf("%d ", arr.length)
print arr[1]</langsyntaxhighlight>
 
{{out}}
Line 1,550 ⟶ 1,647:
=={{header|Go}}==
 
<langsyntaxhighlight Golang="go">package main
 
import "fmt"
Line 1,558 ⟶ 1,655:
 
fmt.Printf("Length of %v is %v.\n", arr, len(arr))
}</langsyntaxhighlight>
 
 
Line 1,568 ⟶ 1,665:
=={{header|Groovy}}==
 
<syntaxhighlight lang="groovy">
<lang Groovy>
def fruits = ['apple','orange']
println fruits.size()
</syntaxhighlight>
</lang>
 
=={{header|Harbour}}==
 
<langsyntaxhighlight lang="visualfoxpro">
LOCAL aFruits := {"apple", "orange"}
Qout( Len( aFruits ) ) // --> 2
</syntaxhighlight>
</lang>
 
=={{header|Haskell}}==
 
<langsyntaxhighlight Haskelllang="haskell">-- [[Char]] -> Int
length ["apple", "orange"]</langsyntaxhighlight>
 
=={{header|hexiscript}}==
<langsyntaxhighlight lang="hexiscript">let a arr 2
let a[0] "apple"
let a[1] "orange"
println len a</langsyntaxhighlight>
 
=={{header|Hoon}}==
<langsyntaxhighlight Hoonlang="hoon">|= arr=(list *) (lent arr)</langsyntaxhighlight>
 
=={{header|i}}==
<langsyntaxhighlight lang="i">main: print(#["apple", "orange"])</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Icon, and therefore Unicon, includes a prefix size operator, star <code>*</code>. This operator can be applied to just about any data type or data structure.
 
<langsyntaxhighlight lang="unicon">write(*["apple", "orange"])</langsyntaxhighlight>
 
=={{header|Idris}}==
<langsyntaxhighlight Idrislang="idris">length ["apple", "orange"]</langsyntaxhighlight>
 
=={{header|Insitux}}==
<syntaxhighlight lang="insitux">(len ['apple' 'orange'])</syntaxhighlight>
 
=={{header|J}}==
Tally (<code>#</code>) returns the length of the leading dimension of an array (or 1 if the array has no dimensions). Shape Of (<code>$</code>) returns the length of each dimension of an array.
<langsyntaxhighlight lang="j"> # 'apple';'orange'
2
$ 'apple';'orange'
2</langsyntaxhighlight>
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.
<langsyntaxhighlight lang="j"> $#'apple';'orange'
 
$$'apple';'orange'
1</langsyntaxhighlight>
This might be a clearer concept with a few more examples. Here's an array with two dimensions:
<langsyntaxhighlight lang="j"> >'apple';'orange'
apple
orange
Line 1,623 ⟶ 1,723:
2 6
#>'apple';'orange'
2</langsyntaxhighlight>
And, here's an array with no dimensions:
<syntaxhighlight lang="text"> 9001
9001
#9001
1
$9001
</syntaxhighlight>
</lang>
You can count the number of dimensions of an array (the length of the list of lengths) using <code>#$array</code>:
<syntaxhighlight lang="j">
<lang j>
#$9001
0
Line 1,638 ⟶ 1,738:
1
#$>'apple';'orange'
2</langsyntaxhighlight>
 
=={{header|Janet}}==
 
<langsyntaxhighlight lang="janet">
(def our-array @["apple" "orange"])
(length our-array)
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,653 ⟶ 1,753:
 
=={{header|Java}}==
The resulting ''array'' object will have a ''length'' field.
<lang java>public class ArrayLength {
<syntaxhighlight lang="java">
public static void main(String[] args) {
String[] strings = { System.out.println(new String[]{"apple", "orange" }.length);
int length = strings.length;
}
</syntaxhighlight>
}</lang>
Additionally, you can do this in one line, if need be.
<syntaxhighlight lang="java">
int length = new String[] { "apple", "orange" }.length;
</syntaxhighlight>
 
=={{header|JavaScript}}==
 
<langsyntaxhighlight lang="javascript">console.log(['apple', 'orange'].length);</langsyntaxhighlight>
 
However, determining the length of a list, array, or collection may simply be the wrong thing to do.
Line 1,667 ⟶ 1,771:
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'''
 
<langsyntaxhighlight JavaScriptlang="javascript">function last(lst) {
return lst[lst.length - 1];
}</langsyntaxhighlight>
 
using length has the disadvantage that it leaves ''last'' simply undefined for an empty list.
Line 1,675 ⟶ 1,779:
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.
 
<langsyntaxhighlight JavaScriptlang="javascript">function last(lst) {
return lst.reduce(function (a, x) {
return x;
}, null);
}</langsyntaxhighlight>
 
Alternatively, rather than scanning the entire list to simply get the final value, it might sometimes be better to test the length:
 
<langsyntaxhighlight JavaScriptlang="javascript">function last(list, defaultValue) {
return list.length ?list[list.length-1] :defaultValue;
}</langsyntaxhighlight>
 
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):
 
<langsyntaxhighlight JavaScriptlang="javascript">function last(list, defaultValue) {
return list.slice(-1)[0] || defaultValue;
}</langsyntaxhighlight>
 
=={{header|jqJoy}}==
<syntaxhighlight lang="joy">["apple" "orange"] size.</syntaxhighlight>
{{out}}
<pre>2</pre>
 
=={{header|jq}}==
<lang jq>["apple","orange"] | length</lang>
<syntaxhighlight lang="jq">["apple","orange"] | length</syntaxhighlight>
Output:
<syntaxhighlight lang ="sh">2</langsyntaxhighlight>
 
Note that the ''length'' filter is polymorphic, so for example the empty string (""), the empty list ([]), and ''null'' all have ''length'' 0.
 
=={{header|Jsish}}==
<langsyntaxhighlight lang="javascript">/* Array length, in jsish */
var arr = new Array('apple', 'orange');
puts(arr.length);
puts(arr[1]);</langsyntaxhighlight>
 
{{out}}
Line 1,714 ⟶ 1,822:
=={{header|Julia}}==
 
<syntaxhighlight lang="julia">
<lang Julia>
a = ["apple","orange"]
length(a)
</syntaxhighlight>
</lang>
 
=={{header|K}}==
<syntaxhighlight lang="k">#("apple";"orange")</syntaxhighlight>
{{out}}
<pre>2</pre>
 
=={{header|Klingphix}}==
<langsyntaxhighlight Klingphixlang="klingphix">include ..\Utilitys.tlhy
 
( "apple" "orange" ) len print
 
" " input</langsyntaxhighlight>
{{out}}
<pre>2</pre>
Line 1,730 ⟶ 1,843:
=={{header|Klong}}==
 
<syntaxhighlight lang="k">
<lang K>
#["apple" "orange"]
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
 
<langsyntaxhighlight lang="scala">fun main(args: Array<String>) {
println(arrayOf("apple", "orange").size)
}</langsyntaxhighlight>
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
{A.length {A.new 1 2 3}}
-> 3
</syntaxhighlight>
</lang>
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
&arr $= [apple, orange]
 
# Array length function
fn.println(fn.arrayLength(&arr))
 
# Length operator function
fn.println(fn.len(&arr))
 
# Length operator
fn.println(parser.op(@&arr))
</syntaxhighlight>
 
=={{header|Latitude}}==
Line 1,750 ⟶ 1,877:
In Latitude, <code>length</code> and <code>size</code> are synonymous and will both retrieve the size of a collection.
 
<langsyntaxhighlight lang="latitude">println: ["apple", "orange"] length.</langsyntaxhighlight>
 
=={{header|LDPL}}==
<syntaxhighlight lang="ldpl">data:
fruits is text list
len is number
 
procedure:
push "apple" to fruits
push "orange" to fruits
get length of fruits in len
display len lf
</syntaxhighlight>
{{out}}
<pre>
2
</pre>
 
=={{header|Liberty BASIC}}==
Line 1,762 ⟶ 1,905:
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/
{{works with|LB Booster}}
<syntaxhighlight lang="lb">
<lang lb>
FruitList$(0)="apple" 'assign 2 cells of a list array
FruitList$(1)="orange"
Line 1,874 ⟶ 2,017:
print ")"
end sub
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,885 ⟶ 2,028:
LIL does not use arrays, but indexed lists. The builtin '''count''' command returns the item count in a list. The '''length''' command returns the length of the list after string conversion.
 
<langsyntaxhighlight lang="tcl"># Array length, in LIL
set a [list "apple"]
append a "orange"
print [count $a]
print [index $a 1]</langsyntaxhighlight>
 
{{out}}
Line 1,897 ⟶ 2,040:
 
=={{header|Limbo}}==
<langsyntaxhighlight Limbolang="limbo">implement Command;
 
include "sys.m";
Line 1,912 ⟶ 2,055:
a := array[] of {"apple", "orange"};
sys->print("length of a: %d\n", len a);
}</langsyntaxhighlight>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">fruits = ["apple", "orange"]
put fruits.count
-- 2</langsyntaxhighlight>
 
=={{header|Little}}==
<langsyntaxhighlight Clang="c">string fruit[] = {"apples", "oranges"};
puts(length(fruit));</langsyntaxhighlight>
 
=={{header|LiveCode}}==
 
<langsyntaxhighlight LiveCodelang="livecode">put "apple","orange" into fruit
split fruit using comma
answer the number of elements of fruit</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">-- For tables as simple arrays, use the # operator:
fruits = {"apple", "orange"}
print(#fruits)
Line 1,947 ⟶ 2,090:
end
 
print(size(fruits))</langsyntaxhighlight>
{{out}}
<pre>
Line 1,956 ⟶ 2,099:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
\\ A is a pointer to array
A=("Apple", "Orange")
Line 1,995 ⟶ 2,138:
Dim K(1,1,1,1,1,1) ' Maximum 10 dimensions
Print Len(K()=1 ' True
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">a := Array(["apple", "orange"]);
numelems(a);</langsyntaxhighlight>
{{out}}
<pre>
Line 2,007 ⟶ 2,150:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Length[{"apple", "orange"}]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight Matlablang="matlab">length({'apple', 'orange'})</langsyntaxhighlight>
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.
<langsyntaxhighlight Matlablang="matlab">numel({'apple', 'orange'; 'pear', 'banana'})</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE ArrayLength EXPORTS Main;
 
IMPORT IO;
Line 2,024 ⟶ 2,167:
BEGIN
IO.PutInt(NUMBER(Arr));
END ArrayLength.</langsyntaxhighlight>
 
=={{header|Mercury}}==
<langsyntaxhighlight Mercurylang="mercury">:- module array_length.
:- interface.
 
Line 2,039 ⟶ 2,182:
main(!IO) :-
Array = array(["apples", "oranges"]),
io.write_int(size(Array), !IO).</langsyntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.3}}
<langsyntaxhighlight lang="min">("apple" "orange") size print</langsyntaxhighlight>
{{out}}
<pre>
Line 2,050 ⟶ 2,193:
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">
<lang MiniScript>
fruits = ["apple", "orange"]
print fruits.len
</syntaxhighlight>
</lang>
=={{header|MiniZinc}}==
<syntaxhighlight lang="minizinc">
<lang MiniZinc>
array[int] of int: arr = [1,2,3];
var int: size = length(arr);
Line 2,062 ⟶ 2,205:
 
output [show(size),"\n"];
</syntaxhighlight>
</lang>
 
=={{header|Nanoquery}}==
<langsyntaxhighlight lang="nanoquery">fruit = array(2)
fruit[0] = "apple"
fruit[1] = "orange"
println len(fruit)
 
// outputs 2</langsyntaxhighlight>
 
=={{header|Neko}}==
<langsyntaxhighlight lang="neko">var fruit = $array("apple", "orange");
 
$print($asize(fruit));</langsyntaxhighlight>
 
=={{header|NewLISP}}==
<langsyntaxhighlight lang="newlisp">(println (length '("apple" "orange")))
 
; Nehal-Singhal 2018-05-25
(length '(apple orange))</langsyntaxhighlight>
 
=={{header|NGS}}==
<langsyntaxhighlight NGSlang="ngs">echo(len(['apple', 'orange']))
# same
echo(['apple', 'orange'].len())</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">let fruit = ["apple", "orange"]
echo "The length of the fruit array is ", len(fruit)</langsyntaxhighlight>
 
{{out}}
Line 2,096 ⟶ 2,239:
The length of the fruit array is 2
</pre>
 
=={{header|Nu}}==
<syntaxhighlight lang="nu">
[apple orange] | length
</syntaxhighlight>
{{out}}
<pre>
2
</pre>
 
=={{header|Nutt}}==
<syntaxhighlight lang="Nutt">
module main
imports native.io.output.say
 
say(#{"apple","orange"})
 
end
</syntaxhighlight>
 
=={{header|Oberon-2}}==
{{works with|oo2c}}
<langsyntaxhighlight lang="oberon2">
MODULE ArrayLength;
IMPORT
Line 2,131 ⟶ 2,293:
Out.String("length: ");Out.Int(Length(a),0);Out.Ln
END ArrayLength.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,138 ⟶ 2,300:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class Test {
function : Main(args : String[]) ~ Nil {
Line 2,144 ⟶ 2,306:
fruit->Size()->PrintLine();
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<syntaxhighlight lang="ocaml">
<lang OCaml>
Array.length [|"apple"; "orange"|];;
</syntaxhighlight>
</lang>
 
=={{header|Oforth}}==
<langsyntaxhighlight Oforthlang="oforth">[ "apple", "orange" ] size</langsyntaxhighlight>
 
=={{header|Ol}}==
All of these methods are equivalent.
<langsyntaxhighlight lang="scheme">
(print (vector-length (vector "apple" "orange")))
(print (vector-length #("apple" "orange")))
Line 2,162 ⟶ 2,324:
 
(print (size #("apple" "orange")))
</syntaxhighlight>
</lang>
 
=={{header|Onyx}}==
 
<langsyntaxhighlight lang="onyx">[`apple' `orange'] length # leaves 2 on top of the stack</langsyntaxhighlight>
 
=={{header|ooRexx}}==
<langsyntaxhighlight lang="oorexx">
/* REXX */
a = .array~of('apple','orange')
Line 2,176 ⟶ 2,338:
say e
End
Say "a[2]="a[2]</langsyntaxhighlight>
{{out}}
<pre>2 elements
Line 2,184 ⟶ 2,346:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">array = ["apple", "orange"]
length(array) \\ == 2
#array \\ == 2</langsyntaxhighlight>
 
The <code>#</code> syntax is a handy shorthand. It usually looks best just on variables but it works on expressions too, possibly with parens to control precedence.
Line 2,196 ⟶ 2,358:
{{works with|Free Pascal|2.6.2}}
 
<syntaxhighlight lang="pascal">
<lang Pascal>
#!/usr/bin/instantfpc
//program ArrayLength;
Line 2,211 ⟶ 2,373:
WriteLn('Length of Fruits by bounds : ', High(Fruits) - Low(Fruits) + 1);
END.
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,221 ⟶ 2,383:
</pre>
 
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="pascal">
// Array length. Nigel Galloway: September 2nd., 2022
var n:array of string:=('apple','orange');
begin
writeln(Length(n));
end.
</syntaxhighlight>
{{out}}
<pre>
2
</pre>
=={{header|Perl}}==
 
The way to get the number of elements of an array in Perl is to put the array in scalar context.
 
<langsyntaxhighlight lang="perl">my @array = qw "apple orange banana", 4, 42;
 
scalar @array; # 5
Line 2,244 ⟶ 2,418:
takes_a_scalar @array;
 
# the built-ins can also act like they have prototypes</langsyntaxhighlight>
 
A common mistake is to use <code>length</code> 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.
 
<langsyntaxhighlight lang="perl">length '' . @array; # 1
length @array; # 1
 
Line 2,259 ⟶ 2,433:
print 'the length of @array is on the order of ';
print 10 ** (length( @array )-1); # 100
print " elements long\n";</langsyntaxhighlight>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">fruits</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{<span style="color: #008000;">"apple"<span style="color: #0000FF;">,<span style="color: #008000;">"orange"<span style="color: #0000FF;">}</span>
<span style="color: #0000FF;">?<span style="color: #7060A8;">length<span style="color: #0000FF;">(<span style="color: #000000;">fruits<span style="color: #0000FF;">)
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,273 ⟶ 2,447:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">"apple" "orange" stklen tolist len print</langsyntaxhighlight>
With syntactic sugar
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
( "apple" "orange" ) len print</langsyntaxhighlight>
{{out}}
<pre>
Line 2,284 ⟶ 2,458:
=={{header|PHP}}==
 
<langsyntaxhighlight lang="php">print count(['apple', 'orange']); // Returns 2</langsyntaxhighlight>
 
=={{header|Picat}}==
<syntaxhighlight lang="text">main =>
L = ["apple", "orange"],
println(len(L))),
println(length(L)),
println(L.len),
println(L.length).</langsyntaxhighlight>
 
{{out}}
Line 2,302 ⟶ 2,476:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">: (length '(apple orange))
-> 2
:</langsyntaxhighlight>
 
=={{header|Pike}}==
<langsyntaxhighlight lang="pike">void main()
{
array fruit = ({ "apple", "orange" });
write("%d\n", sizeof(fruit));
}</langsyntaxhighlight>
 
{{out}}
Line 2,317 ⟶ 2,491:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli"> p: Proc Options(main);
Dcl a(2) Char(6) Varying Init('apple','orange');
Put Edit('Array a has',(hbound(a)-lbound(a)+1),' elements.')
(Skip,a,f(2),a);
Put Skip Data(a);
End;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,329 ⟶ 2,503:
 
=={{header|Plorth}}==
<langsyntaxhighlight lang="plorth">["apple", "orange"] length println</langsyntaxhighlight>
 
=={{header|Pony}}==
<langsyntaxhighlight lang="pony">
actor Main
new create(env:Env)=>
Line 2,339 ⟶ 2,513:
c.push("orange")
env.out.print("Array c is " + c.size().string() + " elements long!")
</syntaxhighlight>
</lang>
 
=={{header|Potion}}==
<langsyntaxhighlight lang="potion">("apple", "orange") length print</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
$Array = @( "Apple", "Orange" )
$Array.Count
$Array.Length</langsyntaxhighlight>
{{out}}
<pre>
Line 2,355 ⟶ 2,529:
 
=={{header|Processing}}==
<syntaxhighlight lang="processing">
<lang Processing>
String[] arr = {"apple", "orange"};
void setup(){
println(arr.length);
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,367 ⟶ 2,541:
 
==={{header|Processing Python mode}}===
<langsyntaxhighlight lang="python">
arr = ['apple', 'orange'] # a list for an array
 
def setup():
println(len(arr))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,380 ⟶ 2,554:
 
=={{header|Prolog}}==
<langsyntaxhighlight Prologlang="prolog">| ?- length(["apple", "orange"], X).
 
X = 2
 
yes</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">
<lang PureBasic>
EnableExplicit
Define Dim fruit$(1); defines array with 2 elements at indices 0 and 1
Line 2,400 ⟶ 2,574:
CloseConsole()
EndIf
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,407 ⟶ 2,581:
 
An abbreviated form of the above, not printing to console/terminal
<syntaxhighlight lang="purebasic">
<lang PureBasic>
Dim fruit$(1); defines array with 2 elements at indices 0 and 1
fruit$(0) = "apple"
fruit$(1) = "orange"
Debug ArraySize(fruit$()) + 1 ;the number of elements is equal to the size + 1. For example: Dim a(2) contains 3 elements from a(0) to a(2) for a size of 2.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,419 ⟶ 2,593:
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">>>> print(len(['apple', 'orange']))
2
>>> </langsyntaxhighlight>
 
=={{header|QB64}}==
 
<syntaxhighlight lang="qb64">
<lang QB64>
Dim max As Integer, Index As Integer
Randomize Timer
Line 2,436 ⟶ 2,610:
Print UBound(Stringar)
End
</syntaxhighlight>
</lang>
=={{header|Quackery}}==
 
<Langsyntaxhighlight Quackerylang="quackery"> $ "apples" $ "oranges" 2 pack size echo</langsyntaxhighlight>
 
{{out}}
Line 2,446 ⟶ 2,620:
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
a <- c('apple','orange') # create a vector containing "apple" and "orange"
length(a)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,457 ⟶ 2,631:
=={{header|Racket}}==
{{trans|EchoLisp}}
<langsyntaxhighlight lang="racket">#lang racket/base
(length '("apple" "orange")) ;; list
(vector-length #("apple" "orange")) ;; vector</langsyntaxhighlight>
{{out}}
<pre>2
Line 2,470 ⟶ 2,644:
To get the number of elements of an array in Raku you put the array in a coercing Numeric context, or call <code>elems</code> on it.
 
<syntaxhighlight lang="raku" line>
<lang perl6>
my @array = <apple orange>;
 
Line 2,477 ⟶ 2,651:
say + @array; # 2
say @array + 0; # 2
</syntaxhighlight>
</lang>
 
Watch out for infinite/lazy arrays though. You can't get the length of those.
 
<syntaxhighlight lang="raku" perl6line>my @infinite = 1 .. Inf; # 1, 2, 3, 4, ...
 
say @infinite[5000]; # 5001
say @infinite.elems; # Throws exception "Cannot .elems a lazy list"
</syntaxhighlight>
</lang>
 
=={{header|Rapira}}==
<syntaxhighlight lang="rapira">arr := <* "apple", "orange" *>
<lang Rapira>
output: #arr</syntaxhighlight>
arr := <* "apple", "orange" *>
 
output: #arr
=={{header|REBOL}}==
</lang>
<syntaxhighlight lang="rebol">
>> length? ["apples" "oranges"]
== 2
</syntaxhighlight>
 
=={{header|Red}}==
<langsyntaxhighlight Redlang="red">length? ["apples" "oranges"]
== 2</langsyntaxhighlight>
 
=={{header|Relation}}==
<syntaxhighlight lang="relation">
<lang Relation>
relation fruit
insert "apples"
Line 2,504 ⟶ 2,682:
project fruit count
print
</syntaxhighlight>
</lang>
 
{| border=1
Line 2,514 ⟶ 2,692:
 
=={{header|ReScript}}==
<langsyntaxhighlight lang="rescript">let fruits = ["apple", "orange"]
 
Js.log(Js.Array.length(fruits))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="html"><!DOCTYPE html>
<html>
<head>
Line 2,531 ⟶ 2,709:
 
</body>
</html></langsyntaxhighlight>
{{out}}
<pre>// Generated by ReScript, PLEASE EDIT WITH CARE
Line 2,548 ⟶ 2,726:
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/* REXX ----------------------------------------------
* The compond variable a. implements an array
* By convention, a.0 contains the number of elements
Line 2,564 ⟶ 2,742:
a.z=arg(1)
a.0=z
Return</langsyntaxhighlight>
{{out}}
<pre>There are 2 elements in the array:
Line 2,572 ⟶ 2,750:
=={{header|Ring}}==
 
<langsyntaxhighlight lang="python">See len(['apple', 'orange']) # output = 2 </langsyntaxhighlight>
 
=={{header|Robotic}}==
Line 2,578 ⟶ 2,756:
 
Example 1:
<langsyntaxhighlight lang="robotic">
set "index" to 0
set "$array&index&" to "apple"
Line 2,584 ⟶ 2,762:
set "$array&index&" to "orange"
* "Array length: ('index' + 1)"
</syntaxhighlight>
</lang>
 
Example 2:
<langsyntaxhighlight lang="robotic">
set "index" to 0
set "local1" to random 1 to 99
Line 2,596 ⟶ 2,774:
if "local1" > 1 then "rand"
* "Array length: ('index')"
</syntaxhighlight>
</lang>
 
=={{header|RPL}}==
The <code>SIZE</code> instruction can be used for arrays (e.g. vectors) and lists. RPL arrays can only contain real or complex numbers, so we will use a list here.
{ "apple" "orange" } SIZE
{{out}}
<pre>
1: 2
</pre>
 
=={{header|Ruby}}==
 
<langsyntaxhighlight lang="ruby">puts ['apple', 'orange'].length # or .size</langsyntaxhighlight>
 
=={{header|Rust}}==
Line 2,606 ⟶ 2,792:
By default arrays are immutable in rust.
 
<langsyntaxhighlight lang="rust">
fn main() {
let array = ["foo", "bar", "baz", "biff"];
println!("the array has {} elements", array.len());
}
</syntaxhighlight>
</lang>
 
=={{header|S-BASIC}}==
Finding the size of an S-BASIC array at run-time is convoluted, to say the least, but it can be done. (It would also generally be pointless, since the size of an array is fixed - and thus presumably known - at compile time.) Each array has an associated data structure (referred to in the documentation as "SPEC") containing information such as the number of dimensions, the size of an array element, the size of each dimension, and so on. The address of the SPEC for an array can be obtained using the LOCATION statement. For a single-dimension array, the number of elements will be found five bytes into the structure, at a point described in the documentation as the "dope vector".
<syntaxhighlight lang = "BASIC">
dim string animals(2) rem here is our array
var array_struct_address = integer
based array_size = integer
 
animals(1) = "ardvark"
animals(2) = "bison"
 
location spec array_struct_address = animals
base array_size at array_struct_address + 5
 
print "Size of array ="; array_size
 
end
</syntaxhighlight>
{{out}}
<pre>
Size of array = 2
</pre>
 
=={{header|Scala}}==
 
<langsyntaxhighlight lang="scala">
println(Array("apple", "orange").length)
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
Line 2,623 ⟶ 2,831:
Using Scheme's vector type as an equivalent to an array:
 
<langsyntaxhighlight lang="scheme">
(display (vector-length #("apple" "orange")))
</syntaxhighlight>
</lang>
 
=={{header|Seed7}}==
The function [http://seed7.sourceforge.net/libraries/array.htm#length(in_arrayType) length]
determines the length of an array.
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const array string: anArray is [] ("apple", "orange");
Line 2,637 ⟶ 2,845:
begin
writeln(length(anArray));
end func;</langsyntaxhighlight>
 
=={{header|SenseTalk}}==
<langsyntaxhighlight lang="sensetalk">put ("apple", "orange", "pear", "banana", "aubergine") into fruits
put the number of items in fruits</langsyntaxhighlight>
 
=={{header|Shen}}==
<langsyntaxhighlight lang="shen">
\\ Using a vector
\\ @v creates the vector
Line 2,655 ⟶ 2,863:
\\ As an list
(length [apple orange])
</syntaxhighlight>
</lang>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var arr = ['apple', 'orange'];
say arr.len; #=> 2
say arr.end; #=> 1 (zero based)</langsyntaxhighlight>
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">COMMENT ARRAY-LENGTH;
BEGIN
 
Line 2,679 ⟶ 2,887:
OUTIMAGE;
END
</syntaxhighlight>
</lang>
{{out}}
<pre>
2
</pre>
 
=={{heaer|Slope}}==
<syntaxhighlight lang="slope">(length ["apple" "orange"])</syntaxhighlight>
 
=={{header|SmallBASIC}}==
<syntaxhighlight lang="SmallBASIC">
A = ["apple", "orange"]
print len(A)
</syntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">
a := #('apple' 'orange').
a size</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight SNOBOL4lang="snobol4"> ar = ARRAY('2,2')
ar<1,1> = 'apple'
ar<1,2> = 'first'
Line 2,697 ⟶ 2,914:
ar<2,2> = 'second'
OUTPUT = IDENT(DATATYPE(ar), 'ARRAY') PROTOTYPE(ar)
end</langsyntaxhighlight>
{{out}}<pre>2,2</pre>
 
=={{header|SPL}}==
<langsyntaxhighlight lang="spl">a = ["apple","orange"]
#.output("Number of elements in array: ",#.size(a,1))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,710 ⟶ 2,927:
=={{header|SQL}}==
 
<langsyntaxhighlight lang="sql">SELECT COUNT() FROM (VALUES ('apple'),('orange'));</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight lang="sml">let
val a = Array.fromList ["apple", "orange"]
in
Array.length a
end;</langsyntaxhighlight>
 
=={{header|Stata}}==
Line 2,723 ⟶ 2,940:
 
=== Dimensions of a dataset ===
<langsyntaxhighlight lang="stata">clear
input str10 fruit
apple
Line 2,730 ⟶ 2,947:
 
di _N
di c(N) " " c(k)</langsyntaxhighlight>
 
=== Length of a macro list ===
Line 2,736 ⟶ 2,953:
Use either the '''[https://www.stata.com/help.cgi?macrolists sizeof]''' macro list function or the '''[https://www.stata.com/help.cgi?extended_fcn word count]''' extended macro function. Notice that the argument of the former is the macro ''name'', while the argument of the latter is the macro ''contents''.
 
<langsyntaxhighlight lang="stata">local fruits apple orange
di `: list sizeof fruits'
di `: word count `fruits''</langsyntaxhighlight>
 
=== Mata ===
For a Mata array, use '''[https://www.stata.com/help.cgi?mf_rows rows]''' and similar functions:
 
<langsyntaxhighlight lang="stata">mata
a=st_sdata(.,"fruit")
rows(a)
cols(a)
length(a)
end</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<langsyntaxhighlight Swiftlang="swift">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</langsyntaxhighlight>
{{out}}<pre>2</pre>
 
=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
<lang Symsyn>
| Symsyn does not support Array of Strings
| The following code for an Array of Integers
Line 2,773 ⟶ 2,990:
sz []
| shows 2
</syntaxhighlight>
</lang>
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
['apple', 'orange'] -> $::length -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>2</pre>
Line 2,785 ⟶ 3,002:
<!-- http://ideone.com/uotEvm -->
 
<langsyntaxhighlight lang="tcl">;# not recommended:
set mylistA {apple orange} ;# actually a string
set mylistA "Apple Orange" ;# same - this works only for simple cases
Line 2,798 ⟶ 3,015:
set lenB [llength $mylistB]
puts "$mylistB : $lenB"
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,807 ⟶ 3,024:
{{works with|TI-83 2.55MP}}
Use function <code>dim()</code>.
<langsyntaxhighlight lang="ti83b">{1,3,–5,4,–2,–1}→L1
dim(L1)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,815 ⟶ 3,032:
 
=={{header|Transd}}==
<langsyntaxhighlight lang="scheme">#lang transd
 
MainModule : {
Line 2,824 ⟶ 3,041:
(lout (size ["apple", "orange"]))
)
}</langsyntaxhighlight>{{out}}
<pre>
2
Line 2,831 ⟶ 3,048:
 
=={{header|UNIX Shell}}==
<langsyntaxhighlight lang="bash">#!/bin/bash
array=("orange" "apple")
echo "${#array[@]}"</langsyntaxhighlight>
{{out}}
<pre>
Line 2,849 ⟶ 3,066:
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">void main() {
string[] fruit = {"apple", "orange"};
stdout.printf("%d\n", fruit.length);
}</langsyntaxhighlight>
 
Note that any of the following array declarations could be used:
 
<langsyntaxhighlight lang="vala">
var fruit = new string[] { "apple", "orange" };
string[] fruit = new string[] { "apple", "orange" };
string[] fruit = { "apple", "orange" };
</syntaxhighlight>
</lang>
 
A shorter variant could also have been used:
 
<langsyntaxhighlight lang="vala">
void main() {
stdout.printf("%d\n", new string[] {"apples", "orange"}.length);
}
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
One-liner. Assumes array lower bound, which is not always safe.
<langsyntaxhighlight lang="vb">Debug.Print "Array Length: " & UBound(Array("apple", "orange")) + 1</langsyntaxhighlight>
 
Works regardless of lower bound:
<langsyntaxhighlight lang="vb">Dim funkyArray(7 to 8) As String
 
Public Function SizeOfArray(ar As Variant) As Long
Line 2,882 ⟶ 3,099:
 
'call the function
Debug.Print "Array Length: " & SizeOfArray(funkyArray)</langsyntaxhighlight>
 
{{Out}}
Line 2,889 ⟶ 3,106:
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">arr = Array("apple","orange")
WScript.StdOut.WriteLine UBound(arr) - LBound(arr) + 1 </langsyntaxhighlight>
 
{{Out}}
Line 2,898 ⟶ 3,115:
The amount of elements in an array in Visual Basic is computed via the upper bound and lower bound indices. In Visual Basic the indices of arrays have to be numeric, but it is even possible to have negative values for them. Of course the element numbering is continuous.
 
<syntaxhighlight lang="vb">
<lang vb>
' declared in a module
Public Function LengthOfArray(ByRef arr As Variant) As Long
Line 2,925 ⟶ 3,142:
Debug.Print LengthOfArray(arr) ' prints 2 as result
 
</syntaxhighlight>
</lang>
 
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
<langsyntaxhighlight lang="vbnet">Module ArrayLength
 
Sub Main()
Line 2,937 ⟶ 3,154:
 
End Module
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,944 ⟶ 3,161:
</pre>
 
=={{header|V (Vlang)}}==
A '''len''' property is maintained for all V (Vlang) arrays.
<langsyntaxhighlight lang="go">// V, array length
// Tectonics: v run array-length.v
module main
Line 2,954 ⟶ 3,171:
arr := ["apple", "orange"]
println(arr.len)
}</langsyntaxhighlight>
 
{{out}}<pre>prompt$ v run array-length.v
Line 2,960 ⟶ 3,177:
 
=={{header|WDTE}}==
<langsyntaxhighlight lang="wdte">let io => import 'io';
let a => ['apple'; 'orange'];
len a -- io.writeln io.stdout;</langsyntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight ecmascriptlang="wren">var arr = ["apple", "orange"]
System.print(arr.count)</langsyntaxhighlight>
 
{{out}}
Line 2,974 ⟶ 3,191:
 
=={{header|XLISP}}==
<langsyntaxhighlight lang="lisp">(vector-length #("apple" "orange"))</langsyntaxhighlight>
 
 
=={{header|Yabasic}}==
<langsyntaxhighlight lang="yabasic">
dim fruta$(3)
read fruta$(1), fruta$(2), fruta$(3)
Line 2,986 ⟶ 3,203:
print fruta$(2)
end
</syntaxhighlight>
</lang>
<pre>
3
Line 2,998 ⟶ 3,215:
The simplest way to implement an array of variable-length strings is to have the array contain pointers to said strings rather than the strings themselves. That way, the elements of the array are of equal length, which makes any array <b>much</b> easier to work with.
 
<langsyntaxhighlight lang="z80"> org &8000
ld hl,TestArray
call GetArrayLength_WordData_NullTerminated
Line 3,042 ⟶ 3,259:
byte "Apple",0
Orange:
byte "Orange",0</langsyntaxhighlight>
 
{{out}}
Line 3,051 ⟶ 3,268:
=={{header|zkl}}==
zkl doesn't support arrays natively, use lists instead.
<langsyntaxhighlight lang="zkl">List("apple", "orange").len().println() //-->2, == L("apple", "orange")
T("apple", "orange").len().println() //-->2, read only list (ROList) </langsyntaxhighlight>
 
=={{header|Zig}}==
<langsyntaxhighlight lang="zig">const std = @import("std");
 
pub fn main() !void {
Line 3,063 ⟶ 3,280:
// slices and arrays have an len field
try stdout_wr.print("fruit.len = {d}\n", .{fruit.len});
}</langsyntaxhighlight>
 
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
<lang Zoea>
program: array_length
input: [a,b,c]
output: 3
</syntaxhighlight>
</lang>
 
=={{header|Zoea Visual}}==
Line 3,076 ⟶ 3,293:
 
=={{header|zonnon}}==
<langsyntaxhighlight lang="zonnon">
module AryLength;
type
Line 3,091 ⟶ 3,308:
writeln(len(b,1):4) (* second dimension *)
end AryLength.
</syntaxhighlight>
</lang>
62

edits