Array length: Difference between revisions

Content deleted Content added
Xixo (talk | contribs)
Kennypete (talk | contribs)
Added OmniMark solution
 
(269 intermediate revisions by more than 100 users not shown)
Line 1:
{{task}}
[[Category:Simple]]
{{task}}
 
;Task:
Line 9:
 
 
{{Template:Strings}}
;Related task:
*   [[String length]]
<br><br>
 
=={{header|11l}}==
<syntaxhighlight lang="11l">print([‘apple’, ‘orange’].len)</syntaxhighlight>
{{out}}
<pre>
2
</pre>
 
=={{header|360 Assembly}}==
Array length is computed at compilation time with the formula : (AEND-A)/L'A
<syntaxhighlight lang="360asm">* Array length 22/02/2017
ARRAYLEN START
USING ARRAYLEN,12
LR 12,15 end of prolog
LA 1,(AEND-A)/L'A hbound(a)
XDECO 1,PG+13 edit
XPRNT PG,L'PG print
BR 14 exit
A DC CL6'apple',CL6'orange' array
AEND DC 0C
PG DC CL25'Array length=' buffer
END ARRAYLEN</syntaxhighlight>
{{out}}
<pre>
Array length= 2
</pre>
=={{header|6502 Assembly}}==
{{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.
<syntaxhighlight lang="6502asm">start:
LDA #(Array_End-Array) ;evaluates to 13
RTS
 
Array:
byte "apple",0
byte "orange",0
Array_End:</syntaxhighlight>
 
=={{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.
 
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.
 
 
<syntaxhighlight lang="68000devpac">start:
MOVE.B #(MyArray_End-MyArray)/4 ;evaluates to 2
RTS
 
Apple:
DC.B "apple",0
even
Orange:
DC.B "orange",0
even
 
MyArray:
DC.L Apple
DC.L Orange
MyArray_End:</syntaxhighlight>
 
=={{header|8th}}==
<langsyntaxhighlight lang="forth">
["apples", "oranges"] a:len . cr
</syntaxhighlight>
</lang>
{{out}}
<pre>
2
</pre>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program lenAreaString64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data */
/*******************************************/
.data
szMessLenArea: .asciz "The length of area is : @ \n"
szCarriageReturn: .asciz "\n"
/* areas strings */
szString1: .asciz "Apples"
szString2: .asciz "Oranges"
/* pointer items area */
tablesPoi:
ptApples: .quad szString1
ptOranges: .quad szString2
ptVoid: .quad 0
/*******************************************/
/* UnInitialized data */
/*******************************************/
.bss
sZoneConv: .skip 30
/*******************************************/
/* code section */
/*******************************************/
.text
.global main
main: // entry of program
ldr x1,qAdrtablesPoi // begin pointer table
mov x0,0 // counter
1: // begin loop
ldr x2,[x1,x0,lsl 3] // read string pointer address item x0 (8 bytes by pointer)
cmp x2,0 // is null ?
cinc x0,x0,ne // no increment counter
bne 1b // and loop
ldr x1,qAdrsZoneConv // conversion decimal
bl conversion10S
ldr x0,qAdrszMessLenArea
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess
 
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrtablesPoi: .quad tablesPoi
qAdrszMessLenArea: .quad szMessLenArea
qAdrsZoneConv: .quad sZoneConv
qAdrszCarriageReturn: .quad szCarriageReturn
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
 
=={{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">
report z_array_length.
 
data(internal_table) = value stringtab( ( `apple` ) ( `orange` ) ).
 
write: internal_table[ 1 ] , internal_table[ 2 ] , lines( internal_table ).
</syntaxhighlight>
 
{{out}}
<pre>
apple orange 2
</pre>
 
=={{header|Ada}}==
 
<syntaxhighlight lang="ada">
<lang Ada>with Ada.Text_IO;
with Ada.Text_IO; use Ada.Text_IO;
with System;
 
procedure Array_Length is
 
typeFruits AC: isconstant array (Positive range <>) of access constant String;
:= (new String'("orange"),
type Strings is array (Natural range <>) of AC;
new String'("apple"));
 
Arr: Strings := (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 Str of Arr loop
Put_Line ("Array memory Size : " & Memory_Size'Image & " bytes" );
Ada.Text_IO.Put(Integer'Image(Str.all'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(Arr'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}}==
<syntaxhighlight lang="apex">System.debug(new String[] { 'apple', 'banana' }.size()); // Prints 2</syntaxhighlight>
 
=={{header|APL}}==
<syntaxhighlight lang ="apl">⍴'apple' 'orange'</langsyntaxhighlight>
Output:
<pre>2</pre>
 
=={{header|Apex}}==
<lang apex>System.debug(new String[] { 'apple', 'banana' }.size()); // Prints 2</lang>
 
=={{header|AppleScript}}==
<syntaxhighlight lang="applescript">
<lang AppleScript>
set theList to {"apple", "orange"}
count theList
Line 68 ⟶ 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}}
<pre>2</pre>
Line 78 ⟶ 229:
<pre>fold (λx n -> 1 + n) 0</pre>
 
<langsyntaxhighlight AppleScriptlang="applescript">on run
set xs to ["alpha", "beta", "gamma", "delta", "epsilon", ¬
Line 119 ⟶ 270:
end repeat
end fold
</syntaxhighlight>
</lang>
 
{{Out}}
 
<pre>{12, 12, "mu", "mu"}</pre>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program lenAreaString.s */
 
/* Constantes */
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/* Initialized data */
.data
szMessLenArea: .ascii "The length of area is : "
sZoneconv: .fill 12,1,' '
szCarriageReturn: .asciz "\n"
 
/* areas strings */
szString1: .asciz "Apples"
szString2: .asciz "Oranges"
/* pointer items area */
tablesPoi:
ptApples: .int szString1
ptOranges: .int szString2
ptVoid: .int 0
 
/* UnInitialized data */
.bss
 
/* code section */
.text
.global main
main: /* entry of program */
push {fp,lr} /* saves 2 registers */
 
ldr r1,iAdrtablesPoi @ begin pointer table
mov r0,#0 @ counter
1: @ begin loop
ldr r2,[r1,r0,lsl #2] @ read string pointer address item r0 (4 bytes by pointer)
cmp r2,#0 @ is null ?
addne r0,#1 @ no increment counter
bne 1b @ and loop
ldr r1,iAdrsZoneconv @ conversion decimal
bl conversion10S
ldr r0,iAdrszMessLenArea
bl affichageMess
2:
 
100: /* standard end of the program */
mov r0, #0 @ return code
pop {fp,lr} @restaur 2 registers
mov r7, #EXIT @ request to exit program
swi 0 @ perform the system call
iAdrtablesPoi: .int tablesPoi
iAdrszMessLenArea: .int szMessLenArea
iAdrsZoneconv: .int sZoneconv
iAdrszCarriageReturn: .int szCarriageReturn
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {fp,lr} /* save registres */
push {r0,r1,r2,r7} /* save others registers */
mov r2,#0 /* counter length */
1: /* loop length calculation */
ldrb r1,[r0,r2] /* read octet start position + index */
cmp r1,#0 /* if 0 its over */
addne r2,r2,#1 /* else add 1 in the length */
bne 1b /* and loop */
/* so here r2 contains the length of the message */
mov r1,r0 /* address message in r1 */
mov r0,#STDOUT /* code to write to the standard output Linux */
mov r7, #WRITE /* code call system "write" */
swi #0 /* call systeme */
pop {r0,r1,r2,r7} /* restaur others registers */
pop {fp,lr} /* restaur des 2 registres */
bx lr /* return */
 
/***************************************************/
/* conversion register signed décimal */
/***************************************************/
/* r0 contient le registre */
/* r1 contient l adresse de la zone de conversion */
conversion10S:
push {r0-r5,lr} /* save des registres */
mov r2,r1 /* debut zone stockage */
mov r5,#'+' /* par defaut le signe est + */
cmp r0,#0 /* nombre négatif ? */
movlt r5,#'-' /* oui le signe est - */
mvnlt r0,r0 /* et inversion en valeur positive */
addlt r0,#1
mov r4,#10 /* longueur de la zone */
1: /* debut de boucle de conversion */
bl divisionpar10 /* division */
add r1,#48 /* ajout de 48 au reste pour conversion ascii */
strb r1,[r2,r4] /* stockage du byte en début de zone r5 + la position r4 */
sub r4,r4,#1 /* position précedente */
cmp r0,#0
bne 1b /* boucle si quotient different de zéro */
strb r5,[r2,r4] /* stockage du signe à la position courante */
subs r4,r4,#1 /* position précedente */
blt 100f /* si r4 < 0 fin */
/* sinon il faut completer le debut de la zone avec des blancs */
mov r3,#' ' /* caractere espace */
2:
strb r3,[r2,r4] /* stockage du byte */
subs r4,r4,#1 /* position précedente */
bge 2b /* boucle si r4 plus grand ou egal a zero */
100: /* fin standard de la fonction */
pop {r0-r5,lr} /*restaur desregistres */
bx lr
 
/***************************************************/
/* division par 10 signé */
/* Thanks to http://thinkingeek.com/arm-assembler-raspberry-pi/*
/* and http://www.hackersdelight.org/ */
/***************************************************/
/* r0 contient le dividende */
/* r0 retourne le quotient */
/* r1 retourne le reste */
divisionpar10:
/* r0 contains the argument to be divided by 10 */
push {r2-r4} /* save registers */
mov r4,r0
ldr r3, .Ls_magic_number_10 /* r1 <- magic_number */
smull r1, r2, r3, r0 /* r1 <- Lower32Bits(r1*r0). r2 <- Upper32Bits(r1*r0) */
mov r2, r2, ASR #2 /* r2 <- r2 >> 2 */
mov r1, r0, LSR #31 /* r1 <- r0 >> 31 */
add r0, r2, r1 /* r0 <- r2 + r1 */
add r2,r0,r0, lsl #2 /* r2 <- r0 * 5 */
sub r1,r4,r2, lsl #1 /* r1 <- r4 - (r2 * 2) = r4 - (r0 * 10) */
pop {r2-r4}
bx lr /* leave function */
bx lr /* leave function */
.Ls_magic_number_10: .word 0x66666667
 
</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">fruit: ["apple" "orange"]
 
print ["array length =" size fruit]</syntaxhighlight>
{{out}}
 
<pre>array length = 2</pre>
 
=={{header|ATS}}==
<syntaxhighlight lang="ats">
#include
"share/atspre_staload.hats"
#include
"share/atspre_staload_libats_ML.hats"
 
val A0 =
array0_tuple<string>
( "apple", "orange" )
val () =
println!("length(A0) = ", length(A0))
 
implement main0((*void*)) = ((*void*))
</syntaxhighlight>
 
=={{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 139 ⟶ 456:
ConsoleWrite("aArray[" & $i & "] = '" & $aArray[$i] & "'" & @CRLF)
Next
</syntaxhighlight>
</lang>
{{Out}}
<pre>Elements in array: 2
aArray[0] = 'Apple'
aArray[1] = 'Orange'</pre>
 
=={{header|Avail}}==
 
Using Avail's tuples and the `|_|` method:
 
<syntaxhighlight lang="avail">|<"Apple", "Orange">|</syntaxhighlight>
 
=={{header|AWK}}==
Line 152 ⟶ 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 166 ⟶ 489:
print "String length:", array[1], length(array[1])
}</langsyntaxhighlight>
 
{{out}}
Line 173 ⟶ 496:
String length: apple 5
</pre>
 
=={{header|BaCon}}==
BaCon knows three types of arrays, the UBOUND function can query all.
<syntaxhighlight lang="bacon">' Static arrays
 
DECLARE fruit$[] = { "apple", "orange" }
PRINT UBOUND(fruit$)
 
' Dynamic arrays
 
DECLARE vegetable$ ARRAY 2
vegetable$[0] = "cabbage"
vegetable$[1] = "spinach"
PRINT UBOUND(vegetable$)
 
' Associative arrays
 
DECLARE meat$ ASSOC STRING
meat$("first") = "chicken"
meat$("second") = "pork"
PRINT UBOUND(meat$)</syntaxhighlight>
 
=={{header|Bash}}==
 
<syntaxhighlight lang="bash">
fruit=("apple" "orange" "lemon")
echo "${#fruit[@]}"</syntaxhighlight>
 
=={{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}}===
<syntaxhighlight lang="basic">10 DIM A$(2)
20 A$(1) = "ORANGE"
30 A$(2) = "APPLE"
40 N$ = "A$": GOSUB 70: PRINT L$
 
60 PRINT
61 DIM A%(19,63,0),A3(4,5)
62 N$ = "A%": GOSUB 70: PRINT L$
63 N$ = "A3": GOSUB 70: PRINT L$
64 N$ = "COMMODORE"
65 GOSUB 70: PRINT L$: END
 
70 L$ = "":N0 = 0:N1 = 0
71 N0$ = LEFT$ (N$,1)
72 N1$ = MID$ (N$,2,2)
73 N1 = RIGHT$ (N$,1) = "$"
74 N0 = RIGHT$ (N$,1) = "%"
75 IF N0 THEN N1 = 1
76 I = LEN (N1$) - N1
77 N1$ = MID$ (N1$,1,I)
78 A = ASC (N1$ + CHR$ (0))
79 N1 = 128 * N1 + A
80 N0 = 128 * N0 + ASC (N0$)
90 DEF FN P(A) = PEEK (A) + PEEK (A + 1) * 256
100 I = FN P(109):A = FN P(107)
110 FOR A = A TO I STEP 0
128 IF PEEK (A) < > N0 OR PEEK (A + 1) < > N1 THEN A = A + FN P(A + 2): NEXT A: PRINT "ARRAY "N$" NOT FOUND": STOP
130 N0 = A + 4
140 N1 = N0 + FN P(N0) * 2
150 N0 = N0 + 2
160 FOR I = N1 TO N0 STEP - 2
170 L$ = L$ + STR$ ( FN P(I))
180 L$ = L$ + " ": NEXT I
190 RETURN</syntaxhighlight>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic256">
fruta$ = {"apple", "orange", "pear"}
print length(fruta$)
print fruta$[?]
print fruta$[1]
end
</syntaxhighlight>
<pre>
3
3
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}}
<syntaxhighlight lang="basic">10 DIM A$(1):REM 1=LAST -> ROOM FOR 2
20 A$(0) = "ORANGE"
30 A$(1) = "APPLE"
40 AT=0:N$="":T=0:L=0:REM DECLARE ALL VARS BEFORE PEEKING
50 AT=PEEK(47)+256*PEEK(48):REM START OF ARRAYS IN MEMORY
60 N$=CHR$(PEEK(AT)AND127)+CHR$(PEEK(AT+1)AND127):REM NAME
70 T=(PEEK(AT) AND 128)*2+(PEEK(AT+1)AND128):REM TYPE
80 IF T=384 THEN N$=N$+"%": REM INTEGER
90 IF T=128 THEN N$=N$+"$": REM STRING
100 L=PEEK(AT+6): REM FIRST INDEX SIZE
110 PRINT N$" HAS"L"ELEMENTS."</syntaxhighlight>
 
{{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}}===
<syntaxhighlight lang="qbasic">DIM fruta$(2)
READ fruta$(1), fruta$(2)
DATA "apple", "orange"
 
LET tamano = UBound(fruta$) - LBound(fruta$) + 1
 
PRINT "La longitud del array fruta$ es" ; tamano
END</syntaxhighlight>
{{out}}
<pre> La longitud del array fruta$ es 2 </pre>
 
 
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)
MAT READ fruit$
DATA "apple", "orange"
 
PRINT "The length of the array 'fruit$' is "; SIZE(fruit$)
END</syntaxhighlight>
{{out}}
<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 is 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.
 
<syntaxhighlight lang="dos">
@echo off
 
:_main
setlocal enabledelayedexpansion
 
:: This block of code is putting a list delimitered by spaces into an pseudo-array
:: In practice, this could be its own function _createArray however for the demonstration, it is built in
set colour_list=red yellow blue orange green
set array_entry=0
for %%i in (%colour_list%) do (
set /a array_entry+=1
set colours[!array_entry!]=%%i
)
 
call:_arrayLength colours
echo _arrayLength returned %errorlevel%
pause>nul
exit /b
 
:: _arrayLength returns the length of the array parsed to it in the errorcode
:_arrayLength
setlocal enabledelayedexpansion
 
:loop
set /a arrayentry=%arraylength%+1
if "!%1[%arrayentry%]!"=="" exit /b %arraylength%
set /a arraylength+=1
goto loop
</syntaxhighlight>
{{in}}
<pre>
red yellow blue orange green
</pre>
{{out}}
<pre>
_arrayLength returned 5
</pre>
 
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<syntaxhighlight 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</syntaxhighlight>
{{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|CBinary 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.
<syntaxhighlight lang="bqn">≠ 1‿"a"‿+</syntaxhighlight>
<syntaxhighlight lang="bqn">3</syntaxhighlight>
[https://mlochbaum.github.io/BQN/try.html#code=4omgIDHigL8iYSLigL8r Try It!]
 
=={{header|C}}==
===A commonly used solution===
C features two kinds of arrays: static (compile-time, fixed size) and dynamic (allocated at runtime).
 
Line 193 ⟶ 755:
For static arrays:
 
<syntaxhighlight lang="c">
<lang c>
#include <stdio.h>
 
Line 215 ⟶ 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.
Thus, the length of an array parameter may not be required directly - a dedicated length parameter would be required.
 
=={{header|C++}}=Safe solution===
<p>
The C language uses arrays of a declared size (including variable length arrays,
i.e. VLA) and dynamically allocated memory blocks. While they are mostly the same,
it is important that the sizeof operator, which returns a number of bytes,
behaves quite differently for arrays and for memory pointers.
</p><p>
The problem is that arrays are passed to functions (procedures) via pointers.
Even if we define a global variable as an array, after using it as a function
argument the appropriate parameter will "forget" what size the array is.
</p><p>
Therefore, an object-oriented technique is used in the solution below. (This is possible even with standard C, i.e. C without ++.) Block of memory in which is stored the array is wrapped in structure and thus the size of the array can be easily stored. It is very convenient. Having defined such "classes" as StringArray, their use is easy and hassle-free. Nevertheless, the C language is not designed for OOP, and therefore C ++ is simply better for these kinds of applications.
</p>
====Solution====
<syntaxhighlight lang="c">#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings
#define _CRT_NONSTDC_NO_WARNINGS // enable old-gold POSIX names in MSVS
 
#include <stdarg.h>
C++ follows the same rules as C regarding static and dynamic arrays.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
 
However, C++ has an additional std::array type (amongst other collections) in its standard library:
 
struct StringArray
<lang cpp>
{
#include <array>
size_t sizeOfArray;
#include <iostream>
size_t numberOfElements;
#include <string>
char** elements;
};
typedef struct StringArray* StringArray;
 
StringArray StringArray_new(size_t size)
int main()
{
StringArray this = calloc(1, sizeof(struct StringArray));
std::array<std::string, 2> fruit { "apples", "oranges" };
std::coutif << fruit.size(this);
return 0;{
this->elements = calloc(size, sizeof(int));
if (this->elements)
this->sizeOfArray = size;
else
{
free(this);
this = NULL;
}
}
return this;
}
</lang>
 
void StringArray_delete(StringArray* ptr_to_this)
Note that char* or const char* could have been used instead of std::string.
{
assert(ptr_to_this != NULL);
StringArray this = (*ptr_to_this);
if (this)
{
for (size_t i = 0; i < this->sizeOfArray; i++)
free(this->elements[i]);
free(this->elements);
free(this);
this = NULL;
}
}
 
void StringArray_add(StringArray this, ...)
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.
char* s;
<lang cpp>
va_list args;
std::vector<std::string> fruitV({ "apples", "oranges" });
va_start(args, this);
std::list<std::string> fruitL({ "apples", "oranges" });
while (this->numberOfElements < this->sizeOfArray && (s = va_arg(args, char*)))
std::deque<std::string> fruitD({ "apples", "oranges" });
this->elements[this->numberOfElements++] = strdup(s);
std::cout << fruitV.size() << fruitL.size() << fruitD.size() << std::endl;
va_end(args);
</lang>
}
 
 
Of these, vector is probably the most widely used.
int main(int argc, char* argv[])
{
StringArray a = StringArray_new(10);
StringArray_add(a, "apple", "orange", NULL);
 
printf(
"There are %d elements in an array with a capacity of %d elements:\n\n",
a->numberOfElements, a->sizeOfArray);
 
for (size_t i = 0; i < a->numberOfElements; i++)
printf(" the element %d is the string \"%s\"\n", i, a->elements[i]);
 
StringArray_delete(&a);
 
return EXIT_SUCCESS;
}</syntaxhighlight>
{{output}}
<pre>There are 2 elements in an array with a capacity of 10 elements:
 
the element 0 is the string "apple"
the element 1 is the string "orange"</pre>
 
====An example why sizeof(A)/sizeof(E) may be a bad idea in C====
<syntaxhighlight lang="c">#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings
#define _CRT_NONSTDC_NO_WARNINGS // enable old-gold POSIX names in MSVS
 
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 
#define N 10
 
// Fixed size global arrays
 
static const int scGlobal[N];
const int cGlobal[N];
static int sGlobal[N];
int Global[N];
 
#define TEST(A, N) \
do { \
puts(""); \
printf("directly called: sizeof(%8s) = %2d, length = %2d, %s\n",\
#A, \
sizeof(A), \
sizeof(A) / sizeof(int), \
sizeof(A) / sizeof(int) == N ? "pass" : "fail"); \
\
test1(#A, A, N); \
test2(#A, A, N); \
test3(#A, A, N); \
} while (0);
 
void test1(char* name, int* A, int n)
{
printf("as parameter int* A: sizeof(%8s) = %2d, length = %2d, %s\n",
name,
sizeof(A),
sizeof(A) / sizeof(int),
sizeof(A) / sizeof(int) == n ? "pass" : "fail");
}
 
void test2(char* name, int A[], int n)
{
printf("as parameter int A[]: sizeof(%8s) = %2d, length = %2d, %s\n",
name,
sizeof(A),
sizeof(A) / sizeof(int),
sizeof(A) / sizeof(int) == n ? "pass" : "fail");
}
 
void test3(char* name, int A[10], int n)
{
printf("as parameter int A[10]: sizeof(%8s) = %2d, length = %2d, %s\n",
name,
sizeof(A),
sizeof(A) / sizeof(int),
sizeof(A) / sizeof(int) == n ? "pass" : "fail");
}
 
 
int main(int argc, char argv[])
{
// Fixed size local arrays (defined inside curly braces block)
 
static const int scLocal[N];
const int cLocal[N];
static int sLocal[N];
auto int aLocal[N];
int Local[N];
 
// Fixed size VLA arrays can/should be used instead dynamically alocated
// blocks. VLA has not implemented in Microsoft Visual Studio C.
 
srand(time(NULL));
int n = N + rand() % 2; // the value of n is unknow in the compile time?
 
#ifndef _MSC_VER
int vlaLocal[n];
#endif
 
// Memory blocks as ersatz arrays. This is not all possible ways to allocate
// memory. There are other functions, like LocalAlloc, HeapAlloc, sbreak...
// Don't use alloca in any serious program - this function is really bad
// choice - it can corrupt the program stack and generate a stack overflow.
 
int* mBlock = (int*)malloc(n * sizeof(int));
int* cBlock = (int*)calloc(n, sizeof(int));
int* aBlock = (int*)_alloca(n * sizeof(int)); // don't use in your programs!
 
TEST(scGlobal, N);
TEST(cGlobal, N);
TEST(sGlobal, N);
TEST(Global, N);
 
TEST(scLocal, N);
TEST(cLocal, N);
TEST(sLocal, N);
TEST(aLocal, N);
TEST(Local, N);
 
#ifndef _MSC_VER
TEST(vlaLocal, n);
#endif
 
TEST(mBlock, N);
TEST(cBlock, N);
TEST(aBlock, N);
 
free(mBlock, N);
free(cBlock, N);
// free must not be called on aBlock
 
return 0;
}</syntaxhighlight>
<p>
As we can see the ''sizeof(ArrayType)/sizeof(ElementType)'' approach mostly fail.
</p>
{{output}}
<pre>directly called: sizeof(scGlobal) = 40, length = 10, pass
as parameter int* A: sizeof(scGlobal) = 4, length = 1, fail
as parameter int A[]: sizeof(scGlobal) = 4, length = 1, fail
as parameter int A[10]: sizeof(scGlobal) = 4, length = 1, fail
 
directly called: sizeof( cGlobal) = 40, length = 10, pass
as parameter int* A: sizeof( cGlobal) = 4, length = 1, fail
as parameter int A[]: sizeof( cGlobal) = 4, length = 1, fail
as parameter int A[10]: sizeof( cGlobal) = 4, length = 1, fail
 
directly called: sizeof( sGlobal) = 40, length = 10, pass
as parameter int* A: sizeof( sGlobal) = 4, length = 1, fail
as parameter int A[]: sizeof( sGlobal) = 4, length = 1, fail
as parameter int A[10]: sizeof( sGlobal) = 4, length = 1, fail
 
directly called: sizeof( Global) = 40, length = 10, pass
as parameter int* A: sizeof( Global) = 4, length = 1, fail
as parameter int A[]: sizeof( Global) = 4, length = 1, fail
as parameter int A[10]: sizeof( Global) = 4, length = 1, fail
 
directly called: sizeof( scLocal) = 40, length = 10, pass
as parameter int* A: sizeof( scLocal) = 4, length = 1, fail
as parameter int A[]: sizeof( scLocal) = 4, length = 1, fail
as parameter int A[10]: sizeof( scLocal) = 4, length = 1, fail
 
directly called: sizeof( cLocal) = 40, length = 10, pass
as parameter int* A: sizeof( cLocal) = 4, length = 1, fail
as parameter int A[]: sizeof( cLocal) = 4, length = 1, fail
as parameter int A[10]: sizeof( cLocal) = 4, length = 1, fail
 
directly called: sizeof( sLocal) = 40, length = 10, pass
as parameter int* A: sizeof( sLocal) = 4, length = 1, fail
as parameter int A[]: sizeof( sLocal) = 4, length = 1, fail
as parameter int A[10]: sizeof( sLocal) = 4, length = 1, fail
 
directly called: sizeof( aLocal) = 40, length = 10, pass
as parameter int* A: sizeof( aLocal) = 4, length = 1, fail
as parameter int A[]: sizeof( aLocal) = 4, length = 1, fail
as parameter int A[10]: sizeof( aLocal) = 4, length = 1, fail
 
directly called: sizeof( Local) = 40, length = 10, pass
as parameter int* A: sizeof( Local) = 4, length = 1, fail
as parameter int A[]: sizeof( Local) = 4, length = 1, fail
as parameter int A[10]: sizeof( Local) = 4, length = 1, fail
 
directly called: sizeof( mBlock) = 4, length = 1, fail
as parameter int* A: sizeof( mBlock) = 4, length = 1, fail
as parameter int A[]: sizeof( mBlock) = 4, length = 1, fail
as parameter int A[10]: sizeof( mBlock) = 4, length = 1, fail
 
directly called: sizeof( cBlock) = 4, length = 1, fail
as parameter int* A: sizeof( cBlock) = 4, length = 1, fail
as parameter int A[]: sizeof( cBlock) = 4, length = 1, fail
as parameter int A[10]: sizeof( cBlock) = 4, length = 1, fail
 
directly called: sizeof( aBlock) = 4, length = 1, fail
as parameter int* A: sizeof( aBlock) = 4, length = 1, fail
as parameter int A[]: sizeof( aBlock) = 4, length = 1, fail
as parameter int A[10]: sizeof( aBlock) = 4, length = 1, fail</pre>
 
=={{header|C sharp|C#}}==
 
<langsyntaxhighlight lang="csharp">
using System;
 
Line 271 ⟶ 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 281 ⟶ 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 295 ⟶ 1,098:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
 
C++ follows the same rules as C regarding static and dynamic arrays.
 
However, C++ has an additional <code>std::array</code> type (amongst other collections) in its standard library:
 
<syntaxhighlight lang="cpp">#include <array>
#include <iostream>
#include <string>
 
int main()
{
std::array<std::string, 2> fruit { "apples", "oranges" };
std::cout << fruit.size();
return 0;
}</syntaxhighlight>
 
Note that <code>char*</code> or <code>const char*</code> could have been used instead of <code>std::string</code>.
 
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.
<syntaxhighlight 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;</syntaxhighlight>
 
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 315 ⟶ 1,146:
? LEN(FRUIT)
RETURN
</syntaxhighlight>
</lang>
Outputs:<pre>2</pre>
[[User:nizchka|nizchka]] 23:27, 16 March 2016 (UTC)
Line 321 ⟶ 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 369 ⟶ 1,200:
.
 
end program array-length.</langsyntaxhighlight>
{{out}}
<pre>$ cobc -xjd array-length.cob
Line 378 ⟶ 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]
 
<syntaxhighlight lang="lisp">
;; Project : Array length
 
(setf my-array (make-array '(2)))
(setf (aref my-array 0) "apple")
(setf (aref my-array 1) "orange")
(format t "~a" "length of my-array: ")
(length my-array)
(terpri)
</syntaxhighlight>
Output:
<pre>
length of my-array: 2
</pre>
 
=={{header|Component Pascal}}==
{{works with|BlackBox Component Builder}}
<syntaxhighlight lang="oberon2">
MODULE AryLen;
IMPORT StdLog;
 
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,LEN(s$) + 1);str^ := s$; RETURN str
END NewString;
 
PROCEDURE Length(a: ARRAY OF String): INTEGER;
VAR
i: INTEGER;
BEGIN
i := 0;
WHILE a[i] # NIL DO INC(i) END;
RETURN i
END Length;
 
PROCEDURE Do*;
BEGIN
a[0] := NewString("Apple");
a[1] := NewString("Orange");
StdLog.String("Length:> ");StdLog.Int(Length(a));StdLog.Ln
END Do;
 
END AryLen.
</syntaxhighlight>
Execute: ^Q AryLen.Do
{{out}}
<pre>
Length:> 2
</pre>
 
=={{header|Crystal}}==
 
<syntaxhighlight lang="ruby">
puts ["apple", "orange"].size
</syntaxhighlight>
 
{{out}}
<pre>
2
</pre>
 
=={{header|D}}==
<syntaxhighlight lang="d">
<lang d>
import std.stdio;
 
Line 401 ⟶ 1,301:
return 0;
}
</syntaxhighlight>
</lang>
 
Or a somewhat shorter...
<syntaxhighlight lang="d">
<lang d>
import std.stdio;
 
Line 411 ⟶ 1,311:
["apple", "orange"].length.writeln;
}
</syntaxhighlight>
</lang>
 
=={{header|DWScriptDart}}==
<syntaxhighlight lang="dart">
<lang delphi>
arrLength(arr) {
var a := ['apple', 'orange'];
return arr.length;
PrintLn(a.Length);
}
</lang>
 
main() {
var fruits = ['apple', 'orange'];
print(arrLength(fruits));
}
 
</syntaxhighlight>
 
=={{header|DataWeave}}==
<syntaxhighlight lang="dataweave">var arr = ["apple", "orange"]
sizeOf(arr)
</syntaxhighlight>
 
=={{header|Delphi}}==
<syntaxhighlight lang="delphi">
showmessage( length(['a','b','c']).ToString );
</syntaxhighlight>
 
=={{header|Diego}}==
<syntaxhighlight lang="diego">set_namespace(rosettacode)_me();
 
me_msg()_array()_values(apple,orange)_length();
reset_namespace[];</syntaxhighlight>
{{out}}
<pre>2</pre>
 
=={{header|Dragon}}==
<syntaxhighlight lang="dragon">select "std"
 
a = ["apple","orange"]
b = length(a)
 
show b
</syntaxhighlight>
 
=={{header|dt}}==
<syntaxhighlight lang="dt">[ "apple" "orange" ] len</syntaxhighlight>
 
=={{header|Dyalect}}==
<syntaxhighlight lang="dyalect">var xs = ["apple", "orange"]
print(xs.Length())</syntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="text">fruit$[] = [ "apples" "oranges" ]
print len fruit$[]</syntaxhighlight>
 
=={{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 :
<syntaxhighlight lang="elena">
var array := new string[]{"apple", "orange"};
var length := array.Length;
</syntaxhighlight>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">iex(1)> length( ["apple", "orange"] ) # List
2
iex(2)> tuple_size( {"apple", "orange"} ) # Tuple
2</syntaxhighlight>
 
=={{header|Elm}}==
<langsyntaxhighlight lang="elm">
import Array
import Html
Line 440 ⟶ 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|ElenaEMal}}==
<syntaxhighlight lang="emal">
<lang elena>
#var a := writeLine(text["apple", "orange"].length).
</syntaxhighlight>
#var length := a length.
</lang>
 
=={{header|ElixirErlang}}==
<syntaxhighlight lang="erlang">
<lang elixir>iex(1)> length( ["apple", "orange"] ) # List
1> length(["apple", "orange"]). %using a list
2
iex(2)1> tuple_size( {"apple", "orange"} ). %using a # Tupletuple
2
2</lang>
</syntaxhighlight>
 
=={{header|Frink}}==
<lang frink>
a = ["apple", "orange"]
println[length[a]]
</lang>
 
=={{header|ForthEuphoria}}==
<syntaxhighlight lang="euphoria">
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.
sequence s = {"apple","orange",2.95} -- Euphoria doesn't care what you put in a sequence
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.
 
? length(s)
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.
 
3 -- three objects
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.
 
? length(s[1])
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.
 
5 -- apple has 5 characters
<lang>: STRING, ( addr len -- ) \ allocate space & compile string into memory
here over 1+ allot place ;
 
? length(s[1][$])
: ," ( -- ) [CHAR] " PARSE STRING, ; \ Parse input to " and compile to memory
 
1 -- 'e' is an atomic value
\ 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 ;
 
? length(s[$])
: 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
 
1 -- 2.95 is an atomic value
 
</syntaxhighlight>
\ 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
<PRE>
 
=={{header|F_Sharp|F#}}==
Q items . 2 ok
<syntaxhighlight lang="fsharp">[|1;2;3|].Length |> printfn "%i"</syntaxhighlight>
W items . 5 ok
Or:
</PRE>
<syntaxhighlight lang="fsharp">[|1;2;3|] |> Array.length |> printfn "%i"</syntaxhighlight>
 
=={{header|Factor}}==
<syntaxhighlight lang="factor">
{ "apple" "orange" } length
</syntaxhighlight>
 
=={{header|Fennel}}==
<syntaxhighlight lang="fennel">(length [:apple :orange])</syntaxhighlight>
 
=={{header|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. His solution was to distill his language into a large set of very simple routines that control the hardware directly.
This demonstration 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.
 
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 ;
 
: " ( -- ) [CHAR] " PARSE STRING, ; \ Parse input to " and compile to memory
 
\ Array delimiter words
: { ALIGN 0 C, ; \ Compile 0 byte start/end of array
: } ALIGN 0 C, ;
 
\ String array words
: {NEXT} ( str -- next_str) \ Iterate to next string
COUNT + ;
 
: {NTH} ( n array_addr -- str) \ Returns address of the Nth item in the array
SWAP 0 DO {NEXT} LOOP ;
 
: {LEN} ( array_addr -- n) \ count strings in the array
0 >R \ Counter on Rstack
{NEXT}
BEGIN
DUP C@ \ Fetch length byte
WHILE \ While true
R> 1+ >R \ Inc. counter
{NEXT}
REPEAT
DROP
R> ; \ return counter to data stack </syntaxhighlight>
Test code at Forth console
<syntaxhighlight lang="forth">CREATE Q { " Apples" " Oranges" } q {len} . 2 ok</syntaxhighlight>
 
=={{header|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 <code>PRINT A</code> would print all the elements of a variable <code>A</code> according to its definition. A subprogram that received a parameter would have no access to these details, so its parameter might be declared as <code>A(12345)</code> 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 <code>A(*)</code> 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 - Fortran stores array elements in [[Array#Fortran|column-major]] order.
 
With Fortran 90, a new protocol was introduced, whereby the parameter might be declared as <code>A(:)</code> signifying an array of one dimension, of bounds unstated. A 2-D array would have <code>A(:,:)</code> and so on. Further, arrays could have arbitrary lower bounds as well, as in <code>A(-7:12)</code> but if no colon appeared for a dimension, the lower bound would be assumed to be one so <code>A(2)</code> means an array of two elements, as before. And as before, in a subprogram a bound could be explicitly stated, perhaps via an explicit parameter such as <code>N</code>, but now with the <code>:</code> 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 <code>UBOUND(A,DIM = 2)</code> 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.
Line 522 ⟶ 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 543 ⟶ 1,533:
WRITE (6,*) "L. bound",LBOUND(ARRAY),", U. bound",UBOUND(ARRAY)
END
</syntaxhighlight>
</lang>
 
Output:
Line 552 ⟶ 1,542:
L. bound -1 , U. bound 1
 
Notice that the subprogram sees the array as an old-style array starting with index one! If it is to work with a lower bound other than one, the declaration in the subprogram must state it, perhaps as A(-1:) or as A(START:), ''etc''. The upper bound remains unspecified, and with that declaration, UBOUND returns 1 instead of 3, corresponding to the shift. Thus, UBOUND returns not the actual upper bound of the array parameter (as supplied) but the upper bound relative to the lower bound in use ''in'' the subprogram so that UBOUND - LBOUND + 1 does give the number of elements.
Notice that the subprogram sees the array as an old-style array starting with index one!
 
If in the subprogram the bounds are fixed (say as <code>A(-1:6)</code>) then a CALL ABOUND(ARRAY) may provoke a compiler complaint if ARRAY is not a suitable size.
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim fruit(1) As String = {"apple", "orange"}
Dim length As Integer = UBound(fruit) - LBound(fruit) + 1
Print "The length of the fruit array is"; length
Print
Print "Press any key to quit the program"
Sleep</syntaxhighlight>
 
{{out}}
<pre>
The length of the fruit array is 2
</pre>
 
=={{header|Frink}}==
<syntaxhighlight lang="frink">
a = ["apple", "orange"]
println[length[a]]
</syntaxhighlight>
 
=={{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|F_Sharp|F#}}==
<lang fsharp>[|1;2;3|].Length |> printfn "%i"</lang>
Or:
<lang fsharp>[|1;2;3|] |> Array.length |> printfn "%i"</lang>
 
=={{header|Futhark}}==
{{needs-review|Futhark}}
 
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:
<syntaxhighlight lang="futurebasic">
window 1
print fn ArrayCount( @[@"apple",@"orange",@"cherry",@"grape",@"lemon"] )
HandleEvents
</syntaxhighlight>
 
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>
5
</pre>
 
=={{header|Fōrmulæ}}==
 
{{FormulaeEntry|page=https://formulae.org/?script=examples/Array_length}}
 
'''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]]
 
[[File:Fōrmulæ - Array length 02.png]]
 
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=2a452c807c7030eb64a2f1d60d31a830 Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim siList As Short[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
 
Print siList.Count
 
End</syntaxhighlight>
Output:
<pre>
10
</pre>
 
=={{header|Genie}}==
<syntaxhighlight lang="genie">[indent=4]
/* Array length, in Genie */
init
arr:array of string = {"apple", "orange"}
stdout.printf("%d ", arr.length)
print arr[1]</syntaxhighlight>
 
{{out}}
<pre>prompt$ valac array_length.gs
prompt$ ./array_length
2 orange</pre>
 
=={{header|Go}}==
 
<langsyntaxhighlight Golang="go">package main
 
import "fmt"
Line 584 ⟶ 1,655:
 
fmt.Printf("Length of %v is %v.\n", arr, len(arr))
}</langsyntaxhighlight>
 
 
{{out}}
<pre>
Length of [apple orange pear] is 3.
</pre>
 
=={{header|Groovy}}==
 
<syntaxhighlight lang="groovy">
<lang Groovy>
def fruits = ['apple','orange']
println fruits.size()
</syntaxhighlight>
</lang>
 
=={{header|FutureBasicHarbour}}==
 
<syntaxhighlight lang="visualfoxpro">
<lang futurebasic>
LOCAL aFruits := {"apple", "orange"}
include "ConsoleWindow"
Qout( Len( aFruits ) ) // --> 2
</syntaxhighlight>
 
=={{header|Haskell}}==
dim as CFArrayRef array
dim as Str255 s
dim as CFStringRef fruits, tempStr
dim as CFIndex ubound, i
 
<syntaxhighlight lang="haskell">-- [[Char]] -> Int
fruits = @"apples,bananas,cherries,dates,grapes,lemon,lime,orange,peach,pear,pineapple,strawberries,watermelon"
length ["apple", "orange"]</syntaxhighlight>
array = fn CFStringCreateArrayBySeparatingStrings( _kCFAllocatorDefault, fruits, @"," )
 
=={{header|hexiscript}}==
ubound = fn CFArrayGetCount( array )
<syntaxhighlight lang="hexiscript">let a arr 2
for i = 0 to ubound - 1
let a[0] "apple"
tempStr = fn CFArrayGetValueAtIndex( array, i )
let a[1] "orange"
fn CFStringGetPascalString( tempStr, @s, 256, _kCFStringEncodingMacRoman )
println len a</syntaxhighlight>
CFRelease( tempStr )
print "Fruit"; i; " = "; s
next
</lang>
Output:
<pre>
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
</pre>
 
=={{header|HaskellHoon}}==
<syntaxhighlight lang="hoon">|= arr=(list *) (lent arr)</syntaxhighlight>
 
=={{header|i}}==
<lang Haskell>-- [[Char]] -> Int
length<syntaxhighlight lang="i">main: print(#["apple", "orange"])</langsyntaxhighlight>
 
=={{header|IIcon}} 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.
In I, strings need to be hashed in order to be stored in an array.
 
<lang i>software {
var a<syntaxhighlight lang= "unicon">write(*["apple"#255, "orange"#255])</syntaxhighlight>
print(len(a))
}</lang>
 
=={{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 664 ⟶ 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 679 ⟶ 1,738:
1
#$>'apple';'orange'
2</langsyntaxhighlight>
 
=={{header|Janet}}==
 
<syntaxhighlight lang="janet">
(def our-array @["apple" "orange"])
(length our-array)
</syntaxhighlight>
 
{{out}}
<pre>
2
</pre>
 
=={{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 696 ⟶ 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 704 ⟶ 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}}==
<syntaxhighlight lang="javascript">/* Array length, in jsish */
var arr = new Array('apple', 'orange');
puts(arr.length);
puts(arr[1]);</syntaxhighlight>
 
{{out}}
<pre>prompt$ jsish arrayLength.jsi
2
orange</pre>
 
=={{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}}==
<syntaxhighlight lang="klingphix">include ..\Utilitys.tlhy
 
( "apple" "orange" ) len print
 
" " input</syntaxhighlight>
{{out}}
<pre>2</pre>
 
=={{header|Klong}}==
 
<syntaxhighlight lang="k">
#["apple" "orange"]
</syntaxhighlight>
 
=={{header|Kotlin}}==
 
<syntaxhighlight lang="scala">fun main(args: Array<String>) {
<lang Kotlin>
fun main(args: Array<String>) {
println(arrayOf("apple", "orange").size)
}</syntaxhighlight>
}
 
</lang>
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
{A.length {A.new 1 2 3}}
-> 3
</syntaxhighlight>
 
=={{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}}==
 
In Latitude, <code>length</code> and <code>size</code> are synonymous and will both retrieve the size of a collection.
 
<syntaxhighlight lang="latitude">println: ["apple", "orange"] length.</syntaxhighlight>
 
=={{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 753 ⟶ 1,904:
 
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 866 ⟶ 2,017:
print ")"
end sub
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 873 ⟶ 2,024:
DIM array$(10)
</pre>
 
=={{header|LIL}}==
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.
 
<syntaxhighlight lang="tcl"># Array length, in LIL
set a [list "apple"]
append a "orange"
print [count $a]
print [index $a 1]</syntaxhighlight>
 
{{out}}
<pre>prompt$ lil arrayLength.lil
2
orange</pre>
 
=={{header|Limbo}}==
<syntaxhighlight lang="limbo">implement Command;
 
include "sys.m";
sys: Sys;
 
include "draw.m";
 
include "sh.m";
 
init(nil: ref Draw->Context, nil: list of string)
{
sys = load Sys Sys->PATH;
 
a := array[] of {"apple", "orange"};
sys->print("length of a: %d\n", len a);
}</syntaxhighlight>
 
=={{header|Lingo}}==
<syntaxhighlight lang="lingo">fruits = ["apple", "orange"]
put fruits.count
-- 2</syntaxhighlight>
 
=={{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}}==
<syntaxhighlight lang="lua">-- For tables as simple arrays, use the # operator:
<lang Lua>
-- For tables as simple arrays, use the # operator:
fruits = {"apple", "orange"}
print(#fruits)
Line 896 ⟶ 2,083:
-- 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))</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 911 ⟶ 2,097:
2
</pre>
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
\\ A is a pointer to array
A=("Apple", "Orange")
Print Len(A)=2 ' True
Print Dimension(A, 0) ' LBound (0 or 1), here 0
Print Dimension(A) ' No of Dimensions 1
Print Dimension(A, 1) ' for 1 dimension array this is also Length=2
\\ A$( ) is an Array (not a pointer to array)
Dim Base 1, A$(2)
A$(1)="Apple", "Orange"
Print Dimension(A$(), 0) ' LBound (0 or 1), here 1
Print Dimension(A$()) ' No of Dimensions 1
Print Dimension(A$(), 1) ' for 1 dimension array this is also Length=2
Link A to B$() ' B$() is a reference to A
Print B$(0)=A$(1)
Print B$(1)=A$(2)
Dim C$()
\\ C$() get a copy of B$()
C$()=B$()
Print C$() ' prints Apple Orange
\\ An array can link to a new name as reference, and can change major type
\\ here A$() get A() so we can read/store numbers and read/store strings in same array
\\ using two names
Link A$() to A()
\\ An array pointer can point to another array
A=A()
Print Dimension(A, 0) ' LBound (0 or 1), here 1 (was 0)
\\ Because B$() is reference of A:
Print Dimension(B$(), 0) ' LBound (0 or 1), here 1 (was 0)
Print B$(1)=A$(1)
Print B$(2)=A$(2)
Print Dimension(C$(), 0) ' LBound (0 or 1), here 0
\\ change base preserve items
Dim Base 1, C$(Dimension(C$(), 1))
Print Dimension(C$(), 0) ' LBound (0 or 1), here 1 (was 0)
Print C$() ' prints Apple Orange
Print Len(C$()) ' Len return all items of an array - can be 0
Dim K(1,1,1,1,1,1) ' Maximum 10 dimensions
Print Len(K()=1 ' True
</syntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight lang="maple">a := Array(["apple", "orange"]);
numelems(a);</langsyntaxhighlight>
{{out}}
<pre>
Line 921 ⟶ 2,149:
</pre>
 
=={{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}}==
<syntaxhighlight lang="modula3">MODULE ArrayLength EXPORTS Main;
 
IMPORT IO;
 
VAR
Arr:ARRAY[1..2] OF TEXT :=
ARRAY[1..2] OF TEXT{"apples", "oranges"};
BEGIN
IO.PutInt(NUMBER(Arr));
END ArrayLength.</syntaxhighlight>
 
=={{header|Mercury}}==
<syntaxhighlight lang="mercury">:- module array_length.
:- interface.
 
:- import_module io.
:- pred main(io::di, io::uo) is det.
 
:- implementation.
 
:- import_module array, list.
 
main(!IO) :-
Array = array(["apples", "oranges"]),
io.write_int(size(Array), !IO).</syntaxhighlight>
 
=={{header|min}}==
{{works with|min|0.19.3}}
<syntaxhighlight lang="min">("apple" "orange") size print</syntaxhighlight>
{{out}}
<pre>
2
</pre>
 
=={{header|MiniScript}}==
<syntaxhighlight lang="miniscript">
fruits = ["apple", "orange"]
print fruits.len
</syntaxhighlight>
=={{header|MiniZinc}}==
<syntaxhighlight lang="minizinc">
array[int] of int: arr = [1,2,3];
var int: size = length(arr);
 
solve satisfy;
 
output [show(size),"\n"];
</syntaxhighlight>
 
=={{header|Nanoquery}}==
<syntaxhighlight lang="nanoquery">fruit = array(2)
fruit[0] = "apple"
fruit[1] = "orange"
println len(fruit)
 
// outputs 2</syntaxhighlight>
 
=={{header|Neko}}==
<langsyntaxhighlight lang="neko">var fruit = $array("apple", "orange");
 
$print($asize(fruit));</langsyntaxhighlight>
 
=={{header|NewLISP}}==
<syntaxhighlight lang="newlisp">(println (length '("apple" "orange")))
 
; Nehal-Singhal 2018-05-25
(length '(apple orange))</syntaxhighlight>
 
=={{header|NGS}}==
<langsyntaxhighlight NGSlang="ngs">echo(len(['apple', 'orange']))
# same
echo(['apple', 'orange'].len())</langsyntaxhighlight>
 
=={{header|NewLISP}}==
<lang newslisp>(println (length '("apple" "orange")))</lang>
 
=={{header|Nim}}==
<syntaxhighlight lang="nim">let fruit = ["apple", "orange"]
<lang nim>
echo "The length of the fruit array is ", len(fruit)</syntaxhighlight>
let fruit = ["apple", "orange"]
echo "The length of the fruit array is ", len(fruit)
</lang>
 
{{out}}
Line 952 ⟶ 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 987 ⟶ 2,293:
Out.String("length: ");Out.Int(Length(a),0);Out.Ln
END ArrayLength.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 994 ⟶ 2,300:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class Test {
function : Main(args : String[]) ~ Nil {
Line 1,000 ⟶ 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.
<syntaxhighlight lang="scheme">
(print (vector-length (vector "apple" "orange")))
(print (vector-length #("apple" "orange")))
(print (vector-length ["apple" "orange"]))
 
(print (size #("apple" "orange")))
</syntaxhighlight>
 
=={{header|OmniMark}}==
In OmniMark, From [https://developers.stilo.com/docs/html/concept/629.html OmniMark v12 documentation]:<br>
<big>"</big>&#xa0;<small>Most programming languages allow programmers to store and manipulate values in arrays, associative arrays, queues, and stacks. Instead, OmniMark provides a data container called a shelf: a shelf can be used to accomplish all of the tasks normally carried out by these various structures in other programming languages. Like arrays, shelves can be indexed by numeric values that reflect the position of the elements they contain or, like associative arrays, these elements can be given names (keys) and then indexed by those keys.</small>&#xa0;<big>"</big>
 
<syntaxhighlight lang="omnimark">
process
local stream s variable initial {"apple", "orange"}
local integer i initial {number of s}
put #main-output 'The number of fruit elements is %d(i).'
</syntaxhighlight>
 
'''Output:'''
<pre>
The number of fruit elements is 2.
</pre>
 
=={{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 1,023 ⟶ 2,354:
say e
End
Say "a[2]="a[2]</langsyntaxhighlight>
{{out}}
<pre>2 elements
Line 1,031 ⟶ 2,362:
 
=={{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 1,043 ⟶ 2,374:
{{works with|Free Pascal|2.6.2}}
 
<syntaxhighlight lang="pascal">
<lang Pascal>
#!/usr/bin/instantfpc
//program ArrayLength;
Line 1,058 ⟶ 2,389:
WriteLn('Length of Fruits by bounds : ', High(Fruits) - Low(Fruits) + 1);
END.
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,066 ⟶ 2,397:
Length of Fruits by bounds : 2
 
</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>
 
Modern way:
<syntaxhighlight lang="pascal">
// Array length. Mikhalkovich Stanislav: May 16, 2024
##
var a := |'apple','orange'|;
a.Length.Print;
</syntaxhighlight>
{{out}}
<pre>
2
</pre>
 
Line 1,072 ⟶ 2,428:
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 1,091 ⟶ 2,447:
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 perl6lang="perl">length '' . @array; # 1
length @array; # 1
 
Line 1,106 ⟶ 2,462:
print 'the length of @array is on the order of ';
print 10 ** (length( @array )-1); # 100
print " elements long\n";</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
{{libheader|Phix/basics}}
{{works with|Rakudo|2015.12}}
<!--<syntaxhighlight lang="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>
To get the number of elements of an array in Perl 6 you put the array in a coercing Numeric context, or call <code>elems</code> on it.
<span style="color: #0000FF;">?<span style="color: #7060A8;">length<span style="color: #0000FF;">(<span style="color: #000000;">fruits<span style="color: #0000FF;">)
 
<!--</syntaxhighlight>-->
<lang perl6>
{{out}}
my @array = <apple orange banana>;
<pre>
 
2
say @array.elems; # 3
</pre>
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.
 
=={{header|Phixmonti}}==
<lang perl6>my @infinite = 1 .. Inf; # 1, 2, 3, 4, ...
<syntaxhighlight lang="phixmonti">"apple" "orange" stklen tolist len print</syntaxhighlight>
 
With syntactic sugar
say @infinite[5000]; # 5001
<syntaxhighlight lang="phixmonti">include ..\Utilitys.pmt
say @infinite.elems; # Throws exception "Cannot .elems a lazy list"
( "apple" "orange" ) len print</syntaxhighlight>
</lang>
 
=={{header|Phix}}==
<lang Phix>constant fruits = {"apple","orange"}
?length(fruits)</lang>
{{out}}
<pre>
Line 1,140 ⟶ 2,487:
=={{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).</syntaxhighlight>
 
{{out}}
<pre>2
2
2
2</pre>
 
 
=={{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 1,158 ⟶ 2,520:
 
=={{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>
Array a has 2 elements.
A(1)='apple ' A(2)='orange';</pre>
 
=={{header|Plorth}}==
<syntaxhighlight lang="plorth">["apple", "orange"] length println</syntaxhighlight>
 
=={{header|Pony}}==
<syntaxhighlight lang="pony">
actor Main
new create(env:Env)=>
var c=Array[String](2)
c.push("apple")
c.push("orange")
env.out.print("Array c is " + c.size().string() + " elements long!")
</syntaxhighlight>
 
=={{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>
2
2</pre>
 
=={{header|Processing}}==
<syntaxhighlight lang="processing">
String[] arr = {"apple", "orange"};
void setup(){
println(arr.length);
}
</syntaxhighlight>
{{out}}
<pre>
2
</pre>
 
==={{header|Processing Python mode}}===
<syntaxhighlight lang="python">
arr = ['apple', 'orange'] # a list for an array
 
def setup():
println(len(arr))
</syntaxhighlight>
 
{{out}}
<pre>
2
</pre>
 
=={{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 1,203 ⟶ 2,603:
CloseConsole()
EndIf
</syntaxhighlight>
</lang>
{{out}}
<pre>
The length of the fruit array is 2
</pre>
 
An abbreviated form of the above, not printing to console/terminal
<syntaxhighlight 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>
{{out}}
<pre>
2
</pre>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">>>> print(len(['apple', 'orange']))
2
>>> </langsyntaxhighlight>
 
=={{header|QB64}}==
 
<syntaxhighlight lang="qb64">
Dim max As Integer, Index As Integer
Randomize Timer
max = Int(Rnd * 10) + 1
Dim StringAr(1 To max) As String
 
For Index = 1 To max
If Int(Rnd * 6) + 1 <= 3 Then StringAr(Index) = "Apple" Else StringAr(Index) = "orange"
Next
Print UBound(Stringar)
End
</syntaxhighlight>
=={{header|Quackery}}==
 
<syntaxhighlight lang="quackery"> $ "apples" $ "oranges" 2 pack size echo</syntaxhighlight>
 
{{out}}
 
<pre>2</pre>
 
=={{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 1,222 ⟶ 2,660:
=={{header|Racket}}==
{{trans|EchoLisp}}
<langsyntaxhighlight lang="racket">#lang racket/base
(length '("apple" "orange")) ;; list
(vector-length #("apple" "orange")) ;; vector</langsyntaxhighlight>
{{out}}
<pre>2
2</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
{{works with|Rakudo|2017.04}}
 
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>
my @array = <apple orange>;
 
say @array.elems; # 2
say elems @array; # 2
say + @array; # 2
say @array + 0; # 2
</syntaxhighlight>
 
Watch out for infinite/lazy arrays though. You can't get the length of those.
 
<syntaxhighlight lang="raku" line>my @infinite = 1 .. Inf; # 1, 2, 3, 4, ...
 
say @infinite[5000]; # 5001
say @infinite.elems; # Throws exception "Cannot .elems a lazy list"
</syntaxhighlight>
 
=={{header|Rapira}}==
<syntaxhighlight lang="rapira">arr := <* "apple", "orange" *>
output: #arr</syntaxhighlight>
 
=={{header|REBOL}}==
<syntaxhighlight lang="rebol">
>> length? ["apples" "oranges"]
== 2
</syntaxhighlight>
 
=={{header|Red}}==
<syntaxhighlight lang="red">length? ["apples" "oranges"]
== 2</syntaxhighlight>
 
=={{header|Relation}}==
<syntaxhighlight lang="relation">
relation fruit
insert "apples"
insert "oranges"
project fruit count
print
</syntaxhighlight>
 
{| border=1
|-
! fruit_count
|-
| 2
|}
 
=={{header|ReScript}}==
<syntaxhighlight lang="rescript">let fruits = ["apple", "orange"]
 
Js.log(Js.Array.length(fruits))</syntaxhighlight>
 
<syntaxhighlight lang="html"><!DOCTYPE html>
<html>
<head>
<title>ReScript: Array.length()</title>
<style rel="stylesheet" type="text/css">
body { color:#EEE; background-color:#888; }
</style>
<script>var exports = {};</script>
<script src="./arrlen.js"></script>
</head>
<body>
 
</body>
</html></syntaxhighlight>
{{out}}
<pre>// Generated by ReScript, PLEASE EDIT WITH CARE
'use strict';
 
var fruits = [
"apple",
"orange"
];
 
console.log(fruits.length);
 
exports.fruits = fruits;
/* Not a pure module */</pre>
 
 
=={{header|REXX}}==
<langsyntaxhighlight lang="rexx">/* REXX ----------------------------------------------
* The compond variable a. implements an array
* By convention, a.0 contains the number of elements
Line 1,246 ⟶ 2,771:
a.z=arg(1)
a.0=z
Return</langsyntaxhighlight>
{{out}}
<pre>There are 2 elements in the array:
Line 1,254 ⟶ 2,779:
=={{header|Ring}}==
 
<langsyntaxhighlight ringlang="python">See len(['apple', 'orange']) # output = 2 </langsyntaxhighlight>
 
=={{header|Robotic}}==
As stated before in the [[Arrays#Robotic|arrays]] section on this Wiki, there is no functions listed for the manipulation/status of arrays. The best way we can count for length in an array is to have a variable keep track of it.
 
Example 1:
<syntaxhighlight lang="robotic">
set "index" to 0
set "$array&index&" to "apple"
inc "index" by 1
set "$array&index&" to "orange"
* "Array length: ('index' + 1)"
</syntaxhighlight>
 
Example 2:
<syntaxhighlight lang="robotic">
set "index" to 0
set "local1" to random 1 to 99
: "rand"
set "array&index&" to random 0 to 99
inc "index" 1
dec "local1" 1
if "local1" > 1 then "rand"
* "Array length: ('index')"
</syntaxhighlight>
 
=={{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 1,264 ⟶ 2,821:
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|SETLScheme}}==
 
<lang haskell>
Using Scheme's vector type as an equivalent to an array:
arr := ["apple", "orange"];
 
print(# arr); -- '#' is the cardinality operator. Works on strings, tuples, and sets.
<syntaxhighlight lang="scheme">
</lang>
(display (vector-length #("apple" "orange")))
</syntaxhighlight>
 
=={{header|Seed7}}==
The function [http://seed7.sourceforge.net/libraries/array.htm#length(in_arrayType) length]
determines the length of an array.
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";
 
const array string: anArray is [] ("apple", "orange");
 
const proc: main is func
begin
writeln(length(anArray));
end func;</syntaxhighlight>
 
=={{header|SenseTalk}}==
<syntaxhighlight lang="sensetalk">put ("apple", "orange", "pear", "banana", "aubergine") into fruits
put the number of items in fruits</syntaxhighlight>
 
=={{header|Shen}}==
<syntaxhighlight lang="shen">
\\ Using a vector
\\ @v creates the vector
\\ <> ends the vector
\\ limit returns the length of a vector
\\ apple and orange are symbols (vs strings) in this case.
(limit (@v apple orange <>))
 
 
\\ As an list
(length [apple orange])
</syntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var arr = ['apple', 'orange'];
say arr.len; #=> 2
say arr.end; #=> 1 (zero based)</langsyntaxhighlight>
 
=={{header|SmalltalkSimula}}==
<syntaxhighlight lang="simula">COMMENT ARRAY-LENGTH;
<lang smalltalk>
BEGIN
a := #('apple' 'orange').
a size</lang>
 
INTEGER PROCEDURE ARRAYLENGTH(A); TEXT ARRAY A;
BEGIN
ARRAYLENGTH := UPPERBOUND(A, 1) - LOWERBOUND(A, 1) + 1;
END ARRAYLENGTH;
 
TEXT ARRAY A(1:2);
INTEGER L;
A(1) :- "APPLE";
A(2) :- "ORANGE";
L := ARRAYLENGTH(A);
OUTINT(L, 0);
OUTIMAGE;
END
</syntaxhighlight>
{{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}}==
<syntaxhighlight lang="smalltalk">
a := #('apple' 'orange').
a size</syntaxhighlight>
 
=={{header|SNOBOL4}}==
<langsyntaxhighlight SNOBOL4lang="snobol4"> ar = ARRAY('2,2')
ar<1,1> = 'apple'
ar<1,2> = 'first'
Line 1,302 ⟶ 2,943:
ar<2,2> = 'second'
OUTPUT = IDENT(DATATYPE(ar), 'ARRAY') PROTOTYPE(ar)
end</langsyntaxhighlight>
{{out}}<pre>2,2</pre>
 
=={{header|SPL}}==
<syntaxhighlight lang="spl">a = ["apple","orange"]
#.output("Number of elements in array: ",#.size(a,1))</syntaxhighlight>
{{out}}
<pre>
Number of elements in array: 2
</pre>
 
=={{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|SwiftStata}}==
String data may be stored either in a Stata dataset or in a Mata matrix, not in a Stata matrix, which may hold only numeric data. A list of strings may also be stored in a Stata macro.
 
=== Dimensions of a dataset ===
<lang Swift>import Cocoa //include Cocoa library (standard in OS X)
<syntaxhighlight lang="stata">clear
input str10 fruit
apple
orange
end
 
di _N
let fruits = ["apple", "orange"] //declare constant array literal
di c(N) " " c(k)</syntaxhighlight>
let fruitsCount = fruits.count //declare constant array length (count)
 
=== Length of a macro list ===
print(fruitsCount) //print array length to output window</lang>
 
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''.
 
<syntaxhighlight lang="stata">local fruits apple orange
di `: list sizeof fruits'
di `: word count `fruits''</syntaxhighlight>
 
=== Mata ===
For a Mata array, use '''[https://www.stata.com/help.cgi?mf_rows rows]''' and similar functions:
 
<syntaxhighlight lang="stata">mata
a=st_sdata(.,"fruit")
rows(a)
cols(a)
length(a)
end</syntaxhighlight>
 
=={{header|Swift}}==
 
<syntaxhighlight lang="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</syntaxhighlight>
{{out}}<pre>2</pre>
 
=={{header|Symsyn}}==
<syntaxhighlight lang="symsyn">
| Symsyn does not support Array of Strings
| The following code for an Array of Integers
 
A : 125 0
#A []
| shows 125
 
| A list of fixed length strings can be handled this way
 
S : 'apple ' : 'orange'
div #S 6 sz
sz []
| shows 2
</syntaxhighlight>
 
=={{header|Tailspin}}==
<syntaxhighlight lang="tailspin">
['apple', 'orange'] -> $::length -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>2</pre>
 
=={{header|Tcl}}==
<!-- http://ideone.com/uotEvm -->
 
<langsyntaxhighlight lang="tcl">;# not recommandedrecommended:
set mylistA {apple orange} ;# actually a string
set mylistA "Apple Orange" ;# same - this works only for simple cases
Line 1,342 ⟶ 3,044:
set lenB [llength $mylistB]
puts "$mylistB : $lenB"
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,351 ⟶ 3,053:
{{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>
6
</pre>
 
=={{header|Transd}}==
<syntaxhighlight lang="scheme">#lang transd
 
MainModule : {
_start: (lambda
(with v ["apple", "orange"]
(lout (size v))
)
(lout (size ["apple", "orange"]))
)
}</syntaxhighlight>{{out}}
<pre>
2
2
</pre>
 
=={{header|Uiua}}==
{{works with|Uiua|0.11.1}}
It would be more accurate to say this is the number of ''rows'' in an array.
<syntaxhighlight lang="uiua">
⧻{"apple" "orange"}
</syntaxhighlight>
{{out}}
<pre>
2
</pre>
 
=={{header|UNIX Shell}}==
<syntaxhighlight lang="bash">#!/bin/bash
array=("orange" "apple")
echo "${#array[@]}"</syntaxhighlight>
{{out}}
<pre>
2
</pre>
 
Line 1,366 ⟶ 3,104:
11
> </pre>
 
=={{header|Vala}}==
<syntaxhighlight lang="vala">void main() {
string[] fruit = {"apple", "orange"};
stdout.printf("%d\n", fruit.length);
}</syntaxhighlight>
 
Note that any of the following array declarations could be used:
 
<syntaxhighlight lang="vala">
var fruit = new string[] { "apple", "orange" };
string[] fruit = new string[] { "apple", "orange" };
string[] fruit = { "apple", "orange" };
</syntaxhighlight>
 
A shorter variant could also have been used:
 
<syntaxhighlight lang="vala">
void main() {
stdout.printf("%d\n", new string[] {"apples", "orange"}.length);
}
</syntaxhighlight>
 
=={{header|VBA}}==
One-liner. Assumes array lower bound, which is not always safe.
<lang vb>Debug.Print "Array Length: " & UBound(Array("apple", "orange")) + 1</lang>
<syntaxhighlight lang="vb">Debug.Print "Array Length: " & UBound(Array("apple", "orange")) + 1</syntaxhighlight>
 
Works regardless of lower bound:
<syntaxhighlight lang="vb">Dim funkyArray(7 to 8) As String
 
Public Function SizeOfArray(ar As Variant) As Long
SizeOfArray = UBound(ar) - LBound(ar) + 1
End Function
 
'call the function
Debug.Print "Array Length: " & SizeOfArray(funkyArray)</syntaxhighlight>
 
{{Out}}
In this instance, same output for both.
<pre>Array Length: 2</pre>
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">arr = Array("apple","orange")
WScript.StdOut.WriteLine UBound(arr) - LBound(arr) + 1 </langsyntaxhighlight>
 
{{Out}}
<pre>2</pre>
 
=={{header|Visual Basic}}==
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">
' declared in a module
Public Function LengthOfArray(ByRef arr As Variant) As Long
If IsArray(arr) Then
LengthOfArray = UBound(arr) - LBound(arr) + 1
Else
LengthOfArray = -1
End If
End Function
 
' somewhere in the programm
' example 1
Dim arr As Variant
arr = Array("apple", "orange")
Debug.Print LengthOfArray(arr) ' prints 2 as result
 
' example 2
Dim arr As Variant
ReDim arr(-2 To -1)
arr(-2) = "apple"
arr(-1) = "orange"
 
Debug.Print LengthOfArray(arr) ' prints 2 as result
 
</syntaxhighlight>
 
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
<syntaxhighlight lang="vbnet">Module ArrayLength
 
Sub Main()
Dim array() As String = {"apple", "orange"}
Console.WriteLine(array.Length)
End Sub
 
End Module
</syntaxhighlight>
 
{{out}}
<pre>
2
</pre>
 
=={{header|V (Vlang)}}==
A '''len''' property is maintained for all V (Vlang) arrays.
<syntaxhighlight lang="go">// V, array length
// Tectonics: v run array-length.v
module main
 
// access array length
pub fn main() {
arr := ["apple", "orange"]
println(arr.len)
}</syntaxhighlight>
 
{{out}}<pre>prompt$ v run array-length.v
2</pre>
 
=={{header|WDTE}}==
<syntaxhighlight lang="wdte">let io => import 'io';
let a => ['apple'; 'orange'];
len a -- io.writeln io.stdout;</syntaxhighlight>
 
=={{header|Wren}}==
<langsyntaxhighlight lang="wren">var arr = [1"apple",2,3 "orange"]
var length = System.print(arr.count)</syntaxhighlight>
 
</lang>
{{out}}
<pre>
2
</pre>
 
=={{header|XLISP}}==
<langsyntaxhighlight lang="lisp">(vector-length #("apple" "orange"))</langsyntaxhighlight>
 
 
=={{header|Yabasic}}==
<syntaxhighlight lang="yabasic">
dim fruta$(3)
read fruta$(1), fruta$(2), fruta$(3)
data "apple", "orange", "pear"
 
print arraysize(fruta$(),1)
print fruta$(2)
end
</syntaxhighlight>
<pre>
3
orange
</pre>
 
 
=={{header|Z80 Assembly}}==
Arrays don't have an "end" as defined by the language, so there are a couple ways to mark the end of an array. One is with a null terminator, and the other is with a pre-defined size byte stored at the beginning. Using a null terminator isn't the best choice for a general-purpose array since it means your array cannot contain that value anywhere except at the end. However, since having the size already determined defeats the purpose of this task, the null-terminator method will be used for this example.
 
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.
 
<syntaxhighlight lang="z80"> org &8000
ld hl,TestArray
call GetArrayLength_WordData_NullTerminated
call Monitor ;show registers to screen, code omitted to keep this example short
ReturnToBasic:
RET
GetArrayLength_WordData_NullTerminated:
push hl ;we'll need this later
loop_GetArrayLength_WordData_NullTerminated
ld a,(hl) ;get the low byte
ld e,a ;stash it in E
inc hl ;next byte
ld a,(hl) ;get the high byte
dec hl ;go back to low byte, otherwise our length will be off.
or a ;compare to zero. This is a shorter and faster way to compare A to zero than "CP 0"
jr nz,keepGoing
cp e ;compare to E
jr z,Terminated_GetArrayLength ;both bytes were zero.
KeepGoing:
inc hl
inc hl ;next word
jp loop_GetArrayLength_WordData_NullTerminated ;back to start
Terminated_GetArrayLength:
pop de ;original array address is in DE
;or a ;normally it's best to clear the carry, but in this situation execution only arrives here after a compare that
;resulted in an equality to zero, which means the carry is guaranteed to be cleared.
sbc hl,de ;there is no sub hl,de; only sbc
srl h
rr l ;divide HL by 2, since each element is 2 bytes.
ret ;returns length in hl
 
TestArray:
word Apple,Orange
byte 0,0
Apple:
byte "Apple",0
Orange:
byte "Orange",0</syntaxhighlight>
 
{{out}}
<pre>(HL contains length of the array)
HL:0002
</pre>
 
=={{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}}==
<syntaxhighlight lang="zig">const std = @import("std");
 
pub fn main() !void {
// left hand side type can be ommitted
const fruit: [2][]const u8 = [_][]const u8{ "apples", "oranges" };
const stdout_wr = std.io.getStdOut().writer();
// slices and arrays have an len field
try stdout_wr.print("fruit.len = {d}\n", .{fruit.len});
}</syntaxhighlight>
 
=={{header|Zoea}}==
<syntaxhighlight lang="zoea">
program: array_length
input: [a,b,c]
output: 3
</syntaxhighlight>
 
=={{header|Zoea Visual}}==
[http://zoea.co.uk/examples/zv-rc/Array_length.png Array Length]
 
=={{header|zonnon}}==
<syntaxhighlight lang="zonnon">
module AryLength;
type
Vector = array 12 of string;
Matrix = array *,* of string;
var
a: Vector;
b: Matrix;
begin
writeln(len(a):4); (* len(a) = len(a,0) *)
 
b := new Matrix(10,11);
writeln(len(b,0):4); (* first dimension *)
writeln(len(b,1):4) (* second dimension *)
end AryLength.
</syntaxhighlight>