Array length: Difference between revisions

From Rosetta Code
Content added Content deleted
m (syntax highlighting fixup automation)
Line 13: Line 13:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>print([‘apple’, ‘orange’].len)</lang>
<syntaxhighlight lang=11l>print([‘apple’, ‘orange’].len)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 21: Line 21:
=={{header|360 Assembly}}==
=={{header|360 Assembly}}==
Array length is computed at compilation time with the formula : (AEND-A)/L'A
Array length is computed at compilation time with the formula : (AEND-A)/L'A
<lang 360asm>* Array length 22/02/2017
<syntaxhighlight lang=360asm>* Array length 22/02/2017
ARRAYLEN START
ARRAYLEN START
USING ARRAYLEN,12
USING ARRAYLEN,12
Line 32: Line 32:
AEND DC 0C
AEND DC 0C
PG DC CL25'Array length=' buffer
PG DC CL25'Array length=' buffer
END ARRAYLEN</lang>
END ARRAYLEN</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 40: Line 40:
{{trans|360 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.
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.
<lang 6502asm>start:
<syntaxhighlight lang=6502asm>start:
LDA #(Array_End-Array) ;evaluates to 13
LDA #(Array_End-Array) ;evaluates to 13
RTS
RTS
Line 47: Line 47:
byte "apple",0
byte "apple",0
byte "orange",0
byte "orange",0
Array_End:</lang>
Array_End:</syntaxhighlight>


=={{header|68000 Assembly}}==
=={{header|68000 Assembly}}==
Line 55: Line 55:




<lang 68000devpac>start:
<syntaxhighlight lang=68000devpac>start:
MOVE.B #(MyArray_End-MyArray)/4 ;evaluates to 2
MOVE.B #(MyArray_End-MyArray)/4 ;evaluates to 2
RTS
RTS
Line 69: Line 69:
DC.L Apple
DC.L Apple
DC.L Orange
DC.L Orange
MyArray_End:</lang>
MyArray_End:</syntaxhighlight>


=={{header|8th}}==
=={{header|8th}}==
<lang forth>
<syntaxhighlight lang=forth>
["apples", "oranges"] a:len . cr
["apples", "oranges"] a:len . cr
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 82: Line 82:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<lang AArch64 Assembly>
<syntaxhighlight lang=AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program lenAreaString64.s */
/* program lenAreaString64.s */
Line 147: Line 147:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>


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


<lang ABAP>
<syntaxhighlight lang=ABAP>
report z_array_length.
report z_array_length.


Line 158: Line 158:


write: internal_table[ 1 ] , internal_table[ 2 ] , lines( internal_table ).
write: internal_table[ 1 ] , internal_table[ 2 ] , lines( internal_table ).
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 167: Line 167:
=={{header|Ada}}==
=={{header|Ada}}==


<lang Ada>with Ada.Text_IO; use Ada.Text_IO;
<syntaxhighlight lang=Ada>with Ada.Text_IO; use Ada.Text_IO;


procedure Array_Length is
procedure Array_Length is
Line 180: Line 180:


Ada.Text_IO.Put_Line (" Array Size : " & Integer'Image (Fruits'Length));
Ada.Text_IO.Put_Line (" Array Size : " & Integer'Image (Fruits'Length));
end Array_Length;</lang>
end Array_Length;</syntaxhighlight>


{{out}}
{{out}}
Line 186: Line 186:


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
<lang algol68># UPB returns the upper bound of an array, LWB the lower bound #
<syntaxhighlight lang=algol68># UPB returns the upper bound of an array, LWB the lower bound #
[]STRING fruits = ( "apple", "orange" );
[]STRING fruits = ( "apple", "orange" );
print( ( ( UPB fruits - LWB fruits ) + 1, newline ) ) # prints 2 #</lang>
print( ( ( UPB fruits - LWB fruits ) + 1, newline ) ) # prints 2 #</syntaxhighlight>


=={{header|AntLang}}==
=={{header|AntLang}}==
<lang AntLang>array: seq["apple"; "orange"]
<syntaxhighlight lang=AntLang>array: seq["apple"; "orange"]
length[array]
length[array]
/Works as a one liner: length[seq["apple"; "orange"]]</lang>
/Works as a one liner: length[seq["apple"; "orange"]]</syntaxhighlight>


=={{header|Apex}}==
=={{header|Apex}}==
<lang apex>System.debug(new String[] { 'apple', 'banana' }.size()); // Prints 2</lang>
<syntaxhighlight lang=apex>System.debug(new String[] { 'apple', 'banana' }.size()); // Prints 2</syntaxhighlight>


=={{header|APL}}==
=={{header|APL}}==
<lang apl>⍴'apple' 'orange'</lang>
<syntaxhighlight lang=apl>⍴'apple' 'orange'</syntaxhighlight>
Output:
Output:
<pre>2</pre>
<pre>2</pre>


=={{header|AppleScript}}==
=={{header|AppleScript}}==
<lang AppleScript>
<syntaxhighlight lang=AppleScript>
set theList to {"apple", "orange"}
set theList to {"apple", "orange"}
count theList
count theList
Line 211: Line 211:
-- or
-- or
number of items in theList
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.''
''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}}
{{out}}
Line 222: Line 222:
<pre>fold (λx n -> 1 + n) 0</pre>
<pre>fold (λx n -> 1 + n) 0</pre>


<lang AppleScript>on run
<syntaxhighlight lang=AppleScript>on run
set xs to ["alpha", "beta", "gamma", "delta", "epsilon", ¬
set xs to ["alpha", "beta", "gamma", "delta", "epsilon", ¬
Line 263: Line 263:
end repeat
end repeat
end fold
end fold
</syntaxhighlight>
</lang>


{{Out}}
{{Out}}
Line 271: Line 271:
=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<lang ARM Assembly>
<syntaxhighlight lang=ARM Assembly>
/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
/* program lenAreaString.s */
/* program lenAreaString.s */
Line 407: Line 407:
.Ls_magic_number_10: .word 0x66666667
.Ls_magic_number_10: .word 0x66666667


</syntaxhighlight>
</lang>


=={{header|Arturo}}==
=={{header|Arturo}}==


<lang rebol>fruit: ["apple" "orange"]
<syntaxhighlight lang=rebol>fruit: ["apple" "orange"]


print ["array length =" size fruit]</lang>
print ["array length =" size fruit]</syntaxhighlight>
{{out}}
{{out}}
Line 420: Line 420:


=={{header|ATS}}==
=={{header|ATS}}==
<lang ATS>
<syntaxhighlight lang=ATS>
#include
#include
"share/atspre_staload.hats"
"share/atspre_staload.hats"
Line 433: Line 433:


implement main0((*void*)) = ((*void*))
implement main0((*void*)) = ((*void*))
</syntaxhighlight>
</lang>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>MsgBox % ["apple","orange"].MaxIndex()</lang>
<syntaxhighlight lang=AutoHotkey>MsgBox % ["apple","orange"].MaxIndex()</syntaxhighlight>
{{Out}}<pre>2</pre>
{{Out}}<pre>2</pre>


=={{header|AutoIt}}==
=={{header|AutoIt}}==
<lang AutoIt>Opt('MustDeclareVars',1) ; 1 = Variables must be pre-declared.
<syntaxhighlight lang=AutoIt>Opt('MustDeclareVars',1) ; 1 = Variables must be pre-declared.


Local $aArray[2] = ["Apple", "Orange"]
Local $aArray[2] = ["Apple", "Orange"]
Line 449: Line 449:
ConsoleWrite("aArray[" & $i & "] = '" & $aArray[$i] & "'" & @CRLF)
ConsoleWrite("aArray[" & $i & "] = '" & $aArray[$i] & "'" & @CRLF)
Next
Next
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>Elements in array: 2
<pre>Elements in array: 2
Line 459: Line 459:
Using Avail's tuples and the `|_|` method:
Using Avail's tuples and the `|_|` method:


<lang Avail>|<"Apple", "Orange">|</lang>
<syntaxhighlight lang=Avail>|<"Apple", "Orange">|</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
Line 468: Line 468:
Another method to count the elements of the array is by using a variant of for().
Another method to count the elements of the array is by using a variant of for().


<lang awk># usage: awk -f arraylen.awk
<syntaxhighlight lang=awk># usage: awk -f arraylen.awk
#
#
function countElements(array) {
function countElements(array) {
Line 482: Line 482:
print "String length:", array[1], length(array[1])
print "String length:", array[1], length(array[1])
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 492: Line 492:
=={{header|BaCon}}==
=={{header|BaCon}}==
BaCon knows three types of arrays, the UBOUND function can query all.
BaCon knows three types of arrays, the UBOUND function can query all.
<lang bacon>' Static arrays
<syntaxhighlight lang=bacon>' Static arrays


DECLARE fruit$[] = { "apple", "orange" }
DECLARE fruit$[] = { "apple", "orange" }
Line 509: Line 509:
meat$("first") = "chicken"
meat$("first") = "chicken"
meat$("second") = "pork"
meat$("second") = "pork"
PRINT UBOUND(meat$)</lang>
PRINT UBOUND(meat$)</syntaxhighlight>


=={{header|Bash}}==
=={{header|Bash}}==


<lang bash>
<syntaxhighlight lang=bash>
fruit=("apple" "orange" "lemon")
fruit=("apple" "orange" "lemon")
echo "${#fruit[@]}"</lang>
echo "${#fruit[@]}"</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
<lang basic>DIM X$(1 TO 2)
<syntaxhighlight lang=basic>DIM X$(1 TO 2)
X$(1) = "apple"
X$(1) = "apple"
X$(2) = "orange"
X$(2) = "orange"
PRINT UBOUND(X$) - LBOUND(X$) + 1</lang>
PRINT UBOUND(X$) - LBOUND(X$) + 1</syntaxhighlight>


==={{header|Applesoft BASIC}}===
==={{header|Applesoft BASIC}}===
<lang basic>10 DIM A$(2)
<syntaxhighlight lang=basic>10 DIM A$(2)
20 A$(1) = "ORANGE"
20 A$(1) = "ORANGE"
30 A$(2) = "APPLE"
30 A$(2) = "APPLE"
Line 557: Line 557:
170 L$ = L$ + STR$ ( FN P(I))
170 L$ = L$ + STR$ ( FN P(I))
180 L$ = L$ + " ": NEXT I
180 L$ = L$ + " ": NEXT I
190 RETURN</lang>
190 RETURN</syntaxhighlight>


==={{header|BASIC256}}===
==={{header|BASIC256}}===
<lang BASIC256>
<syntaxhighlight lang=BASIC256>
fruta$ = {"apple", "orange", "pear"}
fruta$ = {"apple", "orange", "pear"}
Line 567: Line 567:
print fruta$[1]
print fruta$[1]
end
end
</syntaxhighlight>
</lang>
<pre>
<pre>
3
3
Line 577: Line 577:
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:
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}}
{{works with|Commodore BASIC|2.0 on C-64}}
<lang basic>10 DIM A$(1):REM 1=LAST -> ROOM FOR 2
<syntaxhighlight lang=basic>10 DIM A$(1):REM 1=LAST -> ROOM FOR 2
20 A$(0) = "ORANGE"
20 A$(0) = "ORANGE"
30 A$(1) = "APPLE"
30 A$(1) = "APPLE"
Line 587: Line 587:
90 IF T=128 THEN N$=N$+"$": REM STRING
90 IF T=128 THEN N$=N$+"$": REM STRING
100 L=PEEK(AT+6): REM FIRST INDEX SIZE
100 L=PEEK(AT+6): REM FIRST INDEX SIZE
110 PRINT N$" HAS"L"ELEMENTS."</lang>
110 PRINT N$" HAS"L"ELEMENTS."</syntaxhighlight>


{{Out}}
{{Out}}
Line 593: Line 593:


==={{header|True BASIC}}===
==={{header|True BASIC}}===
<lang qbasic>
<syntaxhighlight lang=qbasic>
DIM fruta$(2)
DIM fruta$(2)
READ fruta$(1), fruta$(2)
READ fruta$(1), fruta$(2)
Line 602: Line 602:
PRINT "La longitud del array fruta$ es" ; tamano
PRINT "La longitud del array fruta$ es" ; tamano
END
END
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 610: Line 610:
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.
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.


<lang qbasic>
<syntaxhighlight lang=qbasic>
DIM fruit$(2)
DIM fruit$(2)
MAT READ fruit$
MAT READ fruit$
Line 617: Line 617:
PRINT "The length of the array 'fruit$' is "; SIZE(fruit$)
PRINT "The length of the array 'fruit$' is "; SIZE(fruit$)
END
END
</syntaxhighlight>
</lang>




Line 626: Line 626:
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.
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.


<lang dos>
<syntaxhighlight lang=dos>
@echo off
@echo off


Line 655: Line 655:
set /a arraylength+=1
set /a arraylength+=1
goto loop
goto loop
</syntaxhighlight>
</lang>
{{in}}
{{in}}
<pre>
<pre>
Line 667: Line 667:
=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> DIM array$(1)
<syntaxhighlight lang=bbcbasic> DIM array$(1)
array$() = "apple", "orange"
array$() = "apple", "orange"
PRINT "Number of elements in array = "; DIM(array$(), 1) + 1
PRINT "Number of elements in array = "; DIM(array$(), 1) + 1
PRINT "Number of bytes in all elements combined = "; SUMLEN(array$())
PRINT "Number of bytes in all elements combined = "; SUMLEN(array$())
END</lang>
END</syntaxhighlight>
{{Out}}
{{Out}}


Line 678: Line 678:


=={{header|Brat}}==
=={{header|Brat}}==
<lang brat>
<syntaxhighlight lang=brat>
p ["apple", "orange"].length
p ["apple", "orange"].length
</syntaxhighlight>
</lang>


=={{header|BQN}}==
=={{header|BQN}}==


<code>≠</code> gives the length of an array in BQN.
<code>≠</code> gives the length of an array in BQN.
<lang bqn>≠ 1‿"a"‿+</lang>
<syntaxhighlight lang=bqn>≠ 1‿"a"‿+</syntaxhighlight>
<lang bqn>3</lang>
<syntaxhighlight lang=bqn>3</syntaxhighlight>
[https://mlochbaum.github.io/BQN/try.html#code=4omgIDHigL8iYSLigL8r Try It!]
[https://mlochbaum.github.io/BQN/try.html#code=4omgIDHigL8iYSLigL8r Try It!]


Line 697: Line 697:
For static arrays:
For static arrays:


<syntaxhighlight lang=c>
<lang c>
#include <stdio.h>
#include <stdio.h>


Line 719: Line 719:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


A C pre-processor macro may be created for ease of use:
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]))
#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.
Note that these arrays become pointers when passed as a parameter to a function.
Line 744: Line 744:
</p>
</p>
====Solution====
====Solution====
<lang C>#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings
<syntaxhighlight lang=C>#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings
#define _CRT_NONSTDC_NO_WARNINGS // enable old-gold POSIX names in MSVS
#define _CRT_NONSTDC_NO_WARNINGS // enable old-gold POSIX names in MSVS


Line 819: Line 819:


return EXIT_SUCCESS;
return EXIT_SUCCESS;
}</lang>
}</syntaxhighlight>
{{output}}
{{output}}
<pre>There are 2 elements in an array with a capacity of 10 elements:
<pre>There are 2 elements in an array with a capacity of 10 elements:
Line 827: Line 827:


====An example why sizeof(A)/sizeof(E) may be a bad idea in C====
====An example why sizeof(A)/sizeof(E) may be a bad idea in C====
<lang C>#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings
<syntaxhighlight lang=C>#define _CRT_SECURE_NO_WARNINGS // turn off panic warnings
#define _CRT_NONSTDC_NO_WARNINGS // enable old-gold POSIX names in MSVS
#define _CRT_NONSTDC_NO_WARNINGS // enable old-gold POSIX names in MSVS


Line 938: Line 938:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
<p>
<p>
As we can see the ''sizeof(ArrayType)/sizeof(ElementType)'' approach mostly fail.
As we can see the ''sizeof(ArrayType)/sizeof(ElementType)'' approach mostly fail.
Line 1,005: Line 1,005:
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==


<lang csharp>
<syntaxhighlight lang=csharp>
using System;
using System;


Line 1,016: Line 1,016:
}
}
}
}
</syntaxhighlight>
</lang>


Note that any of the following array declarations could be used:
Note that any of the following array declarations could be used:


<lang csharp>
<syntaxhighlight lang=csharp>
var fruit = new[] { "apple", "orange" };
var fruit = new[] { "apple", "orange" };
var fruit = new string[] { "apple", "orange" };
var fruit = new string[] { "apple", "orange" };
Line 1,026: Line 1,026:
string[] fruit = new string[] { "apple", "orange" };
string[] fruit = new string[] { "apple", "orange" };
string[] fruit = { "apple", "orange" };
string[] fruit = { "apple", "orange" };
</syntaxhighlight>
</lang>


A shorter variant could also have been used:
A shorter variant could also have been used:


<lang csharp>
<syntaxhighlight lang=csharp>
using static System.Console;
using static System.Console;


Line 1,040: Line 1,040:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|C++}}==
=={{header|C++}}==
Line 1,048: Line 1,048:
However, C++ has an additional <code>std::array</code> type (amongst other collections) in its standard library:
However, C++ has an additional <code>std::array</code> type (amongst other collections) in its standard library:


<lang cpp>#include <array>
<syntaxhighlight lang=cpp>#include <array>
#include <iostream>
#include <iostream>
#include <string>
#include <string>
Line 1,057: Line 1,057:
std::cout << fruit.size();
std::cout << fruit.size();
return 0;
return 0;
}</lang>
}</syntaxhighlight>


Note that <code>char*</code> or <code>const char*</code> could have been used instead of <code>std::string</code>.
Note that <code>char*</code> or <code>const char*</code> could have been used instead of <code>std::string</code>.
Line 1,063: Line 1,063:
In addition to the <code>std::array</code> type, the C++ standard library also provides dynamically-sized containers to hold arbitrary objects.
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.
These all support similar interfaces, though their implementations have different performance characteristics.
<lang cpp> std::vector<std::string> fruitV({ "apples", "oranges" });
<syntaxhighlight lang=cpp> std::vector<std::string> fruitV({ "apples", "oranges" });
std::list<std::string> fruitL({ "apples", "oranges" });
std::list<std::string> fruitL({ "apples", "oranges" });
std::deque<std::string> fruitD({ "apples", "oranges" });
std::deque<std::string> fruitD({ "apples", "oranges" });
std::cout << fruitV.size() << fruitL.size() << fruitD.size() << std::endl;</lang>
std::cout << fruitV.size() << fruitL.size() << fruitD.size() << std::endl;</syntaxhighlight>


Of these, vector is probably the most widely used.
Of these, vector is probably the most widely used.


=={{header|Ceylon}}==
=={{header|Ceylon}}==
<lang ceylon>shared void run() {
<syntaxhighlight lang=ceylon>shared void run() {
value array = ["apple", "orange"];
value array = ["apple", "orange"];
print(array.size);
print(array.size);
}</lang>
}</syntaxhighlight>


=={{header|Clipper/XBase++}}==
=={{header|Clipper/XBase++}}==


<lang Clipper/XBase++>/*
<syntaxhighlight lang=Clipper/XBase++>/*
* nizchka: March - 2016
* nizchka: March - 2016
* This is a Clipper/XBase++ of RosettaCode Array_Length
* This is a Clipper/XBase++ of RosettaCode Array_Length
Line 1,088: Line 1,088:
? LEN(FRUIT)
? LEN(FRUIT)
RETURN
RETURN
</syntaxhighlight>
</lang>
Outputs:<pre>2</pre>
Outputs:<pre>2</pre>
[[User:nizchka|nizchka]] 23:27, 16 March 2016 (UTC)
[[User:nizchka|nizchka]] 23:27, 16 March 2016 (UTC)
Line 1,094: Line 1,094:
=={{header|Clojure}}==
=={{header|Clojure}}==


<lang clojure>; using count:
<syntaxhighlight lang=clojure>; using count:
(count ["apple" "orange"])
(count ["apple" "orange"])


; OR alength if using Java arrays:
; OR alength if using Java arrays:
(alength (into-array ["apple" "orange"]))</lang>
(alength (into-array ["apple" "orange"]))</syntaxhighlight>


=={{header|COBOL}}==
=={{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.
Arrays in COBOL are usually referred to as tables. Tables can have fixed or variable (with known maximum) allocations, using a syntax of OCCURS DEPENDING ON. The value of the ODO identifier is the number of active elements in the table.


<lang COBOL> identification division.
<syntaxhighlight lang=COBOL> identification division.
program-id. array-length.
program-id. array-length.


Line 1,142: Line 1,142:
.
.


end program array-length.</lang>
end program array-length.</syntaxhighlight>
{{out}}
{{out}}
<pre>$ cobc -xjd array-length.cob
<pre>$ cobc -xjd array-length.cob
Line 1,151: Line 1,151:
=={{header|ColdFusion}}==
=={{header|ColdFusion}}==


<lang coldfusion>
<syntaxhighlight lang=coldfusion>
<cfset testArray = ["apple","orange"]>
<cfset testArray = ["apple","orange"]>
<cfoutput>Array Length = #ArrayLen(testArray)#</cfoutput>
<cfoutput>Array Length = #ArrayLen(testArray)#</cfoutput>
</syntaxhighlight>
</lang>
Outputs:<pre>Array Length = 2</pre>
Outputs:<pre>Array Length = 2</pre>
[[User:grandnegus|Mike Knapp]] 15:57, 26 May 2016 (UTC)
[[User:grandnegus|Mike Knapp]] 15:57, 26 May 2016 (UTC)


=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
<lang Lisp>
<syntaxhighlight lang=Lisp>
(print (length #("apple" "orange")))
(print (length #("apple" "orange")))
</syntaxhighlight>
</lang>
===Alternate solution===
===Alternate solution===
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]


<lang lisp>
<syntaxhighlight lang=lisp>
;; Project : Array length
;; Project : Array length


Line 1,174: Line 1,174:
(length my-array)
(length my-array)
(terpri)
(terpri)
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,182: Line 1,182:
=={{header|Component Pascal}}==
=={{header|Component Pascal}}==
{{works with|BlackBox Component Builder}}
{{works with|BlackBox Component Builder}}
<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE AryLen;
MODULE AryLen;
IMPORT StdLog;
IMPORT StdLog;
Line 1,215: Line 1,215:


END AryLen.
END AryLen.
</syntaxhighlight>
</lang>
Execute: ^Q AryLen.Do
Execute: ^Q AryLen.Do
{{out}}
{{out}}
Line 1,224: Line 1,224:
=={{header|Crystal}}==
=={{header|Crystal}}==


<lang ruby>
<syntaxhighlight lang=ruby>
puts ["apple", "orange"].size
puts ["apple", "orange"].size
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,234: Line 1,234:


=={{header|D}}==
=={{header|D}}==
<syntaxhighlight lang=d>
<lang d>
import std.stdio;
import std.stdio;


Line 1,243: Line 1,243:
return 0;
return 0;
}
}
</syntaxhighlight>
</lang>


Or a somewhat shorter...
Or a somewhat shorter...
<syntaxhighlight lang=d>
<lang d>
import std.stdio;
import std.stdio;


Line 1,253: Line 1,253:
["apple", "orange"].length.writeln;
["apple", "orange"].length.writeln;
}
}
</syntaxhighlight>
</lang>


=={{header|Dart}}==
=={{header|Dart}}==
<lang dart>
<syntaxhighlight lang=dart>
arrLength(arr) {
arrLength(arr) {
return arr.length;
return arr.length;
Line 1,266: Line 1,266:
}
}


</syntaxhighlight>
</lang>


=={{header|DataWeave}}==
=={{header|DataWeave}}==
<lang DataWeave>var arr = ["apple", "orange"]
<syntaxhighlight lang=DataWeave>var arr = ["apple", "orange"]
sizeOf(arr)
sizeOf(arr)
</syntaxhighlight>
</lang>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang delphi>
<syntaxhighlight lang=delphi>
showmessage( length(['a','b','c']).ToString );
showmessage( length(['a','b','c']).ToString );
</syntaxhighlight>
</lang>


=={{header|Diego}}==
=={{header|Diego}}==
<lang diego>set_namespace(rosettacode)_me();
<syntaxhighlight lang=diego>set_namespace(rosettacode)_me();


me_msg()_array()_values(apple,orange)_length();
me_msg()_array()_values(apple,orange)_length();
reset_namespace[];</lang>
reset_namespace[];</syntaxhighlight>
{{out}}
{{out}}
Line 1,290: Line 1,290:


=={{header|Dragon}}==
=={{header|Dragon}}==
<lang dragon>select "std"
<syntaxhighlight lang=dragon>select "std"


a = ["apple","orange"]
a = ["apple","orange"]
Line 1,296: Line 1,296:


show b
show b
</syntaxhighlight>
</lang>


=={{header|Dyalect}}==
=={{header|Dyalect}}==


<lang dyalect>var xs = ["apple", "orange"]
<syntaxhighlight lang=dyalect>var xs = ["apple", "orange"]
print(xs.Length())</lang>
print(xs.Length())</syntaxhighlight>


=={{header|EasyLang}}==
=={{header|EasyLang}}==
<lang>fruit$[] = [ "apples" "oranges" ]
<lang>fruit$[] = [ "apples" "oranges" ]
print len fruit$[]</lang>
print len fruit$[]</syntaxhighlight>


=={{header|EchoLisp}}==
=={{header|EchoLisp}}==
<lang scheme>
<syntaxhighlight lang=scheme>
(length '("apple" "orange")) ;; list
(length '("apple" "orange")) ;; list
→ 2
→ 2
(vector-length #("apple" "orange")) ;; vector
(vector-length #("apple" "orange")) ;; vector
→ 2
→ 2
</syntaxhighlight>
</lang>


=={{header|Ela}}==
=={{header|Ela}}==
<lang ela>length [1..10]</lang>
<syntaxhighlight lang=ela>length [1..10]</syntaxhighlight>


=={{header|Elena}}==
=={{header|Elena}}==
ELENA 5.0 :
ELENA 5.0 :
<lang elena>
<syntaxhighlight lang=elena>
var array := new string[]{"apple", "orange"};
var array := new string[]{"apple", "orange"};
var length := array.Length;
var length := array.Length;
</syntaxhighlight>
</lang>


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>iex(1)> length( ["apple", "orange"] ) # List
<syntaxhighlight lang=elixir>iex(1)> length( ["apple", "orange"] ) # List
2
2
iex(2)> tuple_size( {"apple", "orange"} ) # Tuple
iex(2)> tuple_size( {"apple", "orange"} ) # Tuple
2</lang>
2</syntaxhighlight>


=={{header|Elm}}==
=={{header|Elm}}==
<lang elm>
<syntaxhighlight lang=elm>
import Array
import Array
import Html
import Html
Line 1,343: Line 1,343:
|> Basics.toString
|> Basics.toString
|> Html.text
|> Html.text
</syntaxhighlight>
</lang>


=={{header|Emacs Lisp}}==
=={{header|Emacs Lisp}}==
<lang Lisp>(length ["apple" "orange"])
<syntaxhighlight lang=Lisp>(length ["apple" "orange"])
=> 2</lang>
=> 2</syntaxhighlight>


<code>length</code> also accepts a list or a string.
<code>length</code> also accepts a list or a string.


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang Erlang>
<syntaxhighlight lang=Erlang>
1> length(["apple", "orange"]). %using a list
1> length(["apple", "orange"]). %using a list
2
2
1> tuple_size({"apple", "orange"}). %using a tuple
1> tuple_size({"apple", "orange"}). %using a tuple
2
2
</syntaxhighlight>
</lang>




=={{header|Euphoria}}==
=={{header|Euphoria}}==
<lang Euphoria>
<syntaxhighlight lang=Euphoria>
sequence s = {"apple","orange",2.95} -- Euphoria doesn't care what you put in a sequence
sequence s = {"apple","orange",2.95} -- Euphoria doesn't care what you put in a sequence


Line 1,381: Line 1,381:
1 -- 2.95 is an atomic value
1 -- 2.95 is an atomic value


</syntaxhighlight>
</lang>


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>[|1;2;3|].Length |> printfn "%i"</lang>
<syntaxhighlight lang=fsharp>[|1;2;3|].Length |> printfn "%i"</syntaxhighlight>
Or:
Or:
<lang fsharp>[|1;2;3|] |> Array.length |> printfn "%i"</lang>
<syntaxhighlight lang=fsharp>[|1;2;3|] |> Array.length |> printfn "%i"</syntaxhighlight>


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>
<syntaxhighlight lang=factor>
{ "apple" "orange" } length
{ "apple" "orange" } length
</syntaxhighlight>
</lang>


=={{header|Forth}}==
=={{header|Forth}}==
Line 1,425: Line 1,425:
REPEAT
REPEAT
DROP
DROP
R> ; \ return counter to data stack </lang>
R> ; \ return counter to data stack </syntaxhighlight>
Test code at Forth console
Test code at Forth console
<lang forth>CREATE Q { " Apples" " Oranges" } q {len} . 2 ok</lang>
<syntaxhighlight lang=forth>CREATE Q { " Apples" " Oranges" } q {len} . 2 ok</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
Line 1,440: Line 1,440:
For a simple example, the WRITE(6,*) suffices: write to standard output (the 6), in free-format (the *).
For a simple example, the WRITE(6,*) suffices: write to standard output (the 6), in free-format (the *).


<lang Fortran>
<syntaxhighlight lang=Fortran>
MODULE EXAMPLE
MODULE EXAMPLE
CONTAINS
CONTAINS
Line 1,461: Line 1,461:
WRITE (6,*) "L. bound",LBOUND(ARRAY),", U. bound",UBOUND(ARRAY)
WRITE (6,*) "L. bound",LBOUND(ARRAY),", U. bound",UBOUND(ARRAY)
END
END
</syntaxhighlight>
</lang>


Output:
Output:
Line 1,475: Line 1,475:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang=freebasic>' FB 1.05.0 Win64


Dim fruit(1) As String = {"apple", "orange"}
Dim fruit(1) As String = {"apple", "orange"}
Line 1,482: Line 1,482:
Print
Print
Print "Press any key to quit the program"
Print "Press any key to quit the program"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,490: Line 1,490:


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>
<syntaxhighlight lang=frink>
a = ["apple", "orange"]
a = ["apple", "orange"]
println[length[a]]
println[length[a]]
</syntaxhighlight>
</lang>


=={{header|FurryScript}}==
=={{header|FurryScript}}==
<lang furryscript>THE_LIST( <apple> <orange> )
<syntaxhighlight lang=furryscript>THE_LIST( <apple> <orange> )
COUNT[ 0 SW ~| COUNT_STEP# 0 SW SU ]
COUNT[ 0 SW ~| COUNT_STEP# 0 SW SU ]
COUNT_STEP[ DR 1 SU ]
COUNT_STEP[ DR 1 SU ]


`THE_LIST COUNT# +<></lang>
`THE_LIST COUNT# +<></syntaxhighlight>


=={{header|Futhark}}==
=={{header|Futhark}}==
Line 1,506: Line 1,506:
The <code>shape</code> builtin returns the shape of an array as an array of integers. The length is element 0 of the shape:
The <code>shape</code> builtin returns the shape of an array as an array of integers. The length is element 0 of the shape:


<lang Futhark>
<syntaxhighlight lang=Futhark>
fun length(as: []int): int = (shape as)[0]
fun length(as: []int): int = (shape as)[0]
</syntaxhighlight>
</lang>


=={{header|FutureBasic}}==
=={{header|FutureBasic}}==
NSUInteger count = fn ArrayCount( ''array'' ). Example:
NSUInteger count = fn ArrayCount( ''array'' ). Example:
<lang futurebasic>
<syntaxhighlight lang=futurebasic>
window 1
window 1
print fn ArrayCount( @[@"apple",@"orange",@"cherry",@"grape",@"lemon"] )
print fn ArrayCount( @[@"apple",@"orange",@"cherry",@"grape",@"lemon"] )
HandleEvents
HandleEvents
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,532: Line 1,532:
=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=2a452c807c7030eb64a2f1d60d31a830 Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=2a452c807c7030eb64a2f1d60d31a830 Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang=gambas>Public Sub Main()
Dim siList As Short[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
Dim siList As Short[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]


Print siList.Count
Print siList.Count


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 1,544: Line 1,544:


=={{header|Genie}}==
=={{header|Genie}}==
<lang genie>[indent=4]
<syntaxhighlight lang=genie>[indent=4]
/* Array length, in Genie */
/* Array length, in Genie */
init
init
arr:array of string = {"apple", "orange"}
arr:array of string = {"apple", "orange"}
stdout.printf("%d ", arr.length)
stdout.printf("%d ", arr.length)
print arr[1]</lang>
print arr[1]</syntaxhighlight>


{{out}}
{{out}}
Line 1,558: Line 1,558:
=={{header|Go}}==
=={{header|Go}}==


<lang Go>package main
<syntaxhighlight lang=Go>package main


import "fmt"
import "fmt"
Line 1,566: Line 1,566:


fmt.Printf("Length of %v is %v.\n", arr, len(arr))
fmt.Printf("Length of %v is %v.\n", arr, len(arr))
}</lang>
}</syntaxhighlight>




Line 1,576: Line 1,576:
=={{header|Groovy}}==
=={{header|Groovy}}==


<lang Groovy>
<syntaxhighlight lang=Groovy>
def fruits = ['apple','orange']
def fruits = ['apple','orange']
println fruits.size()
println fruits.size()
</syntaxhighlight>
</lang>


=={{header|Harbour}}==
=={{header|Harbour}}==


<lang visualfoxpro>
<syntaxhighlight lang=visualfoxpro>
LOCAL aFruits := {"apple", "orange"}
LOCAL aFruits := {"apple", "orange"}
Qout( Len( aFruits ) ) // --> 2
Qout( Len( aFruits ) ) // --> 2
</syntaxhighlight>
</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==


<lang Haskell>-- [[Char]] -> Int
<syntaxhighlight lang=Haskell>-- [[Char]] -> Int
length ["apple", "orange"]</lang>
length ["apple", "orange"]</syntaxhighlight>


=={{header|hexiscript}}==
=={{header|hexiscript}}==
<lang hexiscript>let a arr 2
<syntaxhighlight lang=hexiscript>let a arr 2
let a[0] "apple"
let a[0] "apple"
let a[1] "orange"
let a[1] "orange"
println len a</lang>
println len a</syntaxhighlight>


=={{header|Hoon}}==
=={{header|Hoon}}==
<lang Hoon>|= arr=(list *) (lent arr)</lang>
<syntaxhighlight lang=Hoon>|= arr=(list *) (lent arr)</syntaxhighlight>


=={{header|i}}==
=={{header|i}}==
<lang i>main: print(#["apple", "orange"])</lang>
<syntaxhighlight lang=i>main: print(#["apple", "orange"])</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Icon, and therefore Unicon, includes a prefix size operator, star <code>*</code>. This operator can be applied to just about any data type or data structure.
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.


<lang unicon>write(*["apple", "orange"])</lang>
<syntaxhighlight lang=unicon>write(*["apple", "orange"])</syntaxhighlight>


=={{header|Idris}}==
=={{header|Idris}}==
<lang Idris>length ["apple", "orange"]</lang>
<syntaxhighlight lang=Idris>length ["apple", "orange"]</syntaxhighlight>


=={{header|J}}==
=={{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.
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.
<lang j> # 'apple';'orange'
<syntaxhighlight lang=j> # 'apple';'orange'
2
2
$ 'apple';'orange'
$ 'apple';'orange'
2</lang>
2</syntaxhighlight>
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.
For the list array example given, the result appears to be the same. The difference is that the result of Tally is a scalar (array of 0 dimensions) whereas the result of Shape Of is a list (1 dimensional array), of length 1 in this case.
<lang j> $#'apple';'orange'
<syntaxhighlight lang=j> $#'apple';'orange'


$$'apple';'orange'
$$'apple';'orange'
1</lang>
1</syntaxhighlight>
This might be a clearer concept with a few more examples. Here's an array with two dimensions:
This might be a clearer concept with a few more examples. Here's an array with two dimensions:
<lang j> >'apple';'orange'
<syntaxhighlight lang=j> >'apple';'orange'
apple
apple
orange
orange
Line 1,631: Line 1,631:
2 6
2 6
#>'apple';'orange'
#>'apple';'orange'
2</lang>
2</syntaxhighlight>
And, here's an array with no dimensions:
And, here's an array with no dimensions:
<lang> 9001
<lang> 9001
Line 1,638: Line 1,638:
1
1
$9001
$9001
</syntaxhighlight>
</lang>
You can count the number of dimensions of an array (the length of the list of lengths) using <code>#$array</code>:
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
#$9001
0
0
Line 1,646: Line 1,646:
1
1
#$>'apple';'orange'
#$>'apple';'orange'
2</lang>
2</syntaxhighlight>


=={{header|Janet}}==
=={{header|Janet}}==


<lang janet>
<syntaxhighlight lang=janet>
(def our-array @["apple" "orange"])
(def our-array @["apple" "orange"])
(length our-array)
(length our-array)
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 1,661: Line 1,661:


=={{header|Java}}==
=={{header|Java}}==
<lang java>public class ArrayLength {
<syntaxhighlight lang=java>public class ArrayLength {
public static void main(String[] args) {
public static void main(String[] args) {
System.out.println(new String[]{"apple", "orange"}.length);
System.out.println(new String[]{"apple", "orange"}.length);
}
}
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==


<lang javascript>console.log(['apple', 'orange'].length);</lang>
<syntaxhighlight lang=javascript>console.log(['apple', 'orange'].length);</syntaxhighlight>


However, determining the length of a list, array, or collection may simply be the wrong thing to do.
However, determining the length of a list, array, or collection may simply be the wrong thing to do.
Line 1,675: Line 1,675:
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'''
If, for example, the actual task (undefined here, unfortunately) requires retrieving the final item, while it is perfectly possible to write '''last''' in terms of '''length'''


<lang JavaScript>function last(lst) {
<syntaxhighlight lang=JavaScript>function last(lst) {
return lst[lst.length - 1];
return lst[lst.length - 1];
}</lang>
}</syntaxhighlight>


using length has the disadvantage that it leaves ''last'' simply undefined for an empty list.
using length has the disadvantage that it leaves ''last'' simply undefined for an empty list.
Line 1,683: Line 1,683:
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.
We might do better to drop the narrow focus on length, and instead use a fold (''reduce'', in JS terms) which can return a default value of some kind.


<lang JavaScript>function last(lst) {
<syntaxhighlight lang=JavaScript>function last(lst) {
return lst.reduce(function (a, x) {
return lst.reduce(function (a, x) {
return x;
return x;
}, null);
}, null);
}</lang>
}</syntaxhighlight>


Alternatively, rather than scanning the entire list to simply get the final value, it might sometimes be better to test the length:
Alternatively, rather than scanning the entire list to simply get the final value, it might sometimes be better to test the length:


<lang JavaScript>function last(list, defaultValue) {
<syntaxhighlight lang=JavaScript>function last(list, defaultValue) {
return list.length ?list[list.length-1] :defaultValue;
return list.length ?list[list.length-1] :defaultValue;
}</lang>
}</syntaxhighlight>


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):
Or use other built-in functions – this, for example, seems fairly clear, and is already 100+ times faster than unoptimised tail recursion in ES5 (testing with a list of 1000 elements):


<lang JavaScript>function last(list, defaultValue) {
<syntaxhighlight lang=JavaScript>function last(list, defaultValue) {
return list.slice(-1)[0] || defaultValue;
return list.slice(-1)[0] || defaultValue;
}</lang>
}</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==


<lang jq>["apple","orange"] | length</lang>
<syntaxhighlight lang=jq>["apple","orange"] | length</syntaxhighlight>
Output:
Output:
<lang sh>2</lang>
<syntaxhighlight lang=sh>2</syntaxhighlight>


Note that the ''length'' filter is polymorphic, so for example the empty string (""), the empty list ([]), and ''null'' all have ''length'' 0.
Note that the ''length'' filter is polymorphic, so for example the empty string (""), the empty list ([]), and ''null'' all have ''length'' 0.


=={{header|Jsish}}==
=={{header|Jsish}}==
<lang javascript>/* Array length, in jsish */
<syntaxhighlight lang=javascript>/* Array length, in jsish */
var arr = new Array('apple', 'orange');
var arr = new Array('apple', 'orange');
puts(arr.length);
puts(arr.length);
puts(arr[1]);</lang>
puts(arr[1]);</syntaxhighlight>


{{out}}
{{out}}
Line 1,722: Line 1,722:
=={{header|Julia}}==
=={{header|Julia}}==


<lang Julia>
<syntaxhighlight lang=Julia>
a = ["apple","orange"]
a = ["apple","orange"]
length(a)
length(a)
</syntaxhighlight>
</lang>


=={{header|Klingphix}}==
=={{header|Klingphix}}==
<lang Klingphix>include ..\Utilitys.tlhy
<syntaxhighlight lang=Klingphix>include ..\Utilitys.tlhy


( "apple" "orange" ) len print
( "apple" "orange" ) len print


" " input</lang>
" " input</syntaxhighlight>
{{out}}
{{out}}
<pre>2</pre>
<pre>2</pre>
Line 1,738: Line 1,738:
=={{header|Klong}}==
=={{header|Klong}}==


<syntaxhighlight lang=K>
<lang K>
#["apple" "orange"]
#["apple" "orange"]
</syntaxhighlight>
</lang>


=={{header|Kotlin}}==
=={{header|Kotlin}}==


<lang scala>fun main(args: Array<String>) {
<syntaxhighlight lang=scala>fun main(args: Array<String>) {
println(arrayOf("apple", "orange").size)
println(arrayOf("apple", "orange").size)
}</lang>
}</syntaxhighlight>


=={{header|Lambdatalk}}==
=={{header|Lambdatalk}}==
<lang scheme>
<syntaxhighlight lang=scheme>
{A.length {A.new 1 2 3}}
{A.length {A.new 1 2 3}}
-> 3
-> 3
</syntaxhighlight>
</lang>


=={{header|Latitude}}==
=={{header|Latitude}}==
Line 1,758: Line 1,758:
In Latitude, <code>length</code> and <code>size</code> are synonymous and will both retrieve the size of a collection.
In Latitude, <code>length</code> and <code>size</code> are synonymous and will both retrieve the size of a collection.


<lang latitude>println: ["apple", "orange"] length.</lang>
<syntaxhighlight lang=latitude>println: ["apple", "orange"] length.</syntaxhighlight>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
Line 1,770: Line 1,770:
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/
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}}
{{works with|LB Booster}}
<syntaxhighlight lang=lb>
<lang lb>
FruitList$(0)="apple" 'assign 2 cells of a list array
FruitList$(0)="apple" 'assign 2 cells of a list array
FruitList$(1)="orange"
FruitList$(1)="orange"
Line 1,882: Line 1,882:
print ")"
print ")"
end sub
end sub
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,893: Line 1,893:
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.
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.


<lang tcl># Array length, in LIL
<syntaxhighlight lang=tcl># Array length, in LIL
set a [list "apple"]
set a [list "apple"]
append a "orange"
append a "orange"
print [count $a]
print [count $a]
print [index $a 1]</lang>
print [index $a 1]</syntaxhighlight>


{{out}}
{{out}}
Line 1,905: Line 1,905:


=={{header|Limbo}}==
=={{header|Limbo}}==
<lang Limbo>implement Command;
<syntaxhighlight lang=Limbo>implement Command;


include "sys.m";
include "sys.m";
Line 1,920: Line 1,920:
a := array[] of {"apple", "orange"};
a := array[] of {"apple", "orange"};
sys->print("length of a: %d\n", len a);
sys->print("length of a: %d\n", len a);
}</lang>
}</syntaxhighlight>


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>fruits = ["apple", "orange"]
<syntaxhighlight lang=lingo>fruits = ["apple", "orange"]
put fruits.count
put fruits.count
-- 2</lang>
-- 2</syntaxhighlight>


=={{header|Little}}==
=={{header|Little}}==
<lang C>string fruit[] = {"apples", "oranges"};
<syntaxhighlight lang=C>string fruit[] = {"apples", "oranges"};
puts(length(fruit));</lang>
puts(length(fruit));</syntaxhighlight>


=={{header|LiveCode}}==
=={{header|LiveCode}}==


<lang LiveCode>put "apple","orange" into fruit
<syntaxhighlight lang=LiveCode>put "apple","orange" into fruit
split fruit using comma
split fruit using comma
answer the number of elements of fruit</lang>
answer the number of elements of fruit</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang Lua>-- For tables as simple arrays, use the # operator:
<syntaxhighlight lang=Lua>-- For tables as simple arrays, use the # operator:
fruits = {"apple", "orange"}
fruits = {"apple", "orange"}
print(#fruits)
print(#fruits)
Line 1,955: Line 1,955:
end
end


print(size(fruits))</lang>
print(size(fruits))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,964: Line 1,964:


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<lang M2000 Interpreter>
<syntaxhighlight lang=M2000 Interpreter>
\\ A is a pointer to array
\\ A is a pointer to array
A=("Apple", "Orange")
A=("Apple", "Orange")
Line 2,003: Line 2,003:
Dim K(1,1,1,1,1,1) ' Maximum 10 dimensions
Dim K(1,1,1,1,1,1) ' Maximum 10 dimensions
Print Len(K()=1 ' True
Print Len(K()=1 ' True
</syntaxhighlight>
</lang>


=={{header|Maple}}==
=={{header|Maple}}==
<lang maple>a := Array(["apple", "orange"]);
<syntaxhighlight lang=maple>a := Array(["apple", "orange"]);
numelems(a);</lang>
numelems(a);</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,015: Line 2,015:


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>Length[{"apple", "orange"}]</lang>
<syntaxhighlight lang=Mathematica>Length[{"apple", "orange"}]</syntaxhighlight>


=={{header|MATLAB}} / {{header|Octave}}==
=={{header|MATLAB}} / {{header|Octave}}==
<lang Matlab>length({'apple', 'orange'})</lang>
<syntaxhighlight lang=Matlab>length({'apple', 'orange'})</syntaxhighlight>
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.
For arrays with more than one dimension, length reports the length of the larges dimension. The number of elements in a multi-dimensional array can be obtained with numel.
<lang Matlab>numel({'apple', 'orange'; 'pear', 'banana'})</lang>
<syntaxhighlight lang=Matlab>numel({'apple', 'orange'; 'pear', 'banana'})</syntaxhighlight>


=={{header|Modula-3}}==
=={{header|Modula-3}}==
<lang modula3>MODULE ArrayLength EXPORTS Main;
<syntaxhighlight lang=modula3>MODULE ArrayLength EXPORTS Main;


IMPORT IO;
IMPORT IO;
Line 2,032: Line 2,032:
BEGIN
BEGIN
IO.PutInt(NUMBER(Arr));
IO.PutInt(NUMBER(Arr));
END ArrayLength.</lang>
END ArrayLength.</syntaxhighlight>


=={{header|Mercury}}==
=={{header|Mercury}}==
<lang Mercury>:- module array_length.
<syntaxhighlight lang=Mercury>:- module array_length.
:- interface.
:- interface.


Line 2,047: Line 2,047:
main(!IO) :-
main(!IO) :-
Array = array(["apples", "oranges"]),
Array = array(["apples", "oranges"]),
io.write_int(size(Array), !IO).</lang>
io.write_int(size(Array), !IO).</syntaxhighlight>


=={{header|min}}==
=={{header|min}}==
{{works with|min|0.19.3}}
{{works with|min|0.19.3}}
<lang min>("apple" "orange") size print</lang>
<syntaxhighlight lang=min>("apple" "orange") size print</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,058: Line 2,058:


=={{header|MiniScript}}==
=={{header|MiniScript}}==
<lang MiniScript>
<syntaxhighlight lang=MiniScript>
fruits = ["apple", "orange"]
fruits = ["apple", "orange"]
print fruits.len
print fruits.len
</syntaxhighlight>
</lang>
=={{header|MiniZinc}}==
=={{header|MiniZinc}}==
<lang MiniZinc>
<syntaxhighlight lang=MiniZinc>
array[int] of int: arr = [1,2,3];
array[int] of int: arr = [1,2,3];
var int: size = length(arr);
var int: size = length(arr);
Line 2,070: Line 2,070:


output [show(size),"\n"];
output [show(size),"\n"];
</syntaxhighlight>
</lang>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
<lang nanoquery>fruit = array(2)
<syntaxhighlight lang=nanoquery>fruit = array(2)
fruit[0] = "apple"
fruit[0] = "apple"
fruit[1] = "orange"
fruit[1] = "orange"
println len(fruit)
println len(fruit)


// outputs 2</lang>
// outputs 2</syntaxhighlight>


=={{header|Neko}}==
=={{header|Neko}}==
<lang neko>var fruit = $array("apple", "orange");
<syntaxhighlight lang=neko>var fruit = $array("apple", "orange");


$print($asize(fruit));</lang>
$print($asize(fruit));</syntaxhighlight>


=={{header|NewLISP}}==
=={{header|NewLISP}}==
<lang newlisp>(println (length '("apple" "orange")))
<syntaxhighlight lang=newlisp>(println (length '("apple" "orange")))


; Nehal-Singhal 2018-05-25
; Nehal-Singhal 2018-05-25
(length '(apple orange))</lang>
(length '(apple orange))</syntaxhighlight>


=={{header|NGS}}==
=={{header|NGS}}==
<lang NGS>echo(len(['apple', 'orange']))
<syntaxhighlight lang=NGS>echo(len(['apple', 'orange']))
# same
# same
echo(['apple', 'orange'].len())</lang>
echo(['apple', 'orange'].len())</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>let fruit = ["apple", "orange"]
<syntaxhighlight lang=nim>let fruit = ["apple", "orange"]
echo "The length of the fruit array is ", len(fruit)</lang>
echo "The length of the fruit array is ", len(fruit)</syntaxhighlight>


{{out}}
{{out}}
Line 2,107: Line 2,107:
=={{header|Oberon-2}}==
=={{header|Oberon-2}}==
{{works with|oo2c}}
{{works with|oo2c}}
<lang oberon2>
<syntaxhighlight lang=oberon2>
MODULE ArrayLength;
MODULE ArrayLength;
IMPORT
IMPORT
Line 2,139: Line 2,139:
Out.String("length: ");Out.Int(Length(a),0);Out.Ln
Out.String("length: ");Out.Int(Length(a),0);Out.Ln
END ArrayLength.
END ArrayLength.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,146: Line 2,146:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>
<syntaxhighlight lang=objeck>
class Test {
class Test {
function : Main(args : String[]) ~ Nil {
function : Main(args : String[]) ~ Nil {
Line 2,152: Line 2,152:
fruit->Size()->PrintLine();
fruit->Size()->PrintLine();
}
}
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang OCaml>
<syntaxhighlight lang=OCaml>
Array.length [|"apple"; "orange"|];;
Array.length [|"apple"; "orange"|];;
</syntaxhighlight>
</lang>


=={{header|Oforth}}==
=={{header|Oforth}}==
<lang Oforth>[ "apple", "orange" ] size</lang>
<syntaxhighlight lang=Oforth>[ "apple", "orange" ] size</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
All of these methods are equivalent.
All of these methods are equivalent.
<lang scheme>
<syntaxhighlight lang=scheme>
(print (vector-length (vector "apple" "orange")))
(print (vector-length (vector "apple" "orange")))
(print (vector-length #("apple" "orange")))
(print (vector-length #("apple" "orange")))
Line 2,170: Line 2,170:


(print (size #("apple" "orange")))
(print (size #("apple" "orange")))
</syntaxhighlight>
</lang>


=={{header|Onyx}}==
=={{header|Onyx}}==


<lang onyx>[`apple' `orange'] length # leaves 2 on top of the stack</lang>
<syntaxhighlight lang=onyx>[`apple' `orange'] length # leaves 2 on top of the stack</syntaxhighlight>


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang oorexx>
<syntaxhighlight lang=oorexx>
/* REXX */
/* REXX */
a = .array~of('apple','orange')
a = .array~of('apple','orange')
Line 2,184: Line 2,184:
say e
say e
End
End
Say "a[2]="a[2]</lang>
Say "a[2]="a[2]</syntaxhighlight>
{{out}}
{{out}}
<pre>2 elements
<pre>2 elements
Line 2,192: Line 2,192:


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
<lang parigp>array = ["apple", "orange"]
<syntaxhighlight lang=parigp>array = ["apple", "orange"]
length(array) \\ == 2
length(array) \\ == 2
#array \\ == 2</lang>
#array \\ == 2</syntaxhighlight>


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.
The <code>#</code> syntax is a handy shorthand. It usually looks best just on variables but it works on expressions too, possibly with parens to control precedence.
Line 2,204: Line 2,204:
{{works with|Free Pascal|2.6.2}}
{{works with|Free Pascal|2.6.2}}


<lang Pascal>
<syntaxhighlight lang=Pascal>
#!/usr/bin/instantfpc
#!/usr/bin/instantfpc
//program ArrayLength;
//program ArrayLength;
Line 2,219: Line 2,219:
WriteLn('Length of Fruits by bounds : ', High(Fruits) - Low(Fruits) + 1);
WriteLn('Length of Fruits by bounds : ', High(Fruits) - Low(Fruits) + 1);
END.
END.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,233: Line 2,233:
The way to get the number of elements of an array in Perl is to put the array in scalar context.
The way to get the number of elements of an array in Perl is to put the array in scalar context.


<lang perl>my @array = qw "apple orange banana", 4, 42;
<syntaxhighlight lang=perl>my @array = qw "apple orange banana", 4, 42;


scalar @array; # 5
scalar @array; # 5
Line 2,252: Line 2,252:
takes_a_scalar @array;
takes_a_scalar @array;


# the built-ins can also act like they have prototypes</lang>
# the built-ins can also act like they have prototypes</syntaxhighlight>


A common mistake is to use <code>length</code> which works on strings not arrays.
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.
So using it on an array, as a side-effect, actually gives you a number which represents the order of magnitude.


<lang perl>length '' . @array; # 1
<syntaxhighlight lang=perl>length '' . @array; # 1
length @array; # 1
length @array; # 1


Line 2,267: Line 2,267:
print 'the length of @array is on the order of ';
print 'the length of @array is on the order of ';
print 10 ** (length( @array )-1); # 100
print 10 ** (length( @array )-1); # 100
print " elements long\n";</lang>
print " elements long\n";</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{libheader|Phix/basics}}
<!--<lang Phix>-->
<!--<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>
<span style="color: #008080;">constant</span> <span style="color: #000000;">fruits</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{<span style="color: #008000;">"apple"<span style="color: #0000FF;">,<span style="color: #008000;">"orange"<span style="color: #0000FF;">}</span>
<span style="color: #0000FF;">?<span style="color: #7060A8;">length<span style="color: #0000FF;">(<span style="color: #000000;">fruits<span style="color: #0000FF;">)
<span style="color: #0000FF;">?<span style="color: #7060A8;">length<span style="color: #0000FF;">(<span style="color: #000000;">fruits<span style="color: #0000FF;">)
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,281: Line 2,281:


=={{header|Phixmonti}}==
=={{header|Phixmonti}}==
<lang Phixmonti>"apple" "orange" stklen tolist len print</lang>
<syntaxhighlight lang=Phixmonti>"apple" "orange" stklen tolist len print</syntaxhighlight>
With syntactic sugar
With syntactic sugar
<lang Phixmonti>include ..\Utilitys.pmt
<syntaxhighlight lang=Phixmonti>include ..\Utilitys.pmt
( "apple" "orange" ) len print</lang>
( "apple" "orange" ) len print</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,292: Line 2,292:
=={{header|PHP}}==
=={{header|PHP}}==


<lang php>print count(['apple', 'orange']); // Returns 2</lang>
<syntaxhighlight lang=php>print count(['apple', 'orange']); // Returns 2</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
Line 2,300: Line 2,300:
println(length(L)),
println(length(L)),
println(L.len),
println(L.len),
println(L.length).</lang>
println(L.length).</syntaxhighlight>


{{out}}
{{out}}
Line 2,310: Line 2,310:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>: (length '(apple orange))
<syntaxhighlight lang=PicoLisp>: (length '(apple orange))
-> 2
-> 2
:</lang>
:</syntaxhighlight>


=={{header|Pike}}==
=={{header|Pike}}==
<lang pike>void main()
<syntaxhighlight lang=pike>void main()
{
{
array fruit = ({ "apple", "orange" });
array fruit = ({ "apple", "orange" });
write("%d\n", sizeof(fruit));
write("%d\n", sizeof(fruit));
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,325: Line 2,325:


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang pli> p: Proc Options(main);
<syntaxhighlight lang=pli> p: Proc Options(main);
Dcl a(2) Char(6) Varying Init('apple','orange');
Dcl a(2) Char(6) Varying Init('apple','orange');
Put Edit('Array a has',(hbound(a)-lbound(a)+1),' elements.')
Put Edit('Array a has',(hbound(a)-lbound(a)+1),' elements.')
(Skip,a,f(2),a);
(Skip,a,f(2),a);
Put Skip Data(a);
Put Skip Data(a);
End;</lang>
End;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,337: Line 2,337:


=={{header|Plorth}}==
=={{header|Plorth}}==
<lang plorth>["apple", "orange"] length println</lang>
<syntaxhighlight lang=plorth>["apple", "orange"] length println</syntaxhighlight>


=={{header|Pony}}==
=={{header|Pony}}==
<lang pony>
<syntaxhighlight lang=pony>
actor Main
actor Main
new create(env:Env)=>
new create(env:Env)=>
Line 2,347: Line 2,347:
c.push("orange")
c.push("orange")
env.out.print("Array c is " + c.size().string() + " elements long!")
env.out.print("Array c is " + c.size().string() + " elements long!")
</syntaxhighlight>
</lang>


=={{header|Potion}}==
=={{header|Potion}}==
<lang potion>("apple", "orange") length print</lang>
<syntaxhighlight lang=potion>("apple", "orange") length print</syntaxhighlight>


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang PowerShell>
<syntaxhighlight lang=PowerShell>
$Array = @( "Apple", "Orange" )
$Array = @( "Apple", "Orange" )
$Array.Count
$Array.Count
$Array.Length</lang>
$Array.Length</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,363: Line 2,363:


=={{header|Processing}}==
=={{header|Processing}}==
<lang Processing>
<syntaxhighlight lang=Processing>
String[] arr = {"apple", "orange"};
String[] arr = {"apple", "orange"};
void setup(){
void setup(){
println(arr.length);
println(arr.length);
}
}
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,375: Line 2,375:


==={{header|Processing Python mode}}===
==={{header|Processing Python mode}}===
<lang python>
<syntaxhighlight lang=python>
arr = ['apple', 'orange'] # a list for an array
arr = ['apple', 'orange'] # a list for an array


def setup():
def setup():
println(len(arr))
println(len(arr))
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,388: Line 2,388:


=={{header|Prolog}}==
=={{header|Prolog}}==
<lang Prolog>| ?- length(["apple", "orange"], X).
<syntaxhighlight lang=Prolog>| ?- length(["apple", "orange"], X).


X = 2
X = 2


yes</lang>
yes</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>
<syntaxhighlight lang=PureBasic>
EnableExplicit
EnableExplicit
Define Dim fruit$(1); defines array with 2 elements at indices 0 and 1
Define Dim fruit$(1); defines array with 2 elements at indices 0 and 1
Line 2,408: Line 2,408:
CloseConsole()
CloseConsole()
EndIf
EndIf
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,415: Line 2,415:


An abbreviated form of the above, not printing to console/terminal
An abbreviated form of the above, not printing to console/terminal
<lang PureBasic>
<syntaxhighlight lang=PureBasic>
Dim fruit$(1); defines array with 2 elements at indices 0 and 1
Dim fruit$(1); defines array with 2 elements at indices 0 and 1
fruit$(0) = "apple"
fruit$(0) = "apple"
fruit$(1) = "orange"
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.
Debug ArraySize(fruit$()) + 1 ;the number of elements is equal to the size + 1. For example: Dim a(2) contains 3 elements from a(0) to a(2) for a size of 2.
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,427: Line 2,427:


=={{header|Python}}==
=={{header|Python}}==
<lang python>>>> print(len(['apple', 'orange']))
<syntaxhighlight lang=python>>>> print(len(['apple', 'orange']))
2
2
>>> </lang>
>>> </syntaxhighlight>


=={{header|QB64}}==
=={{header|QB64}}==


<lang QB64>
<syntaxhighlight lang=QB64>
Dim max As Integer, Index As Integer
Dim max As Integer, Index As Integer
Randomize Timer
Randomize Timer
Line 2,444: Line 2,444:
Print UBound(Stringar)
Print UBound(Stringar)
End
End
</syntaxhighlight>
</lang>
=={{header|Quackery}}==
=={{header|Quackery}}==


<Lang Quackery> $ "apples" $ "oranges" 2 pack size echo</lang>
<Lang Quackery> $ "apples" $ "oranges" 2 pack size echo</syntaxhighlight>


{{out}}
{{out}}
Line 2,454: Line 2,454:


=={{header|R}}==
=={{header|R}}==
<syntaxhighlight lang=R>
<lang R>
a <- c('apple','orange') # create a vector containing "apple" and "orange"
a <- c('apple','orange') # create a vector containing "apple" and "orange"
length(a)
length(a)
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,465: Line 2,465:
=={{header|Racket}}==
=={{header|Racket}}==
{{trans|EchoLisp}}
{{trans|EchoLisp}}
<lang racket>#lang racket/base
<syntaxhighlight lang=racket>#lang racket/base
(length '("apple" "orange")) ;; list
(length '("apple" "orange")) ;; list
(vector-length #("apple" "orange")) ;; vector</lang>
(vector-length #("apple" "orange")) ;; vector</syntaxhighlight>
{{out}}
{{out}}
<pre>2
<pre>2
Line 2,478: Line 2,478:
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.
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.


<lang perl6>
<syntaxhighlight lang=perl6>
my @array = <apple orange>;
my @array = <apple orange>;


Line 2,485: Line 2,485:
say + @array; # 2
say + @array; # 2
say @array + 0; # 2
say @array + 0; # 2
</syntaxhighlight>
</lang>


Watch out for infinite/lazy arrays though. You can't get the length of those.
Watch out for infinite/lazy arrays though. You can't get the length of those.


<lang perl6>my @infinite = 1 .. Inf; # 1, 2, 3, 4, ...
<syntaxhighlight lang=perl6>my @infinite = 1 .. Inf; # 1, 2, 3, 4, ...


say @infinite[5000]; # 5001
say @infinite[5000]; # 5001
say @infinite.elems; # Throws exception "Cannot .elems a lazy list"
say @infinite.elems; # Throws exception "Cannot .elems a lazy list"
</syntaxhighlight>
</lang>


=={{header|Rapira}}==
=={{header|Rapira}}==
<lang Rapira>arr := <* "apple", "orange" *>
<syntaxhighlight lang=Rapira>arr := <* "apple", "orange" *>
output: #arr</lang>
output: #arr</syntaxhighlight>


=={{header|Red}}==
=={{header|Red}}==
<lang Red>length? ["apples" "oranges"]
<syntaxhighlight lang=Red>length? ["apples" "oranges"]
== 2</lang>
== 2</syntaxhighlight>


=={{header|Relation}}==
=={{header|Relation}}==
<lang Relation>
<syntaxhighlight lang=Relation>
relation fruit
relation fruit
insert "apples"
insert "apples"
Line 2,510: Line 2,510:
project fruit count
project fruit count
print
print
</syntaxhighlight>
</lang>


{| border=1
{| border=1
Line 2,520: Line 2,520:


=={{header|ReScript}}==
=={{header|ReScript}}==
<lang rescript>let fruits = ["apple", "orange"]
<syntaxhighlight lang=rescript>let fruits = ["apple", "orange"]


Js.log(Js.Array.length(fruits))</lang>
Js.log(Js.Array.length(fruits))</syntaxhighlight>


<lang html><!DOCTYPE html>
<syntaxhighlight lang=html><!DOCTYPE html>
<html>
<html>
<head>
<head>
Line 2,537: Line 2,537:


</body>
</body>
</html></lang>
</html></syntaxhighlight>
{{out}}
{{out}}
<pre>// Generated by ReScript, PLEASE EDIT WITH CARE
<pre>// Generated by ReScript, PLEASE EDIT WITH CARE
Line 2,554: Line 2,554:


=={{header|REXX}}==
=={{header|REXX}}==
<lang rexx>/* REXX ----------------------------------------------
<syntaxhighlight lang=rexx>/* REXX ----------------------------------------------
* The compond variable a. implements an array
* The compond variable a. implements an array
* By convention, a.0 contains the number of elements
* By convention, a.0 contains the number of elements
Line 2,570: Line 2,570:
a.z=arg(1)
a.z=arg(1)
a.0=z
a.0=z
Return</lang>
Return</syntaxhighlight>
{{out}}
{{out}}
<pre>There are 2 elements in the array:
<pre>There are 2 elements in the array:
Line 2,578: Line 2,578:
=={{header|Ring}}==
=={{header|Ring}}==


<lang python>See len(['apple', 'orange']) # output = 2 </lang>
<syntaxhighlight lang=python>See len(['apple', 'orange']) # output = 2 </syntaxhighlight>


=={{header|Robotic}}==
=={{header|Robotic}}==
Line 2,584: Line 2,584:


Example 1:
Example 1:
<lang robotic>
<syntaxhighlight lang=robotic>
set "index" to 0
set "index" to 0
set "$array&index&" to "apple"
set "$array&index&" to "apple"
Line 2,590: Line 2,590:
set "$array&index&" to "orange"
set "$array&index&" to "orange"
* "Array length: ('index' + 1)"
* "Array length: ('index' + 1)"
</syntaxhighlight>
</lang>


Example 2:
Example 2:
<lang robotic>
<syntaxhighlight lang=robotic>
set "index" to 0
set "index" to 0
set "local1" to random 1 to 99
set "local1" to random 1 to 99
Line 2,602: Line 2,602:
if "local1" > 1 then "rand"
if "local1" > 1 then "rand"
* "Array length: ('index')"
* "Array length: ('index')"
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==


<lang ruby>puts ['apple', 'orange'].length # or .size</lang>
<syntaxhighlight lang=ruby>puts ['apple', 'orange'].length # or .size</syntaxhighlight>


=={{header|Rust}}==
=={{header|Rust}}==
Line 2,612: Line 2,612:
By default arrays are immutable in rust.
By default arrays are immutable in rust.


<lang rust>
<syntaxhighlight lang=rust>
fn main() {
fn main() {
let array = ["foo", "bar", "baz", "biff"];
let array = ["foo", "bar", "baz", "biff"];
println!("the array has {} elements", array.len());
println!("the array has {} elements", array.len());
}
}
</syntaxhighlight>
</lang>


=={{header|Scala}}==
=={{header|Scala}}==


<lang scala>
<syntaxhighlight lang=scala>
println(Array("apple", "orange").length)
println(Array("apple", "orange").length)
</syntaxhighlight>
</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==
Line 2,629: Line 2,629:
Using Scheme's vector type as an equivalent to an array:
Using Scheme's vector type as an equivalent to an array:


<lang scheme>
<syntaxhighlight lang=scheme>
(display (vector-length #("apple" "orange")))
(display (vector-length #("apple" "orange")))
</syntaxhighlight>
</lang>


=={{header|Seed7}}==
=={{header|Seed7}}==
The function [http://seed7.sourceforge.net/libraries/array.htm#length(in_arrayType) length]
The function [http://seed7.sourceforge.net/libraries/array.htm#length(in_arrayType) length]
determines the length of an array.
determines the length of an array.
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang=seed7>$ include "seed7_05.s7i";


const array string: anArray is [] ("apple", "orange");
const array string: anArray is [] ("apple", "orange");
Line 2,643: Line 2,643:
begin
begin
writeln(length(anArray));
writeln(length(anArray));
end func;</lang>
end func;</syntaxhighlight>


=={{header|SenseTalk}}==
=={{header|SenseTalk}}==
<lang sensetalk>put ("apple", "orange", "pear", "banana", "aubergine") into fruits
<syntaxhighlight lang=sensetalk>put ("apple", "orange", "pear", "banana", "aubergine") into fruits
put the number of items in fruits</lang>
put the number of items in fruits</syntaxhighlight>


=={{header|Shen}}==
=={{header|Shen}}==
<lang shen>
<syntaxhighlight lang=shen>
\\ Using a vector
\\ Using a vector
\\ @v creates the vector
\\ @v creates the vector
Line 2,661: Line 2,661:
\\ As an list
\\ As an list
(length [apple orange])
(length [apple orange])
</syntaxhighlight>
</lang>


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>var arr = ['apple', 'orange'];
<syntaxhighlight lang=ruby>var arr = ['apple', 'orange'];
say arr.len; #=> 2
say arr.len; #=> 2
say arr.end; #=> 1 (zero based)</lang>
say arr.end; #=> 1 (zero based)</syntaxhighlight>


=={{header|Simula}}==
=={{header|Simula}}==
<lang simula>COMMENT ARRAY-LENGTH;
<syntaxhighlight lang=simula>COMMENT ARRAY-LENGTH;
BEGIN
BEGIN


Line 2,685: Line 2,685:
OUTIMAGE;
OUTIMAGE;
END
END
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 2,692: Line 2,692:


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>
<syntaxhighlight lang=smalltalk>
a := #('apple' 'orange').
a := #('apple' 'orange').
a size</lang>
a size</syntaxhighlight>


=={{header|SNOBOL4}}==
=={{header|SNOBOL4}}==
<lang SNOBOL4> ar = ARRAY('2,2')
<syntaxhighlight lang=SNOBOL4> ar = ARRAY('2,2')
ar<1,1> = 'apple'
ar<1,1> = 'apple'
ar<1,2> = 'first'
ar<1,2> = 'first'
Line 2,703: Line 2,703:
ar<2,2> = 'second'
ar<2,2> = 'second'
OUTPUT = IDENT(DATATYPE(ar), 'ARRAY') PROTOTYPE(ar)
OUTPUT = IDENT(DATATYPE(ar), 'ARRAY') PROTOTYPE(ar)
end</lang>
end</syntaxhighlight>
{{out}}<pre>2,2</pre>
{{out}}<pre>2,2</pre>


=={{header|SPL}}==
=={{header|SPL}}==
<lang spl>a = ["apple","orange"]
<syntaxhighlight lang=spl>a = ["apple","orange"]
#.output("Number of elements in array: ",#.size(a,1))</lang>
#.output("Number of elements in array: ",#.size(a,1))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,716: Line 2,716:
=={{header|SQL}}==
=={{header|SQL}}==


<lang sql>SELECT COUNT() FROM (VALUES ('apple'),('orange'));</lang>
<syntaxhighlight lang=sql>SELECT COUNT() FROM (VALUES ('apple'),('orange'));</syntaxhighlight>


=={{header|Standard ML}}==
=={{header|Standard ML}}==
<lang sml>let
<syntaxhighlight lang=sml>let
val a = Array.fromList ["apple", "orange"]
val a = Array.fromList ["apple", "orange"]
in
in
Array.length a
Array.length a
end;</lang>
end;</syntaxhighlight>


=={{header|Stata}}==
=={{header|Stata}}==
Line 2,729: Line 2,729:


=== Dimensions of a dataset ===
=== Dimensions of a dataset ===
<lang stata>clear
<syntaxhighlight lang=stata>clear
input str10 fruit
input str10 fruit
apple
apple
Line 2,736: Line 2,736:


di _N
di _N
di c(N) " " c(k)</lang>
di c(N) " " c(k)</syntaxhighlight>


=== Length of a macro list ===
=== Length of a macro list ===
Line 2,742: Line 2,742:
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''.
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''.


<lang stata>local fruits apple orange
<syntaxhighlight lang=stata>local fruits apple orange
di `: list sizeof fruits'
di `: list sizeof fruits'
di `: word count `fruits''</lang>
di `: word count `fruits''</syntaxhighlight>


=== Mata ===
=== Mata ===
For a Mata array, use '''[https://www.stata.com/help.cgi?mf_rows rows]''' and similar functions:
For a Mata array, use '''[https://www.stata.com/help.cgi?mf_rows rows]''' and similar functions:


<lang stata>mata
<syntaxhighlight lang=stata>mata
a=st_sdata(.,"fruit")
a=st_sdata(.,"fruit")
rows(a)
rows(a)
cols(a)
cols(a)
length(a)
length(a)
end</lang>
end</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==


<lang Swift>let fruits = ["apple", "orange"] // Declare constant array literal
<syntaxhighlight lang=Swift>let fruits = ["apple", "orange"] // Declare constant array literal
let fruitsCount = fruits.count // Declare constant array length (count)
let fruitsCount = fruits.count // Declare constant array length (count)


print(fruitsCount) // Print array length to output window</lang>
print(fruitsCount) // Print array length to output window</syntaxhighlight>
{{out}}<pre>2</pre>
{{out}}<pre>2</pre>


=={{header|Symsyn}}==
=={{header|Symsyn}}==
<lang Symsyn>
<syntaxhighlight lang=Symsyn>
| Symsyn does not support Array of Strings
| Symsyn does not support Array of Strings
| The following code for an Array of Integers
| The following code for an Array of Integers
Line 2,779: Line 2,779:
sz []
sz []
| shows 2
| shows 2
</syntaxhighlight>
</lang>


=={{header|Tailspin}}==
=={{header|Tailspin}}==
<lang tailspin>
<syntaxhighlight lang=tailspin>
['apple', 'orange'] -> $::length -> !OUT::write
['apple', 'orange'] -> $::length -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>2</pre>
<pre>2</pre>
Line 2,791: Line 2,791:
<!-- http://ideone.com/uotEvm -->
<!-- http://ideone.com/uotEvm -->


<lang tcl>;# not recommended:
<syntaxhighlight lang=tcl>;# not recommended:
set mylistA {apple orange} ;# actually a string
set mylistA {apple orange} ;# actually a string
set mylistA "Apple Orange" ;# same - this works only for simple cases
set mylistA "Apple Orange" ;# same - this works only for simple cases
Line 2,804: Line 2,804:
set lenB [llength $mylistB]
set lenB [llength $mylistB]
puts "$mylistB : $lenB"
puts "$mylistB : $lenB"
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,813: Line 2,813:
{{works with|TI-83 2.55MP}}
{{works with|TI-83 2.55MP}}
Use function <code>dim()</code>.
Use function <code>dim()</code>.
<lang ti83b>{1,3,–5,4,–2,–1}→L1
<syntaxhighlight lang=ti83b>{1,3,–5,4,–2,–1}→L1
dim(L1)</lang>
dim(L1)</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,821: Line 2,821:


=={{header|Transd}}==
=={{header|Transd}}==
<lang scheme>#lang transd
<syntaxhighlight lang=scheme>#lang transd


MainModule : {
MainModule : {
Line 2,830: Line 2,830:
(lout (size ["apple", "orange"]))
(lout (size ["apple", "orange"]))
)
)
}</lang>{{out}}
}</syntaxhighlight>{{out}}
<pre>
<pre>
2
2
Line 2,837: Line 2,837:


=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==
<lang bash>#!/bin/bash
<syntaxhighlight lang=bash>#!/bin/bash
array=("orange" "apple")
array=("orange" "apple")
echo "${#array[@]}"</lang>
echo "${#array[@]}"</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,855: Line 2,855:


=={{header|Vala}}==
=={{header|Vala}}==
<lang vala>void main() {
<syntaxhighlight lang=vala>void main() {
string[] fruit = {"apple", "orange"};
string[] fruit = {"apple", "orange"};
stdout.printf("%d\n", fruit.length);
stdout.printf("%d\n", fruit.length);
}</lang>
}</syntaxhighlight>


Note that any of the following array declarations could be used:
Note that any of the following array declarations could be used:


<lang vala>
<syntaxhighlight lang=vala>
var fruit = new string[] { "apple", "orange" };
var fruit = new string[] { "apple", "orange" };
string[] fruit = new string[] { "apple", "orange" };
string[] fruit = new string[] { "apple", "orange" };
string[] fruit = { "apple", "orange" };
string[] fruit = { "apple", "orange" };
</syntaxhighlight>
</lang>


A shorter variant could also have been used:
A shorter variant could also have been used:


<lang vala>
<syntaxhighlight lang=vala>
void main() {
void main() {
stdout.printf("%d\n", new string[] {"apples", "orange"}.length);
stdout.printf("%d\n", new string[] {"apples", "orange"}.length);
}
}
</syntaxhighlight>
</lang>


=={{header|VBA}}==
=={{header|VBA}}==
One-liner. Assumes array lower bound, which is not always safe.
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:
Works regardless of lower bound:
<lang vb>Dim funkyArray(7 to 8) As String
<syntaxhighlight lang=vb>Dim funkyArray(7 to 8) As String


Public Function SizeOfArray(ar As Variant) As Long
Public Function SizeOfArray(ar As Variant) As Long
Line 2,888: Line 2,888:


'call the function
'call the function
Debug.Print "Array Length: " & SizeOfArray(funkyArray)</lang>
Debug.Print "Array Length: " & SizeOfArray(funkyArray)</syntaxhighlight>


{{Out}}
{{Out}}
Line 2,895: Line 2,895:


=={{header|VBScript}}==
=={{header|VBScript}}==
<lang vb>arr = Array("apple","orange")
<syntaxhighlight lang=vb>arr = Array("apple","orange")
WScript.StdOut.WriteLine UBound(arr) - LBound(arr) + 1 </lang>
WScript.StdOut.WriteLine UBound(arr) - LBound(arr) + 1 </syntaxhighlight>


{{Out}}
{{Out}}
Line 2,904: Line 2,904:
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.
The amount of elements in an array in Visual Basic is computed via the upper bound and lower bound indices. In Visual Basic the indices of arrays have to be numeric, but it is even possible to have negative values for them. Of course the element numbering is continuous.


<syntaxhighlight lang=vb>
<lang vb>
' declared in a module
' declared in a module
Public Function LengthOfArray(ByRef arr As Variant) As Long
Public Function LengthOfArray(ByRef arr As Variant) As Long
Line 2,931: Line 2,931:
Debug.Print LengthOfArray(arr) ' prints 2 as result
Debug.Print LengthOfArray(arr) ' prints 2 as result


</syntaxhighlight>
</lang>


=={{header|Visual Basic .NET}}==
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
{{works with|Visual Basic .NET|9.0+}}
<lang vbnet>Module ArrayLength
<syntaxhighlight lang=vbnet>Module ArrayLength


Sub Main()
Sub Main()
Line 2,943: Line 2,943:


End Module
End Module
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,952: Line 2,952:
=={{header|Vlang}}==
=={{header|Vlang}}==
A '''len''' property is maintained for all V arrays.
A '''len''' property is maintained for all V arrays.
<lang go>// V, array length
<syntaxhighlight lang=go>// V, array length
// Tectonics: v run array-length.v
// Tectonics: v run array-length.v
module main
module main
Line 2,960: Line 2,960:
arr := ["apple", "orange"]
arr := ["apple", "orange"]
println(arr.len)
println(arr.len)
}</lang>
}</syntaxhighlight>


{{out}}<pre>prompt$ v run array-length.v
{{out}}<pre>prompt$ v run array-length.v
Line 2,966: Line 2,966:


=={{header|WDTE}}==
=={{header|WDTE}}==
<lang wdte>let io => import 'io';
<syntaxhighlight lang=wdte>let io => import 'io';
let a => ['apple'; 'orange'];
let a => ['apple'; 'orange'];
len a -- io.writeln io.stdout;</lang>
len a -- io.writeln io.stdout;</syntaxhighlight>


=={{header|Wren}}==
=={{header|Wren}}==
<lang ecmascript>var arr = ["apple", "orange"]
<syntaxhighlight lang=ecmascript>var arr = ["apple", "orange"]
System.print(arr.count)</lang>
System.print(arr.count)</syntaxhighlight>


{{out}}
{{out}}
Line 2,980: Line 2,980:


=={{header|XLISP}}==
=={{header|XLISP}}==
<lang lisp>(vector-length #("apple" "orange"))</lang>
<syntaxhighlight lang=lisp>(vector-length #("apple" "orange"))</syntaxhighlight>




=={{header|Yabasic}}==
=={{header|Yabasic}}==
<lang yabasic>
<syntaxhighlight lang=yabasic>
dim fruta$(3)
dim fruta$(3)
read fruta$(1), fruta$(2), fruta$(3)
read fruta$(1), fruta$(2), fruta$(3)
Line 2,992: Line 2,992:
print fruta$(2)
print fruta$(2)
end
end
</syntaxhighlight>
</lang>
<pre>
<pre>
3
3
Line 3,004: Line 3,004:
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.
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.


<lang z80> org &8000
<syntaxhighlight lang=z80> org &8000
ld hl,TestArray
ld hl,TestArray
call GetArrayLength_WordData_NullTerminated
call GetArrayLength_WordData_NullTerminated
Line 3,048: Line 3,048:
byte "Apple",0
byte "Apple",0
Orange:
Orange:
byte "Orange",0</lang>
byte "Orange",0</syntaxhighlight>


{{out}}
{{out}}
Line 3,057: Line 3,057:
=={{header|zkl}}==
=={{header|zkl}}==
zkl doesn't support arrays natively, use lists instead.
zkl doesn't support arrays natively, use lists instead.
<lang zkl>List("apple", "orange").len().println() //-->2, == L("apple", "orange")
<syntaxhighlight lang=zkl>List("apple", "orange").len().println() //-->2, == L("apple", "orange")
T("apple", "orange").len().println() //-->2, read only list (ROList) </lang>
T("apple", "orange").len().println() //-->2, read only list (ROList) </syntaxhighlight>


=={{header|Zig}}==
=={{header|Zig}}==
<lang zig>const std = @import("std");
<syntaxhighlight lang=zig>const std = @import("std");


pub fn main() !void {
pub fn main() !void {
Line 3,069: Line 3,069:
// slices and arrays have an len field
// slices and arrays have an len field
try stdout_wr.print("fruit.len = {d}\n", .{fruit.len});
try stdout_wr.print("fruit.len = {d}\n", .{fruit.len});
}</lang>
}</syntaxhighlight>


=={{header|Zoea}}==
=={{header|Zoea}}==
<lang Zoea>
<syntaxhighlight lang=Zoea>
program: array_length
program: array_length
input: [a,b,c]
input: [a,b,c]
output: 3
output: 3
</syntaxhighlight>
</lang>


=={{header|Zoea Visual}}==
=={{header|Zoea Visual}}==
Line 3,082: Line 3,082:


=={{header|zonnon}}==
=={{header|zonnon}}==
<lang zonnon>
<syntaxhighlight lang=zonnon>
module AryLength;
module AryLength;
type
type
Line 3,097: Line 3,097:
writeln(len(b,1):4) (* second dimension *)
writeln(len(b,1):4) (* second dimension *)
end AryLength.
end AryLength.
</syntaxhighlight>
</lang>

Revision as of 01:26, 26 August 2022

Task
Array length
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Determine the amount of elements in an array.


As an example use an array holding the strings 'apple' and 'orange'.


Other tasks related to string operations:
Metrics
Counting
Remove/replace
Anagrams/Derangements/shuffling
Find/Search/Determine
Formatting
Song lyrics/poems/Mad Libs/phrases
Tokenize
Sequences



11l

print([‘apple’, ‘orange’].len)
Output:
2

360 Assembly

Array length is computed at compilation time with the formula : (AEND-A)/L'A

*        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
Output:
Array length=           2

6502 Assembly

Translation of: 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.

start:
LDA #(Array_End-Array)   ;evaluates to 13
RTS

Array:
byte "apple",0
byte "orange",0
Array_End:

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 .B or .W 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.


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:

8th

["apples", "oranges"] a:len . cr
Output:
2

AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
/* 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"

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.

report z_array_length.

data(internal_table) = value stringtab( ( `apple` ) ( `orange` ) ).

write: internal_table[ 1 ] , internal_table[ 2 ] , lines( internal_table ).
Output:
apple orange          2

Ada

with Ada.Text_IO;  use Ada.Text_IO;

procedure Array_Length is
   Fruits : constant array (Positive range <>) of access constant String
      := (new String'("orange"),
          new String'("apple"));

begin
   for Fruit of Fruits loop
      Ada.Text_IO.Put (Integer'Image (Fruit'Length));
   end loop;

   Ada.Text_IO.Put_Line ("  Array Size : " & Integer'Image (Fruits'Length));
end Array_Length;
Output:
  6 5  Array Size: 2

ALGOL 68

# 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 #

AntLang

array: seq["apple"; "orange"]
length[array]
/Works as a one liner: length[seq["apple"; "orange"]]

Apex

System.debug(new String[] { 'apple', 'banana' }.size()); // Prints 2

APL

'apple' 'orange'

Output:

2

AppleScript

set theList to {"apple", "orange"}
count theList
-- or
length of theList
-- or
number of items in theList

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.

Output:
2

No context or goal is provided for this task – sometimes for example, we may simply want to take the last member of an array, and counting the length to derive an index might well not be the best route.

More generally, we may learn more about AppleScript by defining length() ourselves. There are two basic functional approaches to doing that – we can write a simple recursive definition, or, if we have a higher order fold/reduce function (see Catamorphism) we can derive length() as:

fold (λx n -> 1 + n)  0
on run
    
    set xs to ["alpha", "beta", "gamma", "delta", "epsilon", ¬
        "zeta", "eta", "theta", "iota", "kappa", "lambda", "mu"]
    
    {_length(xs), fold(xs, succ, 0), item 12 of xs, item -1 of xs}
    
    --> {12, 12, "mu", "mu"}
    
end run

-- TWO FUNCTIONAL DEFINITIONS OF LENGTH

-- 1. Recursive definition

on _length(xs)
    if xs is [] then
        0
    else
        1 + _length(rest of xs)
    end if
end _length


-- 2. fold (λx n -> 1 + n)  0

on succ(x)
    1 + x
end succ

--[a] - > (a - > b) - > b - > [b]
on fold(xs, f, startValue)
    script mf
        property lambda : f
    end script
    
    set v to startValue
    repeat with x in xs
        set v to mf's lambda(v, x)
    end repeat
end fold
Output:
{12, 12, "mu", "mu"}

ARM Assembly

Works with: as version Raspberry Pi
/* 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

Arturo

fruit: ["apple" "orange"]

print ["array length =" size fruit]
Output:
array length = 2

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*))

AutoHotkey

MsgBox % ["apple","orange"].MaxIndex()
Output:
2

AutoIt

Opt('MustDeclareVars',1)	 	; 1 = Variables must be pre-declared.

Local $aArray[2] = ["Apple", "Orange"]
Local $Max = UBound($aArray)
ConsoleWrite("Elements in array: " & $Max & @CRLF)

For $i = 0 To $Max - 1
	ConsoleWrite("aArray[" & $i & "] = '" & $aArray[$i] & "'" & @CRLF)
Next
Output:
Elements in array: 2
aArray[0] = 'Apple'
aArray[1] = 'Orange'

Avail

Using Avail's tuples and the `|_|` method:

|<"Apple", "Orange">|

AWK

The main use of the length()-function is to determine the length of a string.
When used on an array, it returns the number of elements.
Another method to count the elements of the array is by using a variant of for().

# usage:  awk -f arraylen.awk
#
function countElements(array) {
  for( e in array ) {c++}
  return c
}

BEGIN {
  array[1] = "apple"
  array[2] = "orange" 

  print "Array length :", length(array), countElements(array)
  
  print "String length:", array[1], length(array[1])
}
Output:
Array length : 2 2
String length: apple 5

BaCon

BaCon knows three types of arrays, the UBOUND function can query all.

' 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$)

Bash

fruit=("apple" "orange" "lemon")
echo "${#fruit[@]}"

BASIC

DIM X$(1 TO 2)
X$(1) = "apple"
X$(2) = "orange"
PRINT UBOUND(X$) - LBOUND(X$) + 1

Applesoft 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

BASIC256

fruta$ = {"apple", "orange", "pear"}
 
print length(fruta$)
print fruta$[?]
print fruta$[1]
end
3
3
orange

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 version 2.0 on C-64
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."
Output:
A$ HAS 2 ELEMENTS.

True BASIC

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
Output:
 La longitud del array fruta$ es 2 


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.

DIM fruit$(2) 
MAT READ fruit$ 
DATA "apple", "orange"

PRINT "The length of the array 'fruit$' is "; SIZE(fruit$)
END


Output:
 The length of the array 'fruit$' is 2 

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 %name{number}%. 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.

@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
Input:
red yellow blue orange green
Output:
_arrayLength returned 5

BBC BASIC

      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
Output:
Number of elements in array = 2
Number of bytes in all elements combined = 11

Brat

p ["apple", "orange"].length

BQN

gives the length of an array in BQN.

 1"a"+
3

Try It!

C

A commonly used solution

C features two kinds of arrays: static (compile-time, fixed size) and dynamic (allocated at runtime).

The length of a dynamic array cannot be acquired from the array itself - its length must be stored elsewhere.

For static arrays:

#include <stdio.h>

int main()
{    
    const char *fruit[2] = { "apples", "oranges" };

    // Acquire the length of the array by dividing the size of all elements (found
    // with sizeof(fruit)) by the size of the first element.

    // Note that since the array elements are pointers to null-terminated character
    // arrays, the size of the first element is actually the size of the pointer
    // type - not the length of the string.

    // This size, regardless of the type being pointed to, is 8 bytes, 4 bytes, or
    // 2 bytes on 64-bit, 32-bit, or 16-bit platforms respectively.
    int length = sizeof(fruit) / sizeof(fruit[0]);

    printf("%d\n", length);

    return 0;
}

A C pre-processor macro may be created for ease of use:

#define ARRAY_LENGTH(A) (sizeof(A) / sizeof(A[0]))

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.

Safe solution

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.

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.

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.

Solution

#define _CRT_SECURE_NO_WARNINGS    // turn off panic warnings
#define _CRT_NONSTDC_NO_WARNINGS   // enable old-gold POSIX names in MSVS

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>


struct StringArray
{
    size_t sizeOfArray;
    size_t numberOfElements;
    char** elements;
};
typedef struct StringArray* StringArray;

StringArray StringArray_new(size_t size)
{
    StringArray this = calloc(1, sizeof(struct StringArray));
    if (this)
    {
        this->elements = calloc(size, sizeof(int));
        if (this->elements)
            this->sizeOfArray = size;
        else
        {
            free(this);
            this = NULL;
        }
    }
    return this;
}

void StringArray_delete(StringArray* ptr_to_this)
{
    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, ...)
{
    char* s;
    va_list args;
    va_start(args, this);
    while (this->numberOfElements < this->sizeOfArray && (s = va_arg(args, char*)))
        this->elements[this->numberOfElements++] = strdup(s);
    va_end(args);
}


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;
}
Output:
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"

An example why sizeof(A)/sizeof(E) may be a bad idea in 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;
}

As we can see the sizeof(ArrayType)/sizeof(ElementType) approach mostly fail.

Output:
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

C#

using System;

class Program
{
    public static void Main()
    {
        var fruit = new[] { "apple", "orange" };
        Console.WriteLine(fruit.Length);
    }
}

Note that any of the following array declarations could be used:

var fruit = new[] { "apple", "orange" };
var fruit = new string[] { "apple", "orange" };
string[] fruit = new[] { "apple", "orange" };
string[] fruit = new string[] { "apple", "orange" };
string[] fruit = { "apple", "orange" };

A shorter variant could also have been used:

using static System.Console;

class Program 
{
    public static void Main()
    {
        WriteLine(new[] { "apples", "oranges" }.Length);
    }
}

C++

C++ follows the same rules as C regarding static and dynamic arrays.

However, C++ has an additional std::array type (amongst other collections) in its standard library:

#include <array>
#include <iostream>
#include <string>

int main() 
{
    std::array<std::string, 2> fruit { "apples", "oranges" };
    std::cout << fruit.size();
    return 0;
}

Note that char* or const char* could have been used instead of std::string.

In addition to the std::array type, the C++ standard library also provides dynamically-sized containers to hold arbitrary objects. These all support similar interfaces, though their implementations have different performance characteristics.

    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;

Of these, vector is probably the most widely used.

Ceylon

shared void run() {
	value array = ["apple", "orange"];
	print(array.size);
}

Clipper/XBase++

/*
 * nizchka: March - 2016
 * This is a Clipper/XBase++ of RosettaCode Array_Length  
 */

PROCEDURE MAIN()
        LOCAL FRUIT := { "apples","oranges" }

        ? LEN(FRUIT)
RETURN

Outputs:

2

nizchka 23:27, 16 March 2016 (UTC)

Clojure

; using count:
(count ["apple" "orange"])

; OR alength if using Java arrays:
(alength (into-array ["apple" "orange"]))

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.

       identification division.
       program-id. array-length.

       environment division.
       configuration section.
       repository.
           function all intrinsic.

       data division.
       working-storage section.
       01 table-one.
          05 str-field pic x(7) occurs 0 to 5 depending on t1.

       77 t1           pic 99.

       procedure division.
       array-length-main.
       perform initialize-table
       perform display-table-info
       goback.

       initialize-table.
           move 1 to t1
           move "apples" to str-field(t1)

           add 1 to t1
           move "oranges" to str-field(t1).

      *> add an extra element and then retract table size
           add 1 to t1
           move "bananas" to str-field(t1).
           subtract 1 from t1
       .

       display-table-info.
           display "Elements: " t1 ", using " length(table-one) " bytes"
           display table-one
       .

       end program array-length.
Output:
$ cobc -xjd array-length.cob
Elements: 02, using 000000014 bytes
apples oranges

ColdFusion

<cfset testArray = ["apple","orange"]>
<cfoutput>Array Length = #ArrayLen(testArray)#</cfoutput>

Outputs:

Array Length = 2

Mike Knapp 15:57, 26 May 2016 (UTC)

Common Lisp

(print (length #("apple" "orange")))

Alternate solution

I use Allegro CL 10.1

;; 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)

Output:

length of my-array: 2

Component Pascal

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.

Execute: ^Q AryLen.Do

Output:
Length:>  2

Crystal

puts ["apple", "orange"].size
Output:
2

D

import std.stdio;

int main()
{
    auto fruit = ["apple", "orange"];
    fruit.length.writeln;
    return 0;
}

Or a somewhat shorter...

import std.stdio;

void main()
{
    ["apple", "orange"].length.writeln;
}

Dart

arrLength(arr) {
  return arr.length;
}

main() {
  var fruits = ['apple', 'orange'];
  print(arrLength(fruits));
}

DataWeave

var arr = ["apple", "orange"]
sizeOf(arr)

Delphi

   showmessage(  length(['a','b','c']).ToString );

Diego

set_namespace(rosettacode)_me();

me_msg()_array()_values(apple,orange)_length();
    
reset_namespace[];
Output:
2

Dragon

select "std" 

a = ["apple","orange"]
b = length(a) 

show b

Dyalect

var xs = ["apple", "orange"]
print(xs.Length())

EasyLang

<lang>fruit$[] = [ "apples" "oranges" ] print len fruit$[]</syntaxhighlight>

EchoLisp

(length '("apple" "orange")) ;; list
    2
(vector-length #("apple" "orange")) ;; vector
    2

Ela

length [1..10]

Elena

ELENA 5.0 :

    var array := new string[]{"apple", "orange"};
    var length := array.Length;

Elixir

iex(1)> length( ["apple", "orange"] )          # List
2
iex(2)> tuple_size( {"apple", "orange"} )      # Tuple
2

Elm

import Array
import Html

main : Html.Html
main = 
    ["apple", "orange"]
      |> Array.fromList
      |> Array.length
      |> Basics.toString
      |> Html.text

Emacs Lisp

(length ["apple" "orange"])
=> 2

length also accepts a list or a string.

Erlang

1> length(["apple", "orange"]).     %using a list
2
1> tuple_size({"apple", "orange"}). %using a tuple
2


Euphoria

sequence s = {"apple","orange",2.95} -- Euphoria doesn't care what you put in a sequence

? length(s)

3 -- three objects

? length(s[1])

5 -- apple has 5 characters

? length(s[1][$])

1 -- 'e' is an atomic value


? length(s[$])

1 -- 2.95 is an atomic value

F#

[|1;2;3|].Length |> printfn "%i"

Or:

[|1;2;3|] |> Array.length |> printfn "%i"

Factor

{ "apple" "orange" } length

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.

<lang>: 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

CREATE Q { " Apples" " Oranges" }   q {len} . 2  ok

Fortran

Early fortrans offered no protocol for ascertaining the length (or dimensionality) of arrays, though the compiler has this information. Thus a statement such as PRINT A would print all the elements of a variable A according to its definition. A subprogram that received a parameter would have no access to these details, so its parameter might be declared as A(12345) simply to signify that it was an array (rather than an ordinary variable) and the programmer would rely on other data to know the upper bound to employ, for instance via an additional parameter. Any mistakes would cause crashes! On the other hand, with heavy computational tasks, it was common to take advantage of the opportunities. Thus, a subprogram might regard its array parameter as one-dimensional even though the actual parameter was not. Carefully-programmed routines might thusly process a sequence of elements via 1-D indexing, far faster than the 2-D or higher order indexing of the original. Success at this game required understanding how array elements were arranged in multidimensional arrays.

Later fortrans allowed A(*) to signify an array parameter of unstated upper bound, but there was still a problem with higher dimensions. All but the last dimension has to be stated correctly if a multi-dimensional array parameter is to be indexed correctly - Fortran stores array elements in column-major order.

With Fortran 90, a new protocol was introduced, whereby the parameter might be declared as A(:) signifying an array of one dimension, of bounds unstated. A 2-D array would have A(:,:) and so on. Further, arrays could have arbitrary lower bounds as well, as in A(-7:12) but if no colon appeared for a dimension, the lower bound would be assumed to be one so A(2) means an array of two elements, as before. And as before, in a subprogram a bound could be explicitly stated, perhaps via an explicit parameter such as N, but now with the : scheme, the compiler is passing secret additional parameters to the subprogram giving the bounds of the array, and these can be accessed via the library functions LBOUND and UBOUND. For multi-dimensional arrays there are multiple bounds, and an invocation might be UBOUND(A,DIM = 2) but in the example only a one-dimensional array is involved. These facilities are available only if the new MODULE protocol is employed.

The task is in terms of an array holding the texts "Apple" and "Orange", so a CHARACTER*6 element size will do; the subprogram receives yet another secret parameter specifying the size of CHARACTER parameters. This size can be accessed via the LEN function, and, since in principle the index span is arbitrary, no constant index is sure to be a valid index of some single element: thus the LBOUND function is used to finger one that is.

For a simple example, the WRITE(6,*) suffices: write to standard output (the 6), in free-format (the *).

      MODULE EXAMPLE
       CONTAINS
        SUBROUTINE ABOUND(A)
         CHARACTER*(*) A(:)	!One dimensional array, unspecified bounds.
          WRITE (6,*) "Lower bound",LBOUND(A),", Upper bound",UBOUND(A)
          WRITE (6,*) "Element size",LEN(A(LBOUND(A)))
          WRITE (6,*) A
        END SUBROUTINE ABOUND
      END MODULE EXAMPLE

      PROGRAM SHOWBOUNDS
       USE EXAMPLE
       CHARACTER*6 ARRAY(-1:1)
        ARRAY(-1) = "Apple"
        ARRAY(0) = "Orange"
        ARRAY(1) = ""
        CALL ABOUND(ARRAY)
        WRITE (6,*) "But, when it is at home..."
        WRITE (6,*) "L. bound",LBOUND(ARRAY),", U. bound",UBOUND(ARRAY)
      END

Output:

Lower bound           1 , Upper bound           3
Element size           6
Apple Orange
But, when it is at home...
L. bound          -1 , U. bound           1

Notice that the subprogram sees the array as an old-style array starting with index one! 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.

If in the subprogram the bounds are fixed (say as A(-1:6)) then a CALL ABOUND(ARRAY) may provoke a compiler complaint if ARRAY is not a suitable size.

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
Output:
The length of the fruit array is 2

Frink

a = ["apple", "orange"]
println[length[a]]

FurryScript

THE_LIST( <apple> <orange> )
COUNT[ 0 SW ~| COUNT_STEP# 0 SW SU ]
COUNT_STEP[ DR 1 SU ]

`THE_LIST COUNT# +<>

Futhark

This example may be incorrect due to a recent change in the task requirements or a lack of testing. Please verify it and remove this message. If the example does not match the requirements or does not work, replace this message with Template:incorrect or fix the code yourself.

The shape builtin returns the shape of an array as an array of integers. The length is element 0 of the shape:

fun length(as: []int): int = (shape as)[0]

FutureBasic

NSUInteger count = fn ArrayCount( array ). Example:

window 1
print fn ArrayCount( @[@"apple",@"orange",@"cherry",@"grape",@"lemon"] )
HandleEvents
Output:
5

Fōrmulæ

Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.

Programs in Fōrmulæ are created/edited online in its website, However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edite/d, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.

In this page you can see the program(s) related to this task and their results.

Gambas

Click this link to run this code

Public Sub Main()
Dim siList As Short[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

Print siList.Count

End

Output:

10

Genie

[indent=4]
/* Array length, in Genie */
init
    arr:array of string = {"apple", "orange"}
    stdout.printf("%d ", arr.length)
    print arr[1]
Output:
prompt$ valac array_length.gs
prompt$ ./array_length
2 orange

Go

package main

import "fmt"

func main() {
	arr := [...]string{"apple", "orange", "pear"}

	fmt.Printf("Length of %v is %v.\n", arr, len(arr))
}


Output:
Length of [apple orange pear] is 3.

Groovy

def fruits = ['apple','orange']
println fruits.size()

Harbour

LOCAL aFruits := {"apple", "orange"}
Qout( Len( aFruits ) ) // --> 2

Haskell

-- [[Char]] -> Int
length ["apple", "orange"]

hexiscript

let a arr 2
let a[0] "apple"
let a[1] "orange"
println len a

Hoon

|=  arr=(list *)  (lent arr)

i

main: print(#["apple", "orange"])

Icon and Unicon

Icon, and therefore Unicon, includes a prefix size operator, star *. This operator can be applied to just about any data type or data structure.

write(*["apple", "orange"])

Idris

length ["apple", "orange"]

J

Tally (#) returns the length of the leading dimension of an array (or 1 if the array has no dimensions). Shape Of ($) returns the length of each dimension of an array.

   # 'apple';'orange'
2
   $ 'apple';'orange'
2

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.

   $#'apple';'orange'

   $$'apple';'orange'
1

This might be a clearer concept with a few more examples. Here's an array with two dimensions:

   >'apple';'orange'
apple 
orange
   $>'apple';'orange'
2 6
   #>'apple';'orange'
2

And, here's an array with no dimensions: <lang> 9001 9001

  #9001

1

  $9001

</syntaxhighlight> You can count the number of dimensions of an array (the length of the list of lengths) using #$array:

   #$9001
0
   #$'apple';'orange'
1
   #$>'apple';'orange'
2

Janet

(def our-array @["apple" "orange"])
(length our-array)
Output:
2

Java

public class ArrayLength {
    public static void main(String[] args) {
        System.out.println(new String[]{"apple", "orange"}.length);
    }
}

JavaScript

console.log(['apple', 'orange'].length);

However, determining the length of a list, array, or collection may simply be the wrong thing to do.

If, for example, the actual task (undefined here, unfortunately) requires retrieving the final item, while it is perfectly possible to write last in terms of length

function last(lst) {
    return lst[lst.length - 1];
}

using length has the disadvantage that it leaves last simply undefined for an empty list.

We might do better to drop the narrow focus on length, and instead use a fold (reduce, in JS terms) which can return a default value of some kind.

function last(lst) {
    return lst.reduce(function (a, x) {
        return x;
    }, null);
}

Alternatively, rather than scanning the entire list to simply get the final value, it might sometimes be better to test the length:

function last(list, defaultValue) {
   return list.length ?list[list.length-1] :defaultValue;
}

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):

function last(list, defaultValue) {
    return list.slice(-1)[0] || defaultValue;
}

jq

["apple","orange"] | length

Output:

2

Note that the length filter is polymorphic, so for example the empty string (""), the empty list ([]), and null all have length 0.

Jsish

/* Array length, in jsish */
var arr = new Array('apple', 'orange');
puts(arr.length);
puts(arr[1]);
Output:
prompt$ jsish arrayLength.jsi
2
orange

Julia

a = ["apple","orange"]
length(a)

Klingphix

include ..\Utilitys.tlhy

( "apple" "orange" ) len print

" " input
Output:
2

Klong

#["apple" "orange"]

Kotlin

fun main(args: Array<String>) {
    println(arrayOf("apple", "orange").size)
}

Lambdatalk

{A.length {A.new 1 2 3}}
-> 3

Latitude

In Latitude, length and size are synonymous and will both retrieve the size of a collection.

println: ["apple", "orange"] length.

Liberty BASIC

When a one or two dimensional array, A$, with subscript(s) of 10 or less is referenced (either by assigning or reading), the compiler does an implicit DIM A$(10) or DIM A$(10,10). Before referencing an array with any subscript numbered higher than 10, or arrays of three dimensions or more, the programmer must first issue an explicit DIM statement.

There is no function in Liberty Basic to directly read the size of an array. This program uses error trapping loops to, first, determine the number of dimensions of the array. Then, second, again uses error trapping loops to determine the number of elements in each dimension. Finally, it prints the DIM statement that was used to define the array.

I suppose the implicit DIM feature makes it a bit quicker to write short, simple programs. One or two dimension arrays may be resized with REDIM. Three dimension or more arrays can not be resized. All arrays may be cleared with REDIM. Keep in mind that A$(n) and A$(n,m) are the same array. You must refer to it with the correct arguments or get an error.

NOTE -- This program runs only under LB Booster version 3.05 or higher because of arrays with more than two dimensions, passed array names to functions and subroutines as a parameter, and structured error trapping syntax. Get the LBB compiler here: http://lbbooster.com/

Works with: LB Booster
FruitList$(0)="apple" 'assign 2 cells of a list array
FruitList$(1)="orange"
dimension=dimension(FruitList$()) 'first get the dimension of the array
if dimension>3 then
    print "Sorry, program only written for array dimensions of 3 or less."
    end 
end if
call elements FruitList$(), dimension 'next get the size of each dimension
end

function dimension(array$())
    for dimension=1 to 4
        select case dimension
            case 1
                try: x$=array$(0)
                catch: goto [TryNext]
                end try
                exit for
            case 2
                try: x$=array$(0,0)
                catch: goto [TryNext]
                end try
                exit for
            case 3
                try: x$=array$(0,0,0)
                catch: goto [TryNext]
                end try
                exit for
            case 4
                exit for
        end select
    [TryNext]
    next dimension
    if dimension<4 then print "array dimension = "; dimension
    ArraySize(0)=dimension
end function

sub elements array$(), dimension
    select case dimension
        case 1
            try
                do
                    x$=array$(a)
                    a+=1
                loop
            catch: elements=a
            end try
            ArraySize(1)=elements-1
            print "dimension 1 has "; elements; " elements (cells), "_
                    "numbered 0 to "; ArraySize(1)
        case 2
            try
                do
                    x$=array$(a,0)
                    a+=1
                loop
            catch: elements=a
            end try
            ArraySize(1)=elements-1
            print "dimension 1 has "; elements; " elements (cells), "_
                    "numbered 0 to "; ArraySize(1)
            elements=0
            try
                do
                    x$=array$(0,b)
                    b+=1
                loop
            catch: elements=b
            end try            ArraySize(2)=elements-1
            print "dimension 2 has "; elements; " elements (cells), "_
                    "numbered 0 to "; ArraySize(2)
        case 3
            try
                do
                    x$=array$(a,0,0)
                    a+=1
                loop
            catch: elements=a
            end try
            ArraySize(1)=elements-1
            print "dimension 1 has "; elements; " elements (cells), "_
                    "numbered 0 to "; ArraySize(1)
            elements=0
            try
                do
                    x$=array$(0,b,0)
                    b+=1
                loop
            catch: elements=b
            end try
            ArraySize(2)=elements-1
            print "dimension 2 has "; elements; " elements (cells), "_
                    "numbered 0 to "; ArraySize(2)
            elements=0
            try
                do
                    x$=array$(0,0,c)
                    c+=1
                loop
            catch: elements=c
            end try
            ArraySize(3)=elements-1
            print "dimension 3 has "; elements; " elements (cells), "_
                    "numbered 0 to "; ArraySize(3)
    end select
   'print the explicit or implied DIMension statement for this array 
    print "DIM array$("; a-1;
    if b>0 then print ","; b-1;
    if c>0 then print ","; c-1;
    print ")" 
end sub
Output:
array dimension = 1
dimension 1 has 11 elements (cells), numbered 0 to 10
DIM array$(10)

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.

# Array length, in LIL
set a [list "apple"]
append a "orange"
print [count $a]
print [index $a 1]
Output:
prompt$ lil arrayLength.lil
2
orange

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);
}

Lingo

fruits = ["apple", "orange"]
put fruits.count
-- 2

Little

string fruit[] = {"apples", "oranges"};
puts(length(fruit));

LiveCode

put "apple","orange" into fruit
split fruit using comma
answer the number of elements of fruit

Lua

-- For tables as simple arrays, use the # operator:
fruits = {"apple", "orange"}
print(#fruits)

-- Note the # symbol does not work for non-integer-indexed tables:
fruits = {fruit1 = "apple", fruit2 = "orange"}
print(#fruits)

-- For this you can use this short function:
function size (tab)
  local count = 0
  for k, v in pairs(tab) do
    count = count + 1
  end
  return count
end

print(size(fruits))
Output:
2
0
2

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

Maple

a := Array(["apple", "orange"]);
numelems(a);
Output:
a := [ "apple" "orange" ]
2

Mathematica/Wolfram Language

Length[{"apple", "orange"}]

MATLAB / Octave

length({'apple', 'orange'})

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.

numel({'apple', 'orange'; 'pear', 'banana'})

Modula-3

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.

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).

min

Works with: min version 0.19.3
("apple" "orange") size print
Output:
2

MiniScript

fruits = ["apple", "orange"]
print fruits.len

MiniZinc

array[int] of int: arr = [1,2,3];
var int: size = length(arr);

solve satisfy;

output [show(size),"\n"];

Nanoquery

fruit = array(2)
fruit[0] = "apple"
fruit[1] = "orange"
println len(fruit)

// outputs 2

Neko

var fruit = $array("apple", "orange");

$print($asize(fruit));

NewLISP

(println (length '("apple" "orange")))

; Nehal-Singhal 2018-05-25
(length '(apple orange))

NGS

echo(len(['apple', 'orange']))
# same
echo(['apple', 'orange'].len())

Nim

let fruit = ["apple", "orange"]
echo "The length of the fruit array is ", len(fruit)
Output:
The length of the fruit array is 2

Oberon-2

Works with: oo2c
MODULE ArrayLength;
IMPORT 
  Strings,
  Out;
TYPE
  String = POINTER TO ARRAY OF CHAR;
VAR
  a: ARRAY 16 OF String;

PROCEDURE NewString(s: ARRAY OF CHAR): String;
VAR
  str: String;
BEGIN
  NEW(str,Strings.Length(s) + 1);COPY(s,str^);
  RETURN str
END NewString;

PROCEDURE Length(a: ARRAY OF String): LONGINT;
VAR
  i: LONGINT;
BEGIN
  i := 0;
  WHILE (a[i] # NIL) DO INC(i) END;
  RETURN i;
END Length;

BEGIN
  a[0] := NewString("apple");
  a[1] := NewString("orange");
  Out.String("length: ");Out.Int(Length(a),0);Out.Ln
END ArrayLength.
Output:
length: 2

Objeck

class Test {
  function : Main(args : String[]) ~ Nil {
    fruit := ["apples", "oranges"];
    fruit->Size()->PrintLine();
  }
}

OCaml

Array.length [|"apple"; "orange"|];;

Oforth

[ "apple", "orange" ] size

Ol

All of these methods are equivalent.

(print (vector-length (vector "apple" "orange")))
(print (vector-length #("apple" "orange")))
(print (vector-length ["apple" "orange"]))

(print (size #("apple" "orange")))

Onyx

[`apple' `orange'] length # leaves 2 on top of the stack

ooRexx

/* REXX */
a = .array~of('apple','orange')
say a~size 'elements'
Do e over a
  say e
  End
Say "a[2]="a[2]
Output:
2 elements
apple
orange
a[2]=orange

PARI/GP

array = ["apple", "orange"]
length(array)       \\ == 2
#array              \\ == 2

The # syntax is a handy shorthand. It usually looks best just on variables but it works on expressions too, possibly with parens to control precedence.

Both forms work on column vectors too, and also on strings and matrices. (For a matrix it is the number of columns.)

Pascal

Works with: Free Pascal version 2.6.2
#!/usr/bin/instantfpc
//program ArrayLength;

{$mode objfpc}{$H+}

uses SysUtils, Classes;

const
  Fruits : array[0..1] of String = ('apple', 'orange');

begin
   WriteLn('Length of Fruits by function : ', Length(Fruits));
   WriteLn('Length of Fruits by bounds : ', High(Fruits) - Low(Fruits) + 1);
END.
Output:
./ArrayLength.pas 
Length of Fruits by function : 2
Length of Fruits by bounds : 2

Perl

The way to get the number of elements of an array in Perl is to put the array in scalar context.

my @array = qw "apple orange banana", 4, 42;

scalar @array;      #  5
0 + @arrray;        #  5
'' . @array;        # "5"
my $elems = @array; # $elems = 5

scalar @{  [1,2,3]  }; # [1,2,3] is a reference which is already a scalar

my $array_ref = \@array; # a reference
scalar @$array_ref;


# using subroutine prototypes, not generally recommended
# and not usually what you think they are
sub takes_a_scalar ($) { my ($a) = @_; return $a }

takes_a_scalar @array;

# the built-ins can also act like they have prototypes

A common mistake is to use length which works on strings not arrays. So using it on an array, as a side-effect, actually gives you a number which represents the order of magnitude.

length '' . @array; # 1
length      @array; # 1

print '0.', scalar @array, 'e', length @array, "\n"; # 0.5e1

@array = 1..123;
print '0.', scalar @array, 'e', length @array, "\n"; # 0.123e3

print 'the length of @array is on the order of ';
print 10 ** (length( @array )-1); # 100
print " elements long\n";

Phix

Library: Phix/basics
constant fruits = {"apple","orange"}
?length(fruits)
Output:
2

Phixmonti

"apple" "orange" stklen tolist len print

With syntactic sugar

include ..\Utilitys.pmt
( "apple" "orange" ) len print
Output:
2

PHP

print count(['apple', 'orange']); // Returns 2

Picat

<lang>main =>

  L = ["apple", "orange"],
  println(len(L))),
  println(length(L)),
  println(L.len),
  println(L.length).</syntaxhighlight>
Output:
2
2
2
2


PicoLisp

: (length '(apple orange))
-> 2
:

Pike

void main()
{
    array fruit = ({ "apple", "orange" });
    write("%d\n", sizeof(fruit));
}
Output:
2

PL/I

 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;
Output:
Array a has 2 elements.
A(1)='apple'            A(2)='orange';

Plorth

["apple", "orange"] length println

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!")

Potion

("apple", "orange") length print

PowerShell

$Array = @( "Apple", "Orange" )
$Array.Count
$Array.Length
Output:
2
2

Processing

String[] arr = {"apple", "orange"};
void setup(){
  println(arr.length);
}
Output:
2

Processing Python mode

arr = ['apple', 'orange']  # a list for an array

def setup():
    println(len(arr))
Output:
2

Prolog

| ?- length(["apple", "orange"], X).

X = 2

yes

PureBasic

EnableExplicit
Define Dim fruit$(1); defines array with 2 elements at indices 0 and 1 
fruit$(0) = "apple"
fruit$(1) = "orange"
Define length = ArraySize(fruit$()) + 1; including the element at index 0
If OpenConsole()
  PrintN("The length of the fruit array is " + length)
  PrintN("")
  PrintN("Press any key to close the console")
  Repeat: Delay(10) : Until Inkey() <> ""
  CloseConsole()
EndIf
Output:
The length of the fruit array is 2

An abbreviated form of the above, not printing to console/terminal

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.
Output:
2

Python

>>> print(len(['apple', 'orange']))
2
>>>

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

Quackery

<Lang Quackery> $ "apples" $ "oranges" 2 pack size echo</syntaxhighlight>

Output:
2

R

a <- c('apple','orange')   # create a vector containing "apple" and "orange"
length(a)
Output:
[1] 2

Racket

Translation of: EchoLisp
#lang racket/base
(length '("apple" "orange")) ;; list
(vector-length #("apple" "orange")) ;; vector
Output:
2
2

Raku

(formerly Perl 6)

Works with: Rakudo version 2017.04

To get the number of elements of an array in Raku you put the array in a coercing Numeric context, or call elems on it.

my @array = <apple orange>;

say @array.elems;  # 2
say elems @array;  # 2
say + @array;      # 2
say @array + 0;    # 2

Watch out for infinite/lazy arrays though. You can't get the length of those.

my @infinite = 1 .. Inf;  # 1, 2, 3, 4, ...

say @infinite[5000];  # 5001
say @infinite.elems;  # Throws exception "Cannot .elems a lazy list"

Rapira

arr := <* "apple", "orange" *>
output: #arr

Red

length? ["apples" "oranges"]
== 2

Relation

relation fruit
insert "apples"
insert "oranges"
project fruit count
print
fruit_count
2

ReScript

let fruits = ["apple", "orange"]

Js.log(Js.Array.length(fruits))
<!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>
Output:
// Generated by ReScript, PLEASE EDIT WITH CARE
'use strict';

var fruits = [
  "apple",
  "orange"
];

console.log(fruits.length);

exports.fruits = fruits;
/*  Not a pure module */


REXX

/* REXX ----------------------------------------------
* The compond variable a. implements an array
* By convention, a.0 contains the number of elements
*---------------------------------------------------*/
a.=0                   /* initialize the "array" */
call store 'apple'
Call store 'orange'
Say 'There are' a.0 'elements in the array:'
Do i=1 To a.0
  Say 'Element' i':' a.i
  End
Exit
store: Procedure Expose a.
z=a.0+1
a.z=arg(1)
a.0=z
Return
Output:
There are 2 elements in the array:
Element 1: apple
Element 2: orange

Ring

See len(['apple', 'orange']) # output = 2

Robotic

As stated before in the 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:

set "index" to 0
set "$array&index&" to "apple"
inc "index" by 1
set "$array&index&" to "orange"
* "Array length: ('index' + 1)"

Example 2:

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')"

Ruby

puts ['apple', 'orange'].length  # or .size

Rust

By default arrays are immutable in rust.

fn main() {
    let array = ["foo", "bar", "baz", "biff"];
    println!("the array has {} elements", array.len());
}

Scala

println(Array("apple", "orange").length)

Scheme

Using Scheme's vector type as an equivalent to an array:

(display (vector-length #("apple" "orange")))

Seed7

The function length determines the length of an array.

$ include "seed7_05.s7i";

const array string: anArray is [] ("apple", "orange");

const proc: main is func
  begin
    writeln(length(anArray));
  end func;

SenseTalk

put ("apple", "orange", "pear", "banana", "aubergine") into fruits
put the number of items in fruits

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])

Sidef

var arr = ['apple', 'orange'];
say arr.len;        #=> 2
say arr.end;        #=> 1 (zero based)

Simula

COMMENT ARRAY-LENGTH;
BEGIN

    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
Output:
2

Smalltalk

a := #('apple' 'orange').
a size

SNOBOL4

    ar = ARRAY('2,2')
    ar<1,1> = 'apple'
    ar<1,2> = 'first'
    ar<2,1> = 'orange'
    ar<2,2> = 'second'
    OUTPUT = IDENT(DATATYPE(ar), 'ARRAY') PROTOTYPE(ar)
end
Output:
2,2

SPL

a = ["apple","orange"]
#.output("Number of elements in array: ",#.size(a,1))
Output:
Number of elements in array: 2

SQL

SELECT COUNT() FROM (VALUES ('apple'),('orange'));

Standard ML

let
  val a = Array.fromList ["apple", "orange"]
in
  Array.length a
end;

Stata

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

clear
input str10 fruit
apple
orange
end

di _N
di c(N) " " c(k)

Length of a macro list

Use either the sizeof macro list function or the 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.

local fruits apple orange
di `: list sizeof fruits'
di `: word count `fruits''

Mata

For a Mata array, use rows and similar functions:

mata
a=st_sdata(.,"fruit")
rows(a)
cols(a)
length(a)
end

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
Output:
2

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

Tailspin

['apple', 'orange'] -> $::length -> !OUT::write
Output:
2

Tcl

;# not recommended:
set mylistA {apple orange}   ;# actually a string
set mylistA "Apple Orange"   ;# same - this works only for simple cases

set lenA [llength $mylistA]
puts "$mylistA :  $lenA"

# better:  to build a list, use 'list' and/or 'lappend':
set mylistB [list apple orange "red wine" {green frog}]
lappend mylistB "blue bird"

set lenB [llength $mylistB]
puts "$mylistB :  $lenB"
Output:
Apple Orange :  2
apple orange {red wine} {green frog} {blue bird} :  5

TI-83 BASIC

Works with: TI-83 2.55MP

Use function dim().

{1,3,–5,4,–2,–1}→L1
dim(L1)
Output:
6

Transd

#lang transd

MainModule : {
    _start: (lambda 
        (with v ["apple", "orange"]
            (lout (size v))
        )
        (lout (size ["apple", "orange"]))
    )
}
Output:
2
2

UNIX Shell

#!/bin/bash
array=("orange" "apple")
echo "${#array[@]}"
Output:
2

Ursa

> decl string<> stream
> append "two" "strings" stream
> out (size stream) endl console
2
> out (size "test string") endl console
11
> 

Vala

void main() {
  string[] fruit = {"apple", "orange"};
  stdout.printf("%d\n", fruit.length);
}

Note that any of the following array declarations could be used:

var fruit = new string[] { "apple", "orange" };
string[] fruit = new string[] { "apple", "orange" };
string[] fruit = { "apple", "orange" };

A shorter variant could also have been used:

void main() {
  stdout.printf("%d\n", new string[] {"apples", "orange"}.length);
}

VBA

One-liner. Assumes array lower bound, which is not always safe.

Debug.Print "Array Length: " & UBound(Array("apple", "orange")) + 1

Works regardless of lower bound:

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)
Output:

In this instance, same output for both.

Array Length: 2

VBScript

arr = Array("apple","orange")
WScript.StdOut.WriteLine UBound(arr) - LBound(arr) + 1
Output:
2

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.

' 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

Visual Basic .NET

Works with: Visual Basic .NET version 9.0+
Module ArrayLength

    Sub Main()
        Dim array() As String = {"apple", "orange"}
        Console.WriteLine(array.Length)
    End Sub

End Module
Output:
2

Vlang

A len property is maintained for all V arrays.

// V, array length
// Tectonics: v run array-length.v
module main

// access array length
pub fn main() {
    arr := ["apple", "orange"]
    println(arr.len)
}
Output:
prompt$ v run array-length.v
2

WDTE

let io => import 'io';
let a => ['apple'; 'orange'];
len a -- io.writeln io.stdout;

Wren

var arr = ["apple", "orange"]
System.print(arr.count)
Output:
2

XLISP

(vector-length #("apple" "orange"))


Yabasic

dim fruta$(3)
read fruta$(1), fruta$(2), fruta$(3)
data "apple", "orange", "pear"

print arraysize(fruta$(),1)
print fruta$(2)
end
3
orange


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 much easier to work with.

	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
Output:
(HL contains length of the array)
HL:0002

zkl

zkl doesn't support arrays natively, use lists instead.

List("apple", "orange").len().println() //-->2, == L("apple", "orange")
T("apple", "orange").len().println() //-->2, read only list (ROList)

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});
}

Zoea

program: array_length
  input: [a,b,c]
  output: 3

Zoea Visual

Array Length

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.