Array length
Determine the amount of elements in an array.
As an example use an array holding the strings 'apple' and 'orange'.
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
- See also
ALGOL 68
<lang algol68># UPB returns the upper bound of an array, LWB the lower bound # []STRING fruits = ( "apple", "orange" ); print( ( ( UPB fruits - LWB fruits ) + 1, newline ) ) # prints 2 #</lang>
AWK
The main use of the length()-function is to determine the length of a string.
When used on an array, it returns the number of elements.
Another method to count the elements of the array is by using a variant of for().
<lang awk># usage: awk -f arraylen.awk
function countElements(array) {
for( e in array ) {c++} return c
}
BEGIN {
array[1] = "apple" array[2] = "orange"
print "Array length :", length(array), countElements(array) print "String length:", array[1], length(array[1])
}</lang>
- Output:
Array length : 2 2 String length: apple 5
BASIC
<lang basic>DIM X$(1 TO 2) X$(1) = "apple" X$(2) = "orange" PRINT UBOUND(X$) - LBOUND(X$) + 1</lang>
C
C features two kinds of arrays: static (compile-time, fixed size) and dynamic (allocated at runtime).
The length of a dynamic array cannot be acquired from the array itself - its length must be stored elsewhere.
For static arrays:
<lang c>
- include <stdio.h>
int main() {
const char *fruit[2] = { "apples", "oranges" };
// Acquire the length of the array by dividing the size of all elements (found // with sizeof(fruit)) by the size of the first element.
// Note that since the array elements are pointers to null-terminated character // arrays, the size of the first element is actually the size of the pointer // type - not the length of the string.
// This size, regardless of the type being pointed to, is 8 bytes, 4 bytes, or // 2 bytes on 64-bit, 32-bit, or 16-bit platforms respectively. int length = sizeof(fruit) / sizeof(fruit[0]);
printf("%d\n", length);
return 0;
} </lang>
A C pre-processor macro may be created for ease of use:
<lang c>
- define ARRAY_LENGTH(A) (sizeof(A) / sizeof(A[0]))
</lang>
Note that these arrays become pointers when passed as a parameter to a function. Thus, the length of an array parameter may not be required directly - a dedicated length parameter would be required.
C++
C++ follows the same rules as C regarding static and dynamic arrays.
However, C++ has an additional std::array type (amongst other collections) in its standard library:
<lang cpp>
- include <array>
- include <iostream>
- include <string>
int main() {
std::array<std::string, 2> fruit { "apples", "oranges" }; std::cout << fruit.size(); return 0;
} </lang>
Note that char* or const char* could have been used instead of std::string.
C#
<lang csharp> using System;
class Program {
public static void Main() { var fruit = new[] { "apple", "orange" }; Console.WriteLine(fruit.Length); }
} </lang>
Note that any of the following array declarations could be used:
<lang csharp> var fruit = new[] { "apple", "orange" }; var fruit = new string[] { "apple", "orange" }; string[] fruit = new[] { "apple", "orange" }; string[] fruit = new string[] { "apple", "orange" }; string[] fruit = { "apple", "orange" }; </lang>
A shorter variant could also have been used:
<lang csharp> using static System.Console;
class Program {
public static void Main() { WriteLine(new[] { "apples", "oranges" }.Length); }
} </lang>
D
<lang d> import std.stdio;
int main() {
auto fruit = ["apple", "orange"]; fruit.length.writeln; return 0;
} </lang>
Or a somewhat shorter... <lang d> import std.stdio;
void main() {
["apple", "orange"].length.writeln;
} </lang>
EchoLisp
<lang scheme> (length '("apple" "orange")) ;; list
→ 2
(vector-length #("apple" "orange")) ;; vector
→ 2
</lang>
FurryScript
<lang furryscript>THE_LIST( <apple> <orange> ) COUNT[ 0 SW ~| COUNT_STEP# 0 SW SU ] COUNT_STEP[ DR 1 SU ]
`THE_LIST COUNT# +<></lang>
Haskell
<lang Haskell>-- Char -> Int length ["apple", "orange"]</lang>
Java
<lang java>public class ArrayLength {
public static void main(String[] args) { System.out.println(new String[]{"apple", "orange"}.length); }
}</lang>
JavaScript
<lang javascript>console.log(['apple', 'orange'].length);</lang>
ooRexx
<lang oorexx> /* REXX */ a = .array~of('apple','orange') say a~size 'elements' Do e over a
say e End
Say "a[2]="a[2]</lang>
- Output:
2 elements apple orange a[2]=orange
Perl 6
<lang perl6>say <apple orange>.elems;</lang>
- Output:
2
Phix
<lang Phix>constant fruits = {"apple","orange"} ?length(fruits)</lang>
- Output:
2
PHP
<lang php>print count(['apple', 'orange']); // Returns 2</lang>
Python
<lang python>>>> print(len(['apple', 'orange'])) 2 >>> </lang>
Racket
<lang racket>#lang racket/base (length '("apple" "orange")) ;; list (vector-length #("apple" "orange")) ;; vector</lang>
- Output:
2 2
REXX
<lang rexx>/* REXX ----------------------------------------------
- The compond variable a. implements an array
- By convention, a.0 contains the number of elements
- ---------------------------------------------------*/
a.=0 /* initialize the "array" */ call store 'apple' Call store 'orange' Say 'There are' a.0 'elements in the array:' Do i=1 To a.0
Say 'Element' i':' a.i End
Exit store: Procedure Expose a. z=a.0+1 a.z=arg(1) a.0=z Return</lang>
- Output:
There are 2 elements in the array: Element 1: apple Element 2: orange
Ruby
<lang ruby>puts ['apple', 'orange'].length # or .size</lang>
SQL
<lang sql>SELECT COUNT() FROM (VALUES ('apple'),('orange'));</lang>
Tcl
<lang tcl>;# not recommanded: set mylistA {apple orange} ;# actually a string set mylistA "Apple Orange" ;# same - this works only for simple cases
set lenA [llength $mylistA] puts "$mylistA : $lenA"
- better: to build a list, use 'list' and/or 'lappend':
set mylistB [list apple orange "red wine" {green frog}] lappend mylistB "blue bird"
set lenB [llength $mylistB] puts "$mylistB : $lenB" </lang>
- Output:
Apple Orange : 2 apple orange {red wine} {green frog} {blue bird} : 5
zkl
zkl doesn't support arrays natively, use lists instead. <lang zkl>List("apple", "orange").len().println() //-->2, == L("apple", "orange") T("apple", "orange").len().println() //-->2, read only list (ROList) </lang>