Array length: Difference between revisions
Content added Content deleted
Puppydrum64 (talk | contribs) |
Thundergnat (talk | contribs) m (syntax highlighting fixup automation) |
||
Line 13:
=={{header|11l}}==
<
{{out}}
<pre>
Line 21:
=={{header|360 Assembly}}==
Array length is computed at compilation time with the formula : (AEND-A)/L'A
<
ARRAYLEN START
USING ARRAYLEN,12
Line 32:
AEND DC 0C
PG DC CL25'Array length=' buffer
END ARRAYLEN</
{{out}}
<pre>
Line 40:
{{trans|360 Assembly}}
Array length is computed at compilation time with the formula: (Array_End-Array). Even though the labels Array and Array_End are both 16-bit values, if their difference fits into 8 bits the assembler will allow you to load it into a register.
<
LDA #(Array_End-Array) ;evaluates to 13
RTS
Line 47:
byte "apple",0
byte "orange",0
Array_End:</
=={{header|68000 Assembly}}==
Line 55:
<
MOVE.B #(MyArray_End-MyArray)/4 ;evaluates to 2
RTS
Line 69:
DC.L Apple
DC.L Orange
MyArray_End:</
=={{header|8th}}==
<
["apples", "oranges"] a:len . cr
</syntaxhighlight>
{{out}}
<pre>
Line 82:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program lenAreaString64.s */
Line 147:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|ABAP}}==
The concept of arrays does not exist in ABAP, instead internal tables are used. Since ABAP Version 7.40 they can be accessed with the common index notation. Note that the index starts at 1 and out of bound access raises an exception. The built-in function "lines" returns the number of records.
<
report z_array_length.
Line 158:
write: internal_table[ 1 ] , internal_table[ 2 ] , lines( internal_table ).
</syntaxhighlight>
{{out}}
Line 167:
=={{header|Ada}}==
<
procedure Array_Length is
Line 180:
Ada.Text_IO.Put_Line (" Array Size : " & Integer'Image (Fruits'Length));
end Array_Length;</
{{out}}
Line 186:
=={{header|ALGOL 68}}==
<
[]STRING fruits = ( "apple", "orange" );
print( ( ( UPB fruits - LWB fruits ) + 1, newline ) ) # prints 2 #</
=={{header|AntLang}}==
<
length[array]
/Works as a one liner: length[seq["apple"; "orange"]]</
=={{header|Apex}}==
<
=={{header|APL}}==
<syntaxhighlight lang
Output:
<pre>2</pre>
=={{header|AppleScript}}==
<
set theList to {"apple", "orange"}
count theList
Line 211:
-- or
number of items in theList
</syntaxhighlight>
''Strictly speaking, 'items in' can be omitted from the last example, since 'number of' does essentially the same as 'length of'. The additional stage of extracting theList's 'items' is inefficient.''
{{out}}
Line 222:
<pre>fold (λx n -> 1 + n) 0</pre>
<
set xs to ["alpha", "beta", "gamma", "delta", "epsilon", ¬
Line 263:
end repeat
end fold
</syntaxhighlight>
{{Out}}
Line 271:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<
/* ARM assembly Raspberry PI */
/* program lenAreaString.s */
Line 407:
.Ls_magic_number_10: .word 0x66666667
</syntaxhighlight>
=={{header|Arturo}}==
<
print ["array length =" size fruit]</
{{out}}
Line 420:
=={{header|ATS}}==
<
#include
"share/atspre_staload.hats"
Line 433:
implement main0((*void*)) = ((*void*))
</syntaxhighlight>
=={{header|AutoHotkey}}==
<
{{Out}}<pre>2</pre>
=={{header|AutoIt}}==
<
Local $aArray[2] = ["Apple", "Orange"]
Line 449:
ConsoleWrite("aArray[" & $i & "] = '" & $aArray[$i] & "'" & @CRLF)
Next
</syntaxhighlight>
{{Out}}
<pre>Elements in array: 2
Line 459:
Using Avail's tuples and the `|_|` method:
<
=={{header|AWK}}==
Line 468:
Another method to count the elements of the array is by using a variant of for().
<
#
function countElements(array) {
Line 482:
print "String length:", array[1], length(array[1])
}</
{{out}}
Line 492:
=={{header|BaCon}}==
BaCon knows three types of arrays, the UBOUND function can query all.
<
DECLARE fruit$[] = { "apple", "orange" }
Line 509:
meat$("first") = "chicken"
meat$("second") = "pork"
PRINT UBOUND(meat$)</
=={{header|Bash}}==
<
fruit=("apple" "orange" "lemon")
echo "${#fruit[@]}"</
=={{header|BASIC}}==
<
X$(1) = "apple"
X$(2) = "orange"
PRINT UBOUND(X$) - LBOUND(X$) + 1</
==={{header|Applesoft BASIC}}===
<
20 A$(1) = "ORANGE"
30 A$(2) = "APPLE"
Line 557:
170 L$ = L$ + STR$ ( FN P(I))
180 L$ = L$ + " ": NEXT I
190 RETURN</
==={{header|BASIC256}}===
<
fruta$ = {"apple", "orange", "pear"}
Line 567:
print fruta$[1]
end
</syntaxhighlight>
<pre>
3
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:
{{works with|Commodore BASIC|2.0 on C-64}}
<
20 A$(0) = "ORANGE"
30 A$(1) = "APPLE"
Line 587:
90 IF T=128 THEN N$=N$+"$": REM STRING
100 L=PEEK(AT+6): REM FIRST INDEX SIZE
110 PRINT N$" HAS"L"ELEMENTS."</
{{Out}}
Line 593:
==={{header|True BASIC}}===
<
DIM fruta$(2)
READ fruta$(1), fruta$(2)
Line 602:
PRINT "La longitud del array fruta$ es" ; tamano
END
</syntaxhighlight>
{{out}}
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.
<
DIM fruit$(2)
MAT READ fruit$
Line 617:
PRINT "The length of the array 'fruit$' is "; SIZE(fruit$)
END
</syntaxhighlight>
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.
<
@echo off
Line 655:
set /a arraylength+=1
goto loop
</syntaxhighlight>
{{in}}
<pre>
Line 667:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<
array$() = "apple", "orange"
PRINT "Number of elements in array = "; DIM(array$(), 1) + 1
PRINT "Number of bytes in all elements combined = "; SUMLEN(array$())
END</
{{Out}}
Line 678:
=={{header|Brat}}==
<
p ["apple", "orange"].length
</syntaxhighlight>
=={{header|BQN}}==
<code>≠</code> gives the length of an array in BQN.
<syntaxhighlight lang
<syntaxhighlight lang
[https://mlochbaum.github.io/BQN/try.html#code=4omgIDHigL8iYSLigL8r Try It!]
Line 697:
For static arrays:
<syntaxhighlight lang=c>
#include <stdio.h>
Line 719:
return 0;
}
</syntaxhighlight>
A C pre-processor macro may be created for ease of use:
<syntaxhighlight lang=c>
#define ARRAY_LENGTH(A) (sizeof(A) / sizeof(A[0]))
</syntaxhighlight>
Note that these arrays become pointers when passed as a parameter to a function.
Line 744:
</p>
====Solution====
<
#define _CRT_NONSTDC_NO_WARNINGS // enable old-gold POSIX names in MSVS
Line 819:
return EXIT_SUCCESS;
}</
{{output}}
<pre>There are 2 elements in an array with a capacity of 10 elements:
Line 827:
====An example why sizeof(A)/sizeof(E) may be a bad idea in C====
<
#define _CRT_NONSTDC_NO_WARNINGS // enable old-gold POSIX names in MSVS
Line 938:
return 0;
}</
<p>
As we can see the ''sizeof(ArrayType)/sizeof(ElementType)'' approach mostly fail.
Line 1,005:
=={{header|C sharp|C#}}==
<
using System;
Line 1,016:
}
}
</syntaxhighlight>
Note that any of the following array declarations could be used:
<
var fruit = new[] { "apple", "orange" };
var fruit = new string[] { "apple", "orange" };
Line 1,026:
string[] fruit = new string[] { "apple", "orange" };
string[] fruit = { "apple", "orange" };
</syntaxhighlight>
A shorter variant could also have been used:
<
using static System.Console;
Line 1,040:
}
}
</syntaxhighlight>
=={{header|C++}}==
Line 1,048:
However, C++ has an additional <code>std::array</code> type (amongst other collections) in its standard library:
<
#include <iostream>
#include <string>
Line 1,057:
std::cout << fruit.size();
return 0;
}</
Note that <code>char*</code> or <code>const char*</code> could have been used instead of <code>std::string</code>.
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.
These all support similar interfaces, though their implementations have different performance characteristics.
<
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.
=={{header|Ceylon}}==
<
value array = ["apple", "orange"];
print(array.size);
}</
=={{header|Clipper/XBase++}}==
<
* nizchka: March - 2016
* This is a Clipper/XBase++ of RosettaCode Array_Length
Line 1,088:
? LEN(FRUIT)
RETURN
</syntaxhighlight>
Outputs:<pre>2</pre>
[[User:nizchka|nizchka]] 23:27, 16 March 2016 (UTC)
Line 1,094:
=={{header|Clojure}}==
<
(count ["apple" "orange"])
; OR alength if using Java arrays:
(alength (into-array ["apple" "orange"]))</
=={{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.
<
program-id. array-length.
Line 1,142:
.
end program array-length.</
{{out}}
<pre>$ cobc -xjd array-length.cob
Line 1,151:
=={{header|ColdFusion}}==
<
<cfset testArray = ["apple","orange"]>
<cfoutput>Array Length = #ArrayLen(testArray)#</cfoutput>
</syntaxhighlight>
Outputs:<pre>Array Length = 2</pre>
[[User:grandnegus|Mike Knapp]] 15:57, 26 May 2016 (UTC)
=={{header|Common Lisp}}==
<
(print (length #("apple" "orange")))
</syntaxhighlight>
===Alternate solution===
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]
<
;; Project : Array length
Line 1,174:
(length my-array)
(terpri)
</syntaxhighlight>
Output:
<pre>
Line 1,182:
=={{header|Component Pascal}}==
{{works with|BlackBox Component Builder}}
<
MODULE AryLen;
IMPORT StdLog;
Line 1,215:
END AryLen.
</syntaxhighlight>
Execute: ^Q AryLen.Do
{{out}}
Line 1,224:
=={{header|Crystal}}==
<
puts ["apple", "orange"].size
</syntaxhighlight>
{{out}}
Line 1,234:
=={{header|D}}==
<syntaxhighlight lang=d>
import std.stdio;
Line 1,243:
return 0;
}
</syntaxhighlight>
Or a somewhat shorter...
<syntaxhighlight lang=d>
import std.stdio;
Line 1,253:
["apple", "orange"].length.writeln;
}
</syntaxhighlight>
=={{header|Dart}}==
<
arrLength(arr) {
return arr.length;
Line 1,266:
}
</syntaxhighlight>
=={{header|DataWeave}}==
<
sizeOf(arr)
</syntaxhighlight>
=={{header|Delphi}}==
<
showmessage( length(['a','b','c']).ToString );
</syntaxhighlight>
=={{header|Diego}}==
<
me_msg()_array()_values(apple,orange)_length();
reset_namespace[];</
{{out}}
Line 1,290:
=={{header|Dragon}}==
<
a = ["apple","orange"]
Line 1,296:
show b
</syntaxhighlight>
=={{header|Dyalect}}==
<
print(xs.Length())</
=={{header|EasyLang}}==
<lang>fruit$[] = [ "apples" "oranges" ]
print len fruit$[]</
=={{header|EchoLisp}}==
<
(length '("apple" "orange")) ;; list
→ 2
(vector-length #("apple" "orange")) ;; vector
→ 2
</syntaxhighlight>
=={{header|Ela}}==
<syntaxhighlight lang
=={{header|Elena}}==
ELENA 5.0 :
<
var array := new string[]{"apple", "orange"};
var length := array.Length;
</syntaxhighlight>
=={{header|Elixir}}==
<
2
iex(2)> tuple_size( {"apple", "orange"} ) # Tuple
2</
=={{header|Elm}}==
<
import Array
import Html
Line 1,343:
|> Basics.toString
|> Html.text
</syntaxhighlight>
=={{header|Emacs Lisp}}==
<
=> 2</
<code>length</code> also accepts a list or a string.
=={{header|Erlang}}==
<
1> length(["apple", "orange"]). %using a list
2
1> tuple_size({"apple", "orange"}). %using a tuple
2
</syntaxhighlight>
=={{header|Euphoria}}==
<
sequence s = {"apple","orange",2.95} -- Euphoria doesn't care what you put in a sequence
Line 1,381:
1 -- 2.95 is an atomic value
</syntaxhighlight>
=={{header|F_Sharp|F#}}==
<
Or:
<
=={{header|Factor}}==
<
{ "apple" "orange" } length
</syntaxhighlight>
=={{header|Forth}}==
Line 1,425:
REPEAT
DROP
R> ; \ return counter to data stack </
Test code at Forth console
<
=={{header|Fortran}}==
Line 1,440:
For a simple example, the WRITE(6,*) suffices: write to standard output (the 6), in free-format (the *).
<
MODULE EXAMPLE
CONTAINS
Line 1,461:
WRITE (6,*) "L. bound",LBOUND(ARRAY),", U. bound",UBOUND(ARRAY)
END
</syntaxhighlight>
Output:
Line 1,475:
=={{header|FreeBASIC}}==
<
Dim fruit(1) As String = {"apple", "orange"}
Line 1,482:
Print
Print "Press any key to quit the program"
Sleep</
{{out}}
Line 1,490:
=={{header|Frink}}==
<
a = ["apple", "orange"]
println[length[a]]
</syntaxhighlight>
=={{header|FurryScript}}==
<
COUNT[ 0 SW ~| COUNT_STEP# 0 SW SU ]
COUNT_STEP[ DR 1 SU ]
`THE_LIST COUNT# +<></
=={{header|Futhark}}==
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:
<
fun length(as: []int): int = (shape as)[0]
</syntaxhighlight>
=={{header|FutureBasic}}==
NSUInteger count = fn ArrayCount( ''array'' ). Example:
<
window 1
print fn ArrayCount( @[@"apple",@"orange",@"cherry",@"grape",@"lemon"] )
HandleEvents
</syntaxhighlight>
{{out}}
<pre>
Line 1,532:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=2a452c807c7030eb64a2f1d60d31a830 Click this link to run this code]'''
<
Dim siList As Short[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
Print siList.Count
End</
Output:
<pre>
Line 1,544:
=={{header|Genie}}==
<
/* Array length, in Genie */
init
arr:array of string = {"apple", "orange"}
stdout.printf("%d ", arr.length)
print arr[1]</
{{out}}
Line 1,558:
=={{header|Go}}==
<
import "fmt"
Line 1,566:
fmt.Printf("Length of %v is %v.\n", arr, len(arr))
}</
Line 1,576:
=={{header|Groovy}}==
<
def fruits = ['apple','orange']
println fruits.size()
</syntaxhighlight>
=={{header|Harbour}}==
<
LOCAL aFruits := {"apple", "orange"}
Qout( Len( aFruits ) ) // --> 2
</syntaxhighlight>
=={{header|Haskell}}==
<
length ["apple", "orange"]</
=={{header|hexiscript}}==
<
let a[0] "apple"
let a[1] "orange"
println len a</
=={{header|Hoon}}==
<
=={{header|i}}==
<
=={{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.
<
=={{header|Idris}}==
<
=={{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.
<
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'
1</
This might be a clearer concept with a few more examples. Here's an array with two dimensions:
<
apple
orange
Line 1,631:
2 6
#>'apple';'orange'
2</
And, here's an array with no dimensions:
<lang> 9001
Line 1,638:
1
$9001
</syntaxhighlight>
You can count the number of dimensions of an array (the length of the list of lengths) using <code>#$array</code>:
<syntaxhighlight lang=j>
#$9001
0
Line 1,646:
1
#$>'apple';'orange'
2</
=={{header|Janet}}==
<
(def our-array @["apple" "orange"])
(length our-array)
</syntaxhighlight>
{{out}}
Line 1,661:
=={{header|Java}}==
<
public static void main(String[] args) {
System.out.println(new String[]{"apple", "orange"}.length);
}
}</
=={{header|JavaScript}}==
<
However, determining the length of a list, array, or collection may simply be the wrong thing to do.
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'''
<
return lst[lst.length - 1];
}</
using length has the disadvantage that it leaves ''last'' simply undefined for an empty list.
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.
<
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:
<
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):
<
return list.slice(-1)[0] || defaultValue;
}</
=={{header|jq}}==
<
Output:
<syntaxhighlight lang
Note that the ''length'' filter is polymorphic, so for example the empty string (""), the empty list ([]), and ''null'' all have ''length'' 0.
=={{header|Jsish}}==
<
var arr = new Array('apple', 'orange');
puts(arr.length);
puts(arr[1]);</
{{out}}
Line 1,722:
=={{header|Julia}}==
<
a = ["apple","orange"]
length(a)
</syntaxhighlight>
=={{header|Klingphix}}==
<
( "apple" "orange" ) len print
" " input</
{{out}}
<pre>2</pre>
Line 1,738:
=={{header|Klong}}==
<syntaxhighlight lang=K>
#["apple" "orange"]
</syntaxhighlight>
=={{header|Kotlin}}==
<
println(arrayOf("apple", "orange").size)
}</
=={{header|Lambdatalk}}==
<
{A.length {A.new 1 2 3}}
-> 3
</syntaxhighlight>
=={{header|Latitude}}==
Line 1,758:
In Latitude, <code>length</code> and <code>size</code> are synonymous and will both retrieve the size of a collection.
<
=={{header|Liberty BASIC}}==
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/
{{works with|LB Booster}}
<syntaxhighlight lang=lb>
FruitList$(0)="apple" 'assign 2 cells of a list array
FruitList$(1)="orange"
Line 1,882:
print ")"
end sub
</syntaxhighlight>
{{out}}
<pre>
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.
<
set a [list "apple"]
append a "orange"
print [count $a]
print [index $a 1]</
{{out}}
Line 1,905:
=={{header|Limbo}}==
<
include "sys.m";
Line 1,920:
a := array[] of {"apple", "orange"};
sys->print("length of a: %d\n", len a);
}</
=={{header|Lingo}}==
<
put fruits.count
-- 2</
=={{header|Little}}==
<
puts(length(fruit));</
=={{header|LiveCode}}==
<
split fruit using comma
answer the number of elements of fruit</
=={{header|Lua}}==
<
fruits = {"apple", "orange"}
print(#fruits)
Line 1,955:
end
print(size(fruits))</
{{out}}
<pre>
Line 1,964:
=={{header|M2000 Interpreter}}==
<
\\ A is a pointer to array
A=("Apple", "Orange")
Line 2,003:
Dim K(1,1,1,1,1,1) ' Maximum 10 dimensions
Print Len(K()=1 ' True
</syntaxhighlight>
=={{header|Maple}}==
<
numelems(a);</
{{out}}
<pre>
Line 2,015:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
=={{header|MATLAB}} / {{header|Octave}}==
<
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.
<
=={{header|Modula-3}}==
<
IMPORT IO;
Line 2,032:
BEGIN
IO.PutInt(NUMBER(Arr));
END ArrayLength.</
=={{header|Mercury}}==
<
:- interface.
Line 2,047:
main(!IO) :-
Array = array(["apples", "oranges"]),
io.write_int(size(Array), !IO).</
=={{header|min}}==
{{works with|min|0.19.3}}
<
{{out}}
<pre>
Line 2,058:
=={{header|MiniScript}}==
<
fruits = ["apple", "orange"]
print fruits.len
</syntaxhighlight>
=={{header|MiniZinc}}==
<
array[int] of int: arr = [1,2,3];
var int: size = length(arr);
Line 2,070:
output [show(size),"\n"];
</syntaxhighlight>
=={{header|Nanoquery}}==
<
fruit[0] = "apple"
fruit[1] = "orange"
println len(fruit)
// outputs 2</
=={{header|Neko}}==
<
$print($asize(fruit));</
=={{header|NewLISP}}==
<
; Nehal-Singhal 2018-05-25
(length '(apple orange))</
=={{header|NGS}}==
<
# same
echo(['apple', 'orange'].len())</
=={{header|Nim}}==
<
echo "The length of the fruit array is ", len(fruit)</
{{out}}
Line 2,107:
=={{header|Oberon-2}}==
{{works with|oo2c}}
<
MODULE ArrayLength;
IMPORT
Line 2,139:
Out.String("length: ");Out.Int(Length(a),0);Out.Ln
END ArrayLength.
</syntaxhighlight>
{{out}}
<pre>
Line 2,146:
=={{header|Objeck}}==
<
class Test {
function : Main(args : String[]) ~ Nil {
Line 2,152:
fruit->Size()->PrintLine();
}
}</
=={{header|OCaml}}==
<
Array.length [|"apple"; "orange"|];;
</syntaxhighlight>
=={{header|Oforth}}==
<
=={{header|Ol}}==
All of these methods are equivalent.
<
(print (vector-length (vector "apple" "orange")))
(print (vector-length #("apple" "orange")))
Line 2,170:
(print (size #("apple" "orange")))
</syntaxhighlight>
=={{header|Onyx}}==
<
=={{header|ooRexx}}==
<
/* REXX */
a = .array~of('apple','orange')
Line 2,184:
say e
End
Say "a[2]="a[2]</
{{out}}
<pre>2 elements
Line 2,192:
=={{header|PARI/GP}}==
<
length(array) \\ == 2
#array \\ == 2</
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:
{{works with|Free Pascal|2.6.2}}
<
#!/usr/bin/instantfpc
//program ArrayLength;
Line 2,219:
WriteLn('Length of Fruits by bounds : ', High(Fruits) - Low(Fruits) + 1);
END.
</syntaxhighlight>
{{out}}
Line 2,233:
The way to get the number of elements of an array in Perl is to put the array in scalar context.
<
scalar @array; # 5
Line 2,252:
takes_a_scalar @array;
# the built-ins can also act like they have prototypes</
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.
<
length @array; # 1
Line 2,267:
print 'the length of @array is on the order of ';
print 10 ** (length( @array )-1); # 100
print " elements long\n";</
=={{header|Phix}}==
{{libheader|Phix/basics}}
<!--<
<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;">)
<!--</
{{out}}
<pre>
Line 2,281:
=={{header|Phixmonti}}==
<
With syntactic sugar
<
( "apple" "orange" ) len print</
{{out}}
<pre>
Line 2,292:
=={{header|PHP}}==
<
=={{header|Picat}}==
Line 2,300:
println(length(L)),
println(L.len),
println(L.length).</
{{out}}
Line 2,310:
=={{header|PicoLisp}}==
<
-> 2
:</
=={{header|Pike}}==
<
{
array fruit = ({ "apple", "orange" });
write("%d\n", sizeof(fruit));
}</
{{out}}
Line 2,325:
=={{header|PL/I}}==
<
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;</
{{out}}
<pre>
Line 2,337:
=={{header|Plorth}}==
<
=={{header|Pony}}==
<
actor Main
new create(env:Env)=>
Line 2,347:
c.push("orange")
env.out.print("Array c is " + c.size().string() + " elements long!")
</syntaxhighlight>
=={{header|Potion}}==
<
=={{header|PowerShell}}==
<
$Array = @( "Apple", "Orange" )
$Array.Count
$Array.Length</
{{out}}
<pre>
Line 2,363:
=={{header|Processing}}==
<
String[] arr = {"apple", "orange"};
void setup(){
println(arr.length);
}
</syntaxhighlight>
{{out}}
<pre>
Line 2,375:
==={{header|Processing Python mode}}===
<
arr = ['apple', 'orange'] # a list for an array
def setup():
println(len(arr))
</syntaxhighlight>
{{out}}
Line 2,388:
=={{header|Prolog}}==
<
X = 2
yes</
=={{header|PureBasic}}==
<
EnableExplicit
Define Dim fruit$(1); defines array with 2 elements at indices 0 and 1
Line 2,408:
CloseConsole()
EndIf
</syntaxhighlight>
{{out}}
<pre>
Line 2,415:
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.
</syntaxhighlight>
{{out}}
<pre>
Line 2,427:
=={{header|Python}}==
<
2
>>> </
=={{header|QB64}}==
<
Dim max As Integer, Index As Integer
Randomize Timer
Line 2,444:
Print UBound(Stringar)
End
</syntaxhighlight>
=={{header|Quackery}}==
<Lang Quackery> $ "apples" $ "oranges" 2 pack size echo</
{{out}}
Line 2,454:
=={{header|R}}==
<syntaxhighlight lang=R>
a <- c('apple','orange') # create a vector containing "apple" and "orange"
length(a)
</syntaxhighlight>
{{out}}
<pre>
Line 2,465:
=={{header|Racket}}==
{{trans|EchoLisp}}
<
(length '("apple" "orange")) ;; list
(vector-length #("apple" "orange")) ;; vector</
{{out}}
<pre>2
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.
<
my @array = <apple orange>;
Line 2,485:
say + @array; # 2
say @array + 0; # 2
</syntaxhighlight>
Watch out for infinite/lazy arrays though. You can't get the length of those.
<
say @infinite[5000]; # 5001
say @infinite.elems; # Throws exception "Cannot .elems a lazy list"
</syntaxhighlight>
=={{header|Rapira}}==
<
output: #arr</
=={{header|Red}}==
<
== 2</
=={{header|Relation}}==
<
relation fruit
insert "apples"
Line 2,510:
project fruit count
print
</syntaxhighlight>
{| border=1
Line 2,520:
=={{header|ReScript}}==
<
Js.log(Js.Array.length(fruits))</
<
<html>
<head>
Line 2,537:
</body>
</html></
{{out}}
<pre>// Generated by ReScript, PLEASE EDIT WITH CARE
Line 2,554:
=={{header|REXX}}==
<
* The compond variable a. implements an array
* By convention, a.0 contains the number of elements
Line 2,570:
a.z=arg(1)
a.0=z
Return</
{{out}}
<pre>There are 2 elements in the array:
Line 2,578:
=={{header|Ring}}==
<
=={{header|Robotic}}==
Line 2,584:
Example 1:
<
set "index" to 0
set "$array&index&" to "apple"
Line 2,590:
set "$array&index&" to "orange"
* "Array length: ('index' + 1)"
</syntaxhighlight>
Example 2:
<
set "index" to 0
set "local1" to random 1 to 99
Line 2,602:
if "local1" > 1 then "rand"
* "Array length: ('index')"
</syntaxhighlight>
=={{header|Ruby}}==
<
=={{header|Rust}}==
Line 2,612:
By default arrays are immutable in rust.
<
fn main() {
let array = ["foo", "bar", "baz", "biff"];
println!("the array has {} elements", array.len());
}
</syntaxhighlight>
=={{header|Scala}}==
<
println(Array("apple", "orange").length)
</syntaxhighlight>
=={{header|Scheme}}==
Line 2,629:
Using Scheme's vector type as an equivalent to an array:
<
(display (vector-length #("apple" "orange")))
</syntaxhighlight>
=={{header|Seed7}}==
The function [http://seed7.sourceforge.net/libraries/array.htm#length(in_arrayType) length]
determines the length of an array.
<
const array string: anArray is [] ("apple", "orange");
Line 2,643:
begin
writeln(length(anArray));
end func;</
=={{header|SenseTalk}}==
<
put the number of items in fruits</
=={{header|Shen}}==
<
\\ Using a vector
\\ @v creates the vector
Line 2,661:
\\ As an list
(length [apple orange])
</syntaxhighlight>
=={{header|Sidef}}==
<
say arr.len; #=> 2
say arr.end; #=> 1 (zero based)</
=={{header|Simula}}==
<
BEGIN
Line 2,685:
OUTIMAGE;
END
</syntaxhighlight>
{{out}}
<pre>
Line 2,692:
=={{header|Smalltalk}}==
<
a := #('apple' 'orange').
a size</
=={{header|SNOBOL4}}==
<
ar<1,1> = 'apple'
ar<1,2> = 'first'
Line 2,703:
ar<2,2> = 'second'
OUTPUT = IDENT(DATATYPE(ar), 'ARRAY') PROTOTYPE(ar)
end</
{{out}}<pre>2,2</pre>
=={{header|SPL}}==
<
#.output("Number of elements in array: ",#.size(a,1))</
{{out}}
<pre>
Line 2,716:
=={{header|SQL}}==
<
=={{header|Standard ML}}==
<
val a = Array.fromList ["apple", "orange"]
in
Array.length a
end;</
=={{header|Stata}}==
Line 2,729:
=== Dimensions of a dataset ===
<
input str10 fruit
apple
Line 2,736:
di _N
di c(N) " " c(k)</
=== Length of a macro list ===
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''.
<
di `: list sizeof fruits'
di `: word count `fruits''</
=== Mata ===
For a Mata array, use '''[https://www.stata.com/help.cgi?mf_rows rows]''' and similar functions:
<
a=st_sdata(.,"fruit")
rows(a)
cols(a)
length(a)
end</
=={{header|Swift}}==
<
let fruitsCount = fruits.count // Declare constant array length (count)
print(fruitsCount) // Print array length to output window</
{{out}}<pre>2</pre>
=={{header|Symsyn}}==
<
| Symsyn does not support Array of Strings
| The following code for an Array of Integers
Line 2,779:
sz []
| shows 2
</syntaxhighlight>
=={{header|Tailspin}}==
<
['apple', 'orange'] -> $::length -> !OUT::write
</syntaxhighlight>
{{out}}
<pre>2</pre>
Line 2,791:
<!-- http://ideone.com/uotEvm -->
<
set mylistA {apple orange} ;# actually a string
set mylistA "Apple Orange" ;# same - this works only for simple cases
Line 2,804:
set lenB [llength $mylistB]
puts "$mylistB : $lenB"
</syntaxhighlight>
{{out}}
Line 2,813:
{{works with|TI-83 2.55MP}}
Use function <code>dim()</code>.
<
dim(L1)</
{{out}}
<pre>
Line 2,821:
=={{header|Transd}}==
<
MainModule : {
Line 2,830:
(lout (size ["apple", "orange"]))
)
}</
<pre>
2
Line 2,837:
=={{header|UNIX Shell}}==
<
array=("orange" "apple")
echo "${#array[@]}"</
{{out}}
<pre>
Line 2,855:
=={{header|Vala}}==
<
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" };
</syntaxhighlight>
A shorter variant could also have been used:
<
void main() {
stdout.printf("%d\n", new string[] {"apples", "orange"}.length);
}
</syntaxhighlight>
=={{header|VBA}}==
One-liner. Assumes array lower bound, which is not always safe.
<
Works regardless of lower bound:
<
Public Function SizeOfArray(ar As Variant) As Long
Line 2,888:
'call the function
Debug.Print "Array Length: " & SizeOfArray(funkyArray)</
{{Out}}
Line 2,895:
=={{header|VBScript}}==
<
WScript.StdOut.WriteLine UBound(arr) - LBound(arr) + 1 </
{{Out}}
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.
<syntaxhighlight lang=vb>
' declared in a module
Public Function LengthOfArray(ByRef arr As Variant) As Long
Line 2,931:
Debug.Print LengthOfArray(arr) ' prints 2 as result
</syntaxhighlight>
=={{header|Visual Basic .NET}}==
{{works with|Visual Basic .NET|9.0+}}
<
Sub Main()
Line 2,943:
End Module
</syntaxhighlight>
{{out}}
Line 2,952:
=={{header|Vlang}}==
A '''len''' property is maintained for all V arrays.
<
// Tectonics: v run array-length.v
module main
Line 2,960:
arr := ["apple", "orange"]
println(arr.len)
}</
{{out}}<pre>prompt$ v run array-length.v
Line 2,966:
=={{header|WDTE}}==
<
let a => ['apple'; 'orange'];
len a -- io.writeln io.stdout;</
=={{header|Wren}}==
<
System.print(arr.count)</
{{out}}
Line 2,980:
=={{header|XLISP}}==
<
=={{header|Yabasic}}==
<
dim fruta$(3)
read fruta$(1), fruta$(2), fruta$(3)
Line 2,992:
print fruta$(2)
end
</syntaxhighlight>
<pre>
3
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.
<
ld hl,TestArray
call GetArrayLength_WordData_NullTerminated
Line 3,048:
byte "Apple",0
Orange:
byte "Orange",0</
{{out}}
Line 3,057:
=={{header|zkl}}==
zkl doesn't support arrays natively, use lists instead.
<
T("apple", "orange").len().println() //-->2, read only list (ROList) </
=={{header|Zig}}==
<
pub fn main() !void {
Line 3,069:
// slices and arrays have an len field
try stdout_wr.print("fruit.len = {d}\n", .{fruit.len});
}</
=={{header|Zoea}}==
<
program: array_length
input: [a,b,c]
output: 3
</syntaxhighlight>
=={{header|Zoea Visual}}==
Line 3,082:
=={{header|zonnon}}==
<
module AryLength;
type
Line 3,097:
writeln(len(b,1):4) (* second dimension *)
end AryLength.
</syntaxhighlight>
|