' Rosetta Code problem: https://rosettacode.org/wiki/Arithmetic_numbers
' by Jjuanhdez, 06/2022

Dim As Double t0 = Timer
Dim As Integer N = 1, ArithCnt = 0, CompCnt = 0
Dim As Integer Div, DivCnt, Sum, Quot

Print "The first 100 arithmetic numbers are:"
Do
    Div = 1 : DivCnt = 0 : Sum = 0
    Do
        Quot = N / Div
        If Quot < Div Then Exit Do
        If Quot = Div AndAlso (N Mod Div) = 0 Then 'N is a square
            Sum += Quot
            DivCnt += 1
            Exit Do
        End If
        If (N Mod Div) = 0 Then
            Sum += Div + Quot
            DivCnt += 2
        End If
        Div += 1
    Loop

    If (Sum Mod DivCnt) = 0 Then                   'N is arithmetic
        ArithCnt += 1
        If ArithCnt <= 100 Then
            Print Using "####"; N;
            If (ArithCnt Mod 20) = 0 Then Print
        End If
        If DivCnt > 2 Then CompCnt += 1
        Select Case ArithCnt
        Case 1e3
            Print Using !"\nThe #######th arithmetic number is #####,### up to which ###,### are composite."; ArithCnt; N; CompCnt
        Case 1e4, 1e5, 1e6
            Print Using "The #######th arithmetic number is #####,### up to which ###,### are composite."; ArithCnt; N; CompCnt
        End Select
    End If
    N += 1
Loop Until ArithCnt >= 1e6
Print !"\nTook"; Timer - t0; " seconds on i5 @3.20 GHz"
Sleep


{{works with| Delphi-6 or better}}
program ArithmeiticNumbers;

{$APPTYPE CONSOLE}

procedure ArithmeticNumbers;
var N, ArithCnt, CompCnt, DDiv: integer;
var DivCnt, Sum, Quot, Rem: integer;
begin
N:= 1;  ArithCnt:= 0;  CompCnt:= 0;
repeat
	begin
	DDiv:= 1;  DivCnt:= 0;  Sum:= 0;
	while true do
		begin
		Quot:= N div DDiv;
		Rem:=N mod DDiv;
		if Quot < DDiv then break;
		if (Quot = DDiv) and (Rem = 0) then //N is a square
			begin
			Sum:= Sum+Quot;
			DivCnt:= DivCnt+1;
			break;
			end;
		if Rem = 0 then
			begin
			Sum:= Sum + DDiv + Quot;
			DivCnt:= DivCnt+2;
			end;
		DDiv:= DDiv+1;
		end;
	if (Sum mod DivCnt) = 0 then //N is arithmetic
		begin
		ArithCnt:= ArithCnt+1;
		if ArithCnt <= 100 then
			begin
			Write(N:4);
			if (ArithCnt mod 20) = 0 then WriteLn;
			end;
		if DivCnt > 2 then CompCnt:= CompCnt+1;
		case ArithCnt of 1000, 10000, 100000, 1000000:
			begin
			Writeln;
			Write(N, #9 {tab} );
			Write(CompCnt);
			end;
	 	 end;
	 	end;
        N:= N+1;
        end
until   ArithCnt >= 1000000;
WriteLn;
end;

begin
ArithmeticNumbers;
WriteLn('Hit Any Key');
ReadLn;
end.


   declare x(12) fixed;
   declare b(5) fixed defined x;
   declare c(7) fixed defined x(1sub+5);


actor Main
    new create(env:Env)=>
        var a:Array[I32]=Array[I32](4)
        var b:Array[I32]=Array[I32](2)
        a.push(1)
        a.push(2)
        a.push(3)
        a.push(4)
        b.push(5)
        b.push(6)
        a.concat(b.values())
        for i in a.values() do
            env.out.print(i.string())
        end


MOVE.L #$00100000,A0      ;define an array at memory address $100000


package main

import (
    "fmt"
    "math"
    "rcu"
    "sort"
)

func main() {
    arithmetic := []int{1}
    primes := []int{}
    limit := int(1e6)
    for n := 3; len(arithmetic) < limit; n++ {
        divs := rcu.Divisors(n)
        if len(divs) == 2 {
            primes = append(primes, n)
            arithmetic = append(arithmetic, n)
        } else {
            mean := float64(rcu.SumInts(divs)) / float64(len(divs))
            if mean == math.Trunc(mean) {
                arithmetic = append(arithmetic, n)
            }
        }
    }
    fmt.Println("The first 100 arithmetic numbers are:")
    rcu.PrintTable(arithmetic[0:100], 10, 3, false)

    for _, x := range []int{1e3, 1e4, 1e5, 1e6} {
        last := arithmetic[x-1]
        lastc := rcu.Commatize(last)
        fmt.Printf("\nThe %sth arithmetic number is: %s\n", rcu.Commatize(x), lastc)
        pcount := sort.SearchInts(primes, last) + 1
        if !rcu.IsPrime(last) {
            pcount--
        }
        comp := x - pcount - 1 // 1 is not composite
        compc := rcu.Commatize(comp)
        fmt.Printf("The count of such numbers <= %s which are composite is %s.\n", lastc, compc)
    }
}


using Primes

function isarithmetic(n)
    f = [one(n)]
    for (p,e) in factor(n)
        f = reduce(vcat, [f*p^j for j in 1:e], init=f)
    end
    return rem(sum(f), length(f)) == 0
end

function arithmetic(n)
    i, arr = 1, Int[]
    while length(arr) < n
        isarithmetic(i) && push!(arr, i)
        i += 1
    end
    return arr
end

a1M = arithmetic(1_000_000)
composites = [!isprime(i) for i in a1M]

println("The first 100 arithmetic numbers are:")
foreach(p -> print(lpad(p[2], 5), p[1] % 20 == 0 ? "\n" : ""), enumerate(a1M[1:100]))

println("\n        X    Xth in Series  Composite")
for n in [1000, 10_000, 100_000, 1_000_000]
    println(lpad(n, 9), lpad(a1M[n], 12), lpad(sum(composites[2:n]), 14))
end


; constant array (elements are unchangeable) - the array is stored in the CODE segment
myarray db 'Array' ; db = define bytes - initializes 5 bytes with values 41, 72, 72, etc. (the ascii characters A,r,r,a,y)
myarray2 dw 'A','r','r','a','y' ; dw = define words - initializes 5 words (1 word = 2 bytes) with values 41 00 , 72 00, 72 00, etc.
; how to read index a of the array
        push acc
        push dph
        push dpl
        mov dpl,#low(myarray) ; location of array
        mov dph,#high(myarray)
        movc a,@a+dptr	; a = element a
        mov r0, a	; r0 = element a
        pop dpl
        pop dph
        pop acc		; a = original index again

; array stored in internal RAM (A_START is the first register of the array, A_END is the last)
; initalise array data (with 0's)
	push 0
	mov r0, #A_START
clear:
	mov @r0, #0
	inc r0
	cjne r0, #A_END, clear
	pop 0
; how to read index r1 of array
	push psw
	mov a, #A_START
	add a, r1	; a = memory location of element r1
	push 0
	mov r0, a
	mov a, @r0	; a = element r1
	pop 0
	pop psw
; how to write value of acc into index r1 of array
	push psw
	push 0
	push acc
	mov a, #A_START
	add a, r1
	mov r0, a
	pop acc
	mov @r0, a	; element r1 = a
	pop 0
	pop psw

; array stored in external RAM (A_START is the first memory location of the array, LEN is the length)
; initalise array data (with 0's)
	push dph
	push dpl
	push acc
	push 0
	mov dptr, #A_START
	clr a
	mov r0, #LEN
clear:
	movx @dptr, a
	inc dptr
	djnz r0, clear
	pop 0
	pop acc
	pop dpl
	pop dph
; how to read index r1 of array
	push dph
	push dpl
	push 0
	mov dptr, #A_START-1
	mov r0, r1
	inc r0
loop:
	inc dptr
	djnz r0, loop
	movx a, @dptr	; a = element r1
	pop 0
	pop dpl
	pop dph
; how to write value of acc into index r1 of array
	push dph
	push dpl
	push 0
	mov dptr, #A_START-1
	mov r0, r1
	inc r0
loop:
	inc dptr
	djnz r0, loop
	movx @dptr, a	; element r1 = a
	pop 0
	pop dpl
	pop dph


program ArithmeiticNumbers;

procedure ArithmeticNumbers;
var N, ArithCnt, CompCnt, DDiv: longint;
var DivCnt, Sum, Quot, Rem: longint;
begin
N:= 1;  ArithCnt:= 0;  CompCnt:= 0;
repeat
	begin
	DDiv:= 1;  DivCnt:= 0;  Sum:= 0;
	while true do
		begin
		Quot:= N div DDiv;
		Rem:=N mod DDiv;
		if Quot < DDiv then break;
		if (Quot = DDiv) and (Rem = 0) then //N is a square
			begin
			Sum:= Sum+Quot;
			DivCnt:= DivCnt+1;
			break;
			end;
		if Rem = 0 then
			begin
			Sum:= Sum + DDiv + Quot;
			DivCnt:= DivCnt+2;
			end;
		DDiv:= DDiv+1;
		end;
	if (Sum mod DivCnt) = 0 then //N is arithmetic
		begin
		ArithCnt:= ArithCnt+1;
		if ArithCnt <= 100 then
			begin
			Write(N:4);
			if (ArithCnt mod 20) = 0 then WriteLn;
			end;
		if DivCnt > 2 then CompCnt:= CompCnt+1;
		case ArithCnt of 1000, 10000, 100000, 1000000:
			begin
			Writeln;
			Write(N, #9 {tab} );
			Write(CompCnt);
			end;
	 	 end;
	 	end;
        N:= N+1;
        end
until   ArithCnt >= 1000000;
WriteLn;
end;

begin
ArithmeticNumbers;
WriteLn('Hit Any Key');
{$IFDEF WINDOWS}ReadLn;{$ENDIF}
end.


use strict;
use warnings;
use feature 'say';

use List::Util <max sum>;
use ntheory <is_prime divisors>;
use Lingua::EN::Numbers qw(num2en num2en_ordinal);

sub comma { reverse ((reverse shift) =~ s/(.{3})/$1,/gr) =~ s/^,//r }
sub table { my $t = 10 * (my $c = 1 + length max @_); ( sprintf( ('%'.$c.'d')x@_, @_) ) =~ s/.{1,$t}\K/\n/gr }

my @A = 0;
for my $n (1..2E6)  {
    my @div = divisors $n;
    push @A, $n if 0 == sum(@div) % @div;
}

say "The first @{[num2en 100]} arithmetic numbers:";
say table @A[1..100];

for my $x (1E3, 1E4, 1E5, 1E6) {
    say "\nThe @{[num2en_ordinal $x]}: " . comma($A[$x]) .
        "\nComposite arithmetic numbers ≤ @{[comma $A[$x]]}: " . comma -1 + grep { not is_prime($_) } @A[1..$x];
}


Procedure displayArray(Array a(1), msg.s)
  Protected i
  Print(msg + " [")
  For i = 0 To ArraySize(a())
    Print(Str(a(i)))
    If i <> ArraySize(a())
      Print(", ")
    EndIf
  Next
  PrintN("]")
EndProcedure

Procedure randomElements(Array a(1), lo, hi)
  Protected i
  For i = 0 To ArraySize(a())
    a(i) = random(hi - lo) + lo
  Next
EndProcedure

Procedure arrayConcat(Array a(1), Array b(1), Array c(1))
  Protected i, newSize = ArraySize(a()) + ArraySize(b()) + 1
  Dim c(newSize)
  For i = 0 To ArraySize(a())
    c(i) = a(i)
  Next
  For i = 0 To ArraySize(b())
    c(i + ArraySize(a()) + 1) = b(i)
  Next
EndProcedure

If OpenConsole()
  Dim a(random(3) + 1)
  Dim b(random(3) + 1)
  Dim c(0) ;array will be resized by arrayConcat()

  randomElements(a(), -5, 5)
  randomElements(b(), -5, 5)
  displayArray(a(), "a:")
  displayArray(b(), "b:")
  arrayConcat(a(), b(), c())
  displayArray(c(), "concat of a[] + b[]:")

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
  Input()
  CloseConsole()
EndIf


[ 1 , 2  ,3 ] \ an array holding three numbers
1 a:@       \ this will be '2', the element at index 1
drop
1 123 a:@ \ this will store the value '123' at index 1, so now
.              \ will print [1,123,3]

[1,2,3] 45 a:push
\ gives us [1,2,3,45]
\ and empty spots are filled with null:
[1,2,3] 5 15 a:!
\ gives [1,2,3,null,15]

\ arrays don't have to be homogenous:
[1,"one", 2, "two"]


/* ARM assembly AARCH64 Raspberry PI 3B */
/*  program areaString64.s   */

/*******************************************/
/* Constantes file                         */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Initialized data                        */
/*******************************************/
.data
szMessStringsch:   .ascii "The string is at item : @ \n"
szCarriageReturn:  .asciz "\n"
szMessStringNfound: .asciz "The string is not found in this area.\n"

/* areas strings  */
szString1:  .asciz "Apples"
szString2:  .asciz "Oranges"
szString3:  .asciz "Pommes"
szString4:  .asciz "Raisins"
szString5:  .asciz "Abricots"

/* pointer items area 1*/
tablesPoi1:
pt1_1:        .quad szString1
pt1_2:        .quad szString2
pt1_3:        .quad szString3
pt1_4:        .quad szString4
ptVoid_1:     .quad 0
ptVoid_2:     .quad 0
ptVoid_3:     .quad 0
ptVoid_4:     .quad 0
ptVoid_5:     .quad 0

szStringSch:  .asciz "Raisins"
szStringSch1: .asciz "Ananas"
/*******************************************/
/* UnInitialized data                      */
/*******************************************/
.bss
sZoneConv:       .skip 30
/*******************************************/
/*  code section                           */
/*******************************************/
.text
.global main
main:                      // entry of program

                           // add string 5 to area
    ldr x1,qAdrtablesPoi1  // begin pointer area 1
    mov x0,0               // counter
1:                         // search first void pointer
    ldr x2,[x1,x0,lsl 3]   // read string pointer address item x0 (4 bytes by pointer)
    cmp x2,0               // is null ?
    cinc x0,x0,ne          // no increment counter
    bne 1b                 // and loop

                           // store pointer string 5 in area  at position x0
    ldr x2,qAdrszString5   // address string 5
    str x2,[x1,x0,lsl 3]   // store address

                           // display string at item 3
    mov x2,2               // pointers begin in position 0
    ldr x1,qAdrtablesPoi1  // begin pointer area 1
    ldr x0,[x1,x2,lsl 3]
    bl affichageMess
    ldr x0,qAdrszCarriageReturn
    bl affichageMess

                           // search string in area
    ldr x1,qAdrszStringSch
    //ldr x1,qAdrszStringSch1  // uncomment for other search : not found !!
    ldr x2,qAdrtablesPoi1  // begin pointer area 1
    mov x3,0
2:                         // search
    ldr x0,[x2,x3,lsl 3]   // read string pointer address item x0 (4 bytes by pointer)
    cbz x0,3f              // is null ?  end search
    bl comparString
    cmp x0,0               // string = ?
    cinc x3,x3,ne          // no increment counter
    bne 2b                 // and loop
    mov x0,x3              // position item string
    ldr x1,qAdrsZoneConv   // conversion decimal
    bl conversion10S
    ldr x0,qAdrszMessStringsch
    ldr x1,qAdrsZoneConv
    bl strInsertAtCharInc  // insert result at @ character
    bl affichageMess
    b 100f
3:                         // end search  string not found
    ldr x0,qAdrszMessStringNfound
    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
qAdrtablesPoi1:         .quad tablesPoi1
qAdrszMessStringsch:    .quad szMessStringsch
qAdrszString5:          .quad szString5
qAdrszStringSch:        .quad szStringSch
qAdrszStringSch1:       .quad szStringSch1
qAdrsZoneConv:          .quad sZoneConv
qAdrszMessStringNfound: .quad szMessStringNfound
qAdrszCarriageReturn:   .quad  szCarriageReturn
/************************************/
/* Strings comparaison              */
/************************************/
/* x0 et x1 contains strings addresses */
/* x0 return 0 if equal */
/* return -1 if string x0 < string x1 */
/* return 1  if string x0 > string x1 */
comparString:
    stp x2,lr,[sp,-16]!         // save  registers
    stp x3,x4,[sp,-16]!         // save  registers
    mov x2,#0                   // indice
1:
    ldrb w3,[x0,x2]             // one byte string 1
    ldrb w4,[x1,x2]             // one byte string 2
    cmp w3,w4
    blt 2f                      // less
    bgt 3f                      // greather
    cmp w3,#0                   // 0 final
    beq 4f                      // equal and end
    add x2,x2,#1                //
    b 1b                        // else loop
2:
    mov x0,#-1                  // less
    b 100f
3:
    mov x0,#1                   // greather
    b 100f
4:
    mov x0,#0                   // equal
    b 100f
100:
    ldp x3,x4,[sp],16           // restaur  2 registers
    ldp x2,lr,[sp],16           // restaur  2 registers
    ret                         // return to address lr x30
/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


with javascript_semantics
sequence arithmetic = {1}
integer composite = 0

function get_arithmetic(integer nth)
    integer n = arithmetic[$]+1
    while length(arithmetic)<nth do
        sequence divs = factors(n,1)
        if remainder(sum(divs),length(divs))=0 then
            composite += length(divs)>2
            arithmetic &= n
        end if
        n += 1
    end while
    return arithmetic[nth]
end function

{} = get_arithmetic(100)
printf(1,"The first 100 arithmetic numbers are:\n%s\n",
         {join_by(arithmetic,1,10," ",fmt:="%3d")})
constant fmt = "The %,dth arithmetic number is %,d up to which %,d are composite.\n"
for n in {1e3,1e4,1e5,1e6} do
    integer nth = get_arithmetic(n)
    printf(1,fmt,{n,nth,composite})
end for


def factors(n: int):
    f = set([1, n])
    i = 2
    while True:
        j = n // i
        if j < i:
            break
        if i * j == n:
            f.add(i)
            f.add(j)
        i += 1
    return f

arithmetic_count = 0
composite_count = 0
n = 1
while arithmetic_count <= 1000000:
    f = factors(n)
    if (sum(f)/len(f)).is_integer():
        arithmetic_count += 1
        if len(f) > 2:
            composite_count += 1
        if arithmetic_count <= 100:
            print(f'{n:3d} ', end='')
            if arithmetic_count % 10 == 0:
                print()
        if arithmetic_count in (1000, 10000, 100000, 1000000):
            print(f'\n{arithmetic_count}th arithmetic number is {n}')
            print(f'Number of composite arithmetic numbers <= {n}: {composite_count}')
    n += 1


use Prime::Factor;
use Lingua::EN::Numbers;

my @arithmetic = lazy (1..∞).hyper.grep: { my @div = .&divisors; (@div.sum / [email protected]div).narrow ~~ Int }

say "The first { .Int.&cardinal } arithmetic numbers:\n", @arithmetic[^$_].batch(10)».fmt("%{.chars}d").join: "\n" given 1e2;

for 1e3, 1e4, 1e5, 1e6 {
    say "\nThe { .Int.&ordinal }: { comma @arithmetic[$_-1] }";
    say "Composite arithmetic numbers ≤ { comma @arithmetic[$_-1] }: { comma [email protected][^$_].grep({!.is-prime}) - 1 }";
}


TYPES: tty_int TYPE STANDARD TABLE OF i
                    WITH NON-UNIQUE DEFAULT KEY.

DATA(itab) = VALUE tty_int( ( 1 )
                            ( 2 )
                            ( 3 ) ).

INSERT 4 INTO TABLE itab.
APPEND 5 TO itab.
DELETE itab INDEX 1.

cl_demo_output=>display( itab ).
cl_demo_output=>display( itab[ 2 ] ).


fn divisor_count_and_sum(mut n: u32) -> (u32, u32) {
    let mut divisor_count = 1;
    let mut divisor_sum = 1;
    let mut power = 2;
    while (n & 1) == 0 {
        divisor_count += 1;
        divisor_sum += power;
        power <<= 1;
        n >>= 1;
    }
    let mut p = 3;
    while p * p <= n {
        let mut count = 1;
        let mut sum = 1;
        power = p;
        while n % p == 0 {
            count += 1;
            sum += power;
            power *= p;
            n /= p;
        }
        divisor_count *= count;
        divisor_sum *= sum;
        p += 2;
    }
    if n > 1 {
        divisor_count *= 2;
        divisor_sum *= n + 1;
    }
    (divisor_count, divisor_sum)
}

fn main() {
    let mut arithmetic_count = 0;
    let mut composite_count = 0;
    let mut n = 1;
    while arithmetic_count <= 1000000 {
        let (divisor_count, divisor_sum) = divisor_count_and_sum(n);
        if divisor_sum % divisor_count != 0 {
            n += 1;
            continue;
        }
        arithmetic_count += 1;
        if divisor_count > 2 {
            composite_count += 1;
        }
        if arithmetic_count <= 100 {
            print!("{:3} ", n);
            if arithmetic_count % 10 == 0 {
                println!();
            }
        }
        if arithmetic_count == 1000
            || arithmetic_count == 10000
            || arithmetic_count == 100000
            || arithmetic_count == 1000000
        {
            println!("\n{}th arithmetic number is {}", arithmetic_count, n);
            println!(
                "Number of composite arithmetic numbers <= {}: {}",
                n, composite_count
            );
        }
        n += 1;
    }
}


import "./math" for Int, Nums
import "./fmt" for Fmt
import "./sort" for Find

var arithmetic = [1]
var primes = []
var limit = 1e6
var n = 3
while (arithmetic.count < limit) {
    var divs = Int.divisors(n)
    if (divs.count == 2) {
        primes.add(n)
        arithmetic.add(n)
    } else {
        var mean = Nums.mean(divs)
        if (mean.isInteger) arithmetic.add(n)
    }
    n = n + 1
}
System.print("The first 100 arithmetic numbers are:")
Fmt.tprint("$3d", arithmetic[0..99], 10)

for (x in [1e3, 1e4, 1e5, 1e6]) {
    var last = arithmetic[x-1]
    Fmt.print("\nThe $,dth arithmetic number is: $,d", x, last)
    var pcount = Find.nearest(primes, last) + 1
    if (!Int.isPrime(last)) pcount = pcount - 1
    var comp = x - pcount - 1 // 1 is not composite
    Fmt.print("The count of such numbers <= $,d which are composite is $,d.", last, comp)
}


int N, ArithCnt, CompCnt, Div, DivCnt, Sum, Quot;
[Format(4, 0);
N:= 1;  ArithCnt:= 0;  CompCnt:= 0;
repeat  Div:= 1;  DivCnt:= 0;  Sum:= 0;
        loop    [Quot:= N/Div;
                if Quot < Div then quit;
                if Quot = Div and rem(0) = 0 then \N is a square
                    [Sum:= Sum+Quot;  DivCnt:= DivCnt+1;  quit];
                if rem(0) = 0 then
                    [Sum:= Sum + Div + Quot;
                    DivCnt:= DivCnt+2;
                    ];
                Div:= Div+1;
                ];
        if rem(Sum/DivCnt) = 0 then \N is arithmetic
            [ArithCnt:= ArithCnt+1;
            if ArithCnt <= 100 then
                [RlOut(0, float(N));
                if rem(ArithCnt/20) = 0 then CrLf(0);
                ];
            if DivCnt > 2 then CompCnt:= CompCnt+1;
            case ArithCnt of 1000, 10_000, 100_000, 1_000_000:
                [CrLf(0);
                IntOut(0, N);  ChOut(0, 9\tab\);
                IntOut(0, CompCnt);
                ]
            other;
            ];
        N:= N+1;
until   ArithCnt >= 1_000_000;
]


FUNCTION ConcatArrays(a(), b())
	ta = UBOUND(a)
	tb = UBOUND(b)

	nt = ta + tb

	FOR i = ta + 1 TO nt
		a(i) = b(i - ta)
	NEXT i

	ConcatArrays = nt
END FUNCTION

dimen = 5
DIM a(dimen)
DIM b(dimen)

FOR i = 1 TO dimen
	a(i) = i
	b(i) = i + dimen
NEXT i

nt = ConcatArrays(a(), b())

FOR i = 1 TO nt
	PRINT a(i);
	IF i < nt THEN PRINT ", ";
NEXT i


Dim As Integer First, Second
First = 5: Second = 8

Dim As Integer Array1(1 To First), Array2(1 To Second), ArrayResult(1 To First + Second)

Init Array1(), 2
Print "First array"
ShowArr Array1()
Sleep 2
Print "Second array"
Init Array2(), 5
ShowArr Array2()
Sleep 2
Print "Final array"

ConcatArray Array1(), Array2(), ArrayResult()
ShowArr ArrayResult()
End

Sub Init (A() As Integer, R As Integer)
    Dim Index As Integer
    For Index = 1 To UBound(a)
        A(Index) = Index * R
    Next
End Sub

Sub ShowArr (A() As Integer)
    Dim Index As Integer
    For Index = 1 To UBound(a)
        Print A(Index)
    Next
End Sub

Sub ConcatArray (A() As Integer, B() As Integer, R() As Integer)
    Dim Index As Integer
    For Index = 1 To UBound(a)
        R(Index) = A(Index)
    Next
    For Index = (1) To (UBound(b))
        R(Index + UBound(a)) = B(Index)
    Next
End Sub


;; Create an array and store it in array-example
(assign array-example
        (compress1 'array-example
                   (list '(:header :dimensions (10)
                                   :maximum-length 11))))

;; Set a[5] to 22
(assign array-example
        (aset1 'array-example
               (@ array-example)
               5
               22))

;; Get a[5]
(aref1 'array-example (@ array-example) 5)


> quackery

Welcome to Quackery.

Enter "leave" to leave the shell.

/O> ' [ [ 1 2 ] [ 3 4 ] [ 5 6 ] ]
... ' [ [ 7 8 ] [ 9 0 ] ] join echo
...
[ [ 1 2 ] [ 3 4 ] [ 5 6 ] [ 7 8 ] [ 9 0 ] ]
Stack empty.

/O> leave
...

Goodbye.


PROC Main()
  BYTE i

  ;array storing 4 INT items with initialized values
  ;negative values must be written as 16-bit unsigned numbers
  INT ARRAY a=[3 5 71 65535]

  ;array storing 4 CARD items whithout initialization of values
  CARD ARRAY b(3)

  ;array of BYTE items without allocation,
  ;it may be used as an pointer for another array
  BYTE ARRAY c

  ;array of 1+7 CHAR items or a string
  ;the first item stores length of the string
  CHAR ARRAY s="abcde"

  PrintE("Array with initialized values:")
  FOR i=0 TO 3
  DO
    PrintF("a(%I)=%I ",i,a(i))
  OD
  PutE() PutE()

  PrintE("Array before initialization of items:")
  FOR i=0 TO 3
  DO
    PrintF("b(%I)=%B ",i,b(i))
  OD
  PutE() PutE()

  FOR i=0 TO 3
  DO
    b(i)=100+i
  OD
  PrintE("After initialization:")
  FOR i=0 TO 3
  DO
    PrintF("b(%I)=%B ",i,b(i))
  OD
  PutE() PutE()

  PrintE("Array of chars. The first item stores the length of string:")
  FOR i=0 TO s(0)
  DO
    PrintF("s(%B)='%C ",i,s(i))
  OD
  PutE() PutE()

  PrintE("As the string:")
  PrintF("s=""%S""%E%E",s)

  c=s
  PrintE("Unallocated array as a pointer to another array. In this case c=s:")
  FOR i=0 TO s(0)
  DO
    PrintF("c(%B)=%B ",i,c(i))
  OD
RETURN


my @array1 = 1, 2, 3;
my @array2 = 4, 5, 6;

# If you want to concatenate two array to form a third,
# either use the slip operator "|", to flatten each array.

my @array3 = |@array1, |@array2;
say @array3;

# or just flatten both arrays in one fell swoop

@array3 = flat @array1, @array2;
say @array3;

# On the other hand, if you just want to add the elements
# of the second array to the first, use the .append method.

say @array1.append: @array2;


DEFINT A(1 to 4) = {1, 2, 3, 4}
DEFINT B(1 to 4) = {10, 20, 30, 40}

'Append array B to array A
Redim A(1 to 8) as integer
MEMCPY(varptr(A(5)), varptr(B(1)), Sizeof(integer)*4)


//creates an array of length 10
var array1:Array = new Array(10);
//creates an array with the values 1, 2
var array2:Array = new Array(1,2);
//arrays can also be set using array literals
var array3:Array = ["foo", "bar"];
//to resize an array, modify the length property
array2.length = 3;
//arrays can contain objects of multiple types.
array2[2] = "Hello";
//get a value from an array
trace(array2[2]);
//append a value to an array
array2.push(4);
//get and remove the last element of an array
trace(array2.pop());


procedure Array_Test is

   A, B : array (1..20) of Integer;

   -- Ada array indices may begin at any value, not just 0 or 1
   C : array (-37..20) of integer

   -- Ada arrays may be indexed by enumerated types, which are
   -- discrete non-numeric types
   type Days is (Mon, Tue, Wed, Thu, Fri, Sat, Sun);
   type Activities is (Work, Fish);
   type Daily_Activities is array(Days) of Activities;
   This_Week : Daily_Activities := (Mon..Fri => Work, Others => Fish);

   -- Or any numeric type
   type Fingers is range 1..4; -- exclude thumb
   type Fingers_Extended_Type is array(fingers) of Boolean;
   Fingers_Extended : Fingers_Extended_Type;

   -- Array types may be unconstrained. The variables of the type
   -- must be constrained
   type Arr is array (Integer range <>) of Integer;
   Uninitialized : Arr (1 .. 10);
   Initialized_1 : Arr (1 .. 20) := (others => 1);
   Initialized_2 : Arr := (1 .. 30 => 2);
   Const         : constant Arr := (1 .. 10 => 1, 11 .. 20 => 2, 21 | 22 => 3);
   Centered      : Arr (-50..50) := (0 => 1, Others => 0);

   Result        : Integer
begin

   A := (others => 0);     -- Assign whole array
   B := (1 => 1, 2 => 1, 3 => 2, others => 0);
                           -- Assign whole array, different values
   A (1) := -1;            -- Assign individual element
   A (2..4) := B (1..3);   -- Assign a slice
   A (3..5) := (2, 4, -1); -- Assign a constant slice
   A (3..5) := A (4..6);   -- It is OK to overlap slices when assigned

   Fingers_Extended'First := False; -- Set first element of array
   Fingers_Extended'Last := False;  -- Set last element of array

end Array_Test;


arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
arr3 = [7, 8, 9]
arr4 = arr1 + arr2
see arr4
see nl
arr5 = arr4 + arr3
see arr5


var arr1 = [1,2,3,4]   // initialize with array literal
var arr2 = new [10]   // empty array of 10 elements (each element has value none)
var arr3 = new int [40]  // array of 40 integers
var arr4 = new Object (1,2) [10]   // array of 10 instances of Object

arr1.append (5)   // add to array
var b = 4 in arr1   // check for inclusion
arr1 <<= 2           // remove first 2 elements from array
var arrx = arr1[1:3]   // get slice of array
var s = arr1.size()  // or sizeof(arr1)
delete arr4[2]     // remove an element from an array

var arr5 = arr1 + arr2   // append arrays
var arr6 = arr1 | arr2    // union
var arr7 = arr1 & arr2   // intersection


>> x = [1, 2, 3]
>> y = [4, 5, 6]
// appending matrix 'y' on the right from matrix 'x' is possible if the two matrices have
// the same number of rows:
>> z1 = [x, y]
matrix columns 1 thru 6
           1             2             3             4             5             6
// stacking matrix 'y' below the matrix 'x' is possible if the two matrices have
// the same number of columns:
>> z2  = [x; y]
           1             2             3
           4             5             6
>>


fn main() {
    let a_vec = vec![1, 2, 3, 4, 5];
    let b_vec = vec![6; 5];

    let c_vec = concatenate_arrays(&a_vec, &b_vec);

    println!("{:?} ~ {:?} => {:?}", a_vec, b_vec, c_vec);
}

fn concatenate_arrays<T: Clone>(x: &[T], y: &[T]) -> Vec<T> {
    let mut concat = x.to_vec();
    concat.extend_from_slice(y);

    concat
}


begin
comment arrays - Algol 60;

  procedure static;
  begin
    integer array x[0:4];
    x[0]:=10;
    x[1]:=11;
    x[2]:=12;
    x[3]:=13;
    x[4]:=x[0];
    outstring(1,"static at 4: ");
    outinteger(1,x[4]);
    outstring(1,"\n")
  end static;

  procedure dynamic(n); value n; integer n;
  begin
    integer array x[0:n-1];
    x[0]:=10;
    x[1]:=11;
    x[2]:=12;
    x[3]:=13;
    x[4]:=x[0];
    outstring(1,"dynamic at 4: ");
    outinteger(1,x[4]);
    outstring(1,"\n")
  end dynamic;

  static;
  dynamic(5)

end arrays


PROC array_test = VOID:
(
  [1:20]INT a;
  a := others;                           # assign whole array #
  a[1] := -1;                            # assign individual element #
  a[3:5] := (2, 4, -1);                  # assign a slice #
  [1:3]INT slice = a[3:5];               # copy a slice #

  REF []INT rslice = a[3:5];             # create a reference to a slice #
  print((LWB rslice, UPB slice));        # query the bounds of the slice #
  rslice := (2, 4, -1);                  # assign to the slice, modifying original array #

  [1:3, 1:3]INT matrix;                  # create a two dimensional array #
  REF []INT hvector = matrix[2,];        # create a reference to a row #
  REF []INT vvector = matrix[,2];        # create a reference to a column #
  REF [,]INT block = matrix[1:2, 1:2];   # create a reference to an area of the array #

  FLEX []CHAR string := "Hello, world!"; # create an array with variable bounds #
  string := "shorter"                    # flexible arrays automatically resize themselves on assignment #
)


variable a = [1, 2, 3];
variable b = [4, 5, 6], c;


val arr1 = Array( 1, 2, 3 )
val arr2 = Array( 4, 5, 6 )
val arr3 = Array( 7, 8, 9 )

arr1 ++ arr2 ++ arr3
//or:
Array concat ( arr1, arr2, arr3 )
// res0: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9)


begin
    % declare an array %
    integer array a ( 1 :: 10 );
    % set the values %
    for i := 1 until 10 do a( i ) := i;
    % change the 3rd element %
    a( 3 ) := 27;
    % display the 4th element %
    write( a( 4 ) ); % would show 4 %
    % arrays with sizes not known at compile-time must be created in inner-blocks or procedures %
    begin
        integer array b ( a( 3 ) - 2 :: a( 3 ) ); % b has bounds 25 :: 27 %
        for i := a( 3 ) - 2 until a( 3 ) do b( i ) := i
    end
    % arrays cannot be part of records and cannot be returned by procecures though they can be passed %
    % as parameters to procedures                                                                     %
    % multi-dimension arrays are supported                                                            %
end.


; in r5rs, there is append for lists, but we'll need to define vector-append
(define (vector-append . arg) (list->vector (apply append (map vector->list arg))))

(vector-append #(1 2 3 4) #(5 6 7) #(8 9 10))
; #(1 2 3 4 5 6 7 8 9 10)


$ include "seed7_05.s7i";

var array integer: a is [] (1, 2, 3, 4);
var array integer: b is [] (5, 6, 7, 8);
var array integer: c is [] (9, 10);

const proc: main is func
  local
    var integer: number is 0;
  begin
    c := a & b;
    for number range c do
      write(number <& " ");
    end for;
    writeln;
  end func;


put (1, 2, 3) into list1
put (4, 5, 6) into list2
put list1 &&& list2 into list3
put list3


DEF ai[100] : ARRAY OF CHAR, -> static
    da: PTR TO CHAR,
    la: PTR TO CHAR

PROC main()
  da := New(100)
  -> or
  NEW la[100]
  IF da <> NIL
    ai[0] := da[0]    -> first is 0
    ai[99] := da[99]  -> last is "size"-1
    Dispose(da)
  ENDIF
  -> using NEW, we must specify the size even when
  -> "deallocating" the array
  IF la <> NIL THEN END la[100]
ENDPROC


/ Create an immutable sequence (array)
arr: <1;2;3>

/ Get the head an tail part
h: head[arr]
t: tail[arr]

/ Get everything except the last element and the last element
nl: first[arr]
l: last[arr]

/ Get the nth element (index origin = 0)
nth:arr[n]


Integer[] array = new Integer[10]; // optionally, append a braced list of Integers like "{1, 2, 3}"
array[0] = 42;
System.debug(array[0]); // Prints 42


BEGIN  ! Concatenate arrays - of REAL, here;

    CLASS REAL_ARRAY(N); INTEGER N;
    BEGIN
        REAL ARRAY DATA(1:N);

        ! Return a new REAL_ARRAY containing
        ! the values from this REAL_ARRAY
        ! followed by the values from other;
        REF(REAL_ARRAY) PROCEDURE CONCAT(other);
            REF(REAL_ARRAY) other;
        BEGIN
            REF(REAL_ARRAY) C;
            INTEGER I;

            C :- NEW REAL_ARRAY(N + other.N);

            FOR I := 1 STEP 1 UNTIL N DO
                C.DATA(I) := DATA(I);

            FOR I := 1 STEP 1 UNTIL other.N DO
                C.DATA(N + I) := other.DATA(I);

            CONCAT :- C;
        END;

        ! Fill DATA;
        REF(REAL_ARRAY) PROCEDURE linearFill(start, stride);
            REAL start, stride;
        BEGIN
            linearFillFrom(DATA, 1, N, start, stride);
            linearFill :- this REAL_ARRAY
        END;

        PROCEDURE out(sink); REF(printfile) sink;
        BEGIN
            INTEGER i;
            FOR i := 1 STEP 1 UNTIL N DO
                sink.OUTFIX(DATA(i), 2, 7);
            sink.OUTIMAGE;
        END;
    END REAL_ARRAY;

    ! "The problem" is not array as an input parameter:
    !  I don't know how to
    ! "pass a new ARRAY out of a PROCEDURE";
    REF(REAL_ARRAY) PROCEDURE concatenate(a, b);
        REAL ARRAY a, b;
    BEGIN
        INTEGER i, a_, N, b_, M;
        REF(REAL_ARRAY) c;
        a_ := LOWERBOUND(a, 1) - 1;
        N := UPPERBOUND(a, 1) - a_;
        b_ := LOWERBOUND(a, 1) - 1;
        M := UPPERBOUND(b, 1) - b_;
        c :- NEW REAL_ARRAY(N + M);

        FOR i := 1 STEP 1 UNTIL N DO
            c.DATA(i) := a(a_+i);
        ! for readability, don't
        !  reduce one index expression to a variable
        FOR i := 1 STEP 1 UNTIL M DO
            c.DATA(N + i) := b(b_+i);

        concatenate :- c;
    END concatenate REAL ARRAYs;

    ! two more convenience PROCEDUREs;
    PROCEDURE linearFillFrom(a, from, inclusive, start, stride);
            REAL ARRAY a; ! passed by reference;
            INTEGER from, inclusive;
            REAL start, stride;
    BEGIN
        INTEGER i;
        FOR i := from STEP 1 UNTIL inclusive DO
            a(i) := start + stride * (i - from)
    END;
    PROCEDURE linearFill(a, start, stride);
            REAL ARRAY a;
            REAL start, stride;
        linearFillFrom(a, LOWERBOUND(a, 1), UPPERBOUND(a, 1),
                       start, stride);

    REF(REAL_ARRAY) X;
    REAL ARRAY u(1:3), v(1:4);
    linearFill(u, 3, 7);
    linearFill(v, 0, 5);
    concatenate(u, v).out(SYSOUT);

    X :- NEW REAL_ARRAY(3).linearFill(1, 2);
    X.out(SYSOUT);
    X.CONCAT(NEW REAL_ARRAY(4)
                .linearFill(-1, -3)).out(SYSOUT);
END.


*       # Concatenate 2 arrays (vectors)
        define('cat(a1,a2)i,j') :(cat_end)
cat     cat = array(prototype(a1) + prototype(a2))
cat1    i = i + 1; cat<i> = a1<i> :s(cat1)
cat2    j = j + 1; cat<i - 1 + j> = a2<j> :s(cat2)f(return)
cat_end

*       # Fill arrays
        str1 = '1 2 3 4 5'; arr1 = array(5)
loop    i = i + 1; str1 len(p) span('0123456789') . arr1<i> @p :s(loop)
        str2 = '6 7 8 9 10'; arr2 = array(5)
loop2   j = j + 1; str2 len(q) span('0123456789') . arr2<j> @q :s(loop2)

*       # Test and display
        arr3 = cat(arr1,arr2)
loop3   k = k + 1; str3 = str3 arr3<k> ' ' :s(loop3)
        output = str1
        output = str2
        output = str3
end


// Creating an array as [ 23, 12, 2, 5345, 23 ]
// with name "space"

   ( space , 23; 12; 2; 5345; 23 )

// Getting the size of an array:

   "Size of array is | @space? |"

// Appending array with 54

   ( space[ @space? ] , 54 )

// Something else fun about arrays in Arendelle
// for example when you have one like this:
//
//    space -> [ 23, 34, 3, 6345 ]
//
// If you do this on the space:

   ( space[ 7 ] , 10 )

// Arendelle will make the size of array into
// 8 by appending zeros and then it will set
// index 7 to 10 and result will be:
//
//    space -> [ 23, 34, 3, 6345, 0, 0, 0, 10 ]

// To remove the array you can use done keyword:

   ( space  , done )


let array1 = [1,2,3]
let array2 = [4,5,6]
let array3 = array1 + array2


use std, array

(:::::::::::::::::
 : Static arrays :
 :::::::::::::::::)
let the array of 2 text aabbArray be Cdata{"aa";"bb"}
let raw array of real :my array: = Cdata {1.0 ; 2.0 ; 3.0} (: auto sized :)
let another_array be an array of 256 byte (: not initialised :)
let (raw array of (array of 3 real)) foobar = Cdata {
  {1.0; 2.0; 0.0}
  {5.0; 1.0; 3.0}
}

(: macro to get size of static arrays :)
=: <array>.length := -> nat {size of array / (size of array[0])}
printf "%lu, %lu\n" foobar.length (another_array.length) (: 2, 256 :)

(: access :)
another_array[255] = '&'
printf "`%c'\n" another_array[255]

(::::::::::::::::::
 : Dynamic arrays :
 ::::::::::::::::::)
let DynArray = new array of 5 int
DynArray[0] = -42
DynArray = (realloc DynArray (6 * size of DynArray[0])) as (type of DynArray)
DynArray[5] = 243
prints DynArray[0] DynArray[5]
del DynArray


/* ARM assembly Raspberry PI  */
/*  program areaString.s   */

/* Constantes    */
.equ STDOUT, 1     @ Linux output console
.equ EXIT,   1     @ Linux syscall
.equ WRITE,  4     @ Linux syscall
/* Initialized data */
.data
szMessStringsch: .ascii "The string is at item : "
sZoneconv:		 .fill 12,1,' '
szCarriageReturn:  .asciz "\n"
szMessStringNfound: .asciz "The string is not found in this area.\n"

/* areas strings  */
szString1:  .asciz "Apples"
szString2:  .asciz "Oranges"
szString3:  .asciz "Pommes"
szString4:  .asciz "Raisins"
szString5:  .asciz "Abricots"

/* pointer items area 1*/
tablesPoi1:
pt1_1:	    .int szString1
pt1_2:	    .int szString2
pt1_3:	    .int szString3
pt1_4:	    .int szString4
ptVoid_1: .int 0
ptVoid_2: .int 0
ptVoid_3: .int 0
ptVoid_4: .int 0
ptVoid_5: .int 0

szStringSch:	.asciz "Raisins"
szStringSch1:	.asciz "Ananas"

/* UnInitialized data */
.bss

/*  code section */
.text
.global main
main:                /* entry of program  */
    push {fp,lr}    /* saves 2 registers */

    @@@@@@@@@@@@@@@@@@@@@@@@
    @ add string 5 to area
   @@@@@@@@@@@@@@@@@@@@@@@@
    ldr r1,iAdrtablesPoi1  @ begin pointer area 1
    mov r0,#0    @ counter
1:   @ search first void pointer
    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

    @ store pointer string 5 in area  at position r0
    ldr r2,iAdrszString5  @ address string 5
    str r2,[r1,r0,lsl #2]    @ store address

    @@@@@@@@@@@@@@@@@@@@@@@@
    @ display string at item 3
    @@@@@@@@@@@@@@@@@@@@@@@@
    mov r2,#2        @ pointers begin in position 0
    ldr r1,iAdrtablesPoi1  @ begin pointer area 1
    ldr r0,[r1,r2,lsl #2]
    bl affichageMess
    ldr r0,iAdrszCarriageReturn
    bl affichageMess

    @@@@@@@@@@@@@@@@@@@@@@@@
    @ search string in area
    @@@@@@@@@@@@@@@@@@@@@@@@
    ldr r1,iAdrszStringSch
    //ldr r1,iAdrszStringSch1  @ uncomment for other search : not found !!
    ldr r2,iAdrtablesPoi1  @ begin pointer area 1
    mov r3,#0
2:   @ search
    ldr r0,[r2,r3,lsl #2]    @ read string pointer address item r0 (4 bytes by pointer)
    cmp r0,#0                @ is null ?
    beq 3f        @ end search
    bl comparaison
    cmp r0,#0                @ string = ?
    addne r3,#1             @ no increment counter
    bne 2b                  @ and loop
    mov r0,r3             @ position item string
    ldr r1,iAdrsZoneconv   @ conversion decimal
    bl conversion10S
    ldr r0,iAdrszMessStringsch
    bl affichageMess
    b 100f
3:   @ end search  string not found
    ldr r0,iAdrszMessStringNfound
    bl affichageMess

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
iAdrtablesPoi1:		.int tablesPoi1
iAdrszMessStringsch:   .int szMessStringsch
iAdrszString5:		.int szString5
iAdrszStringSch:	.int szStringSch
iAdrszStringSch1:   .int szStringSch1
iAdrsZoneconv:       .int sZoneconv
iAdrszMessStringNfound:  .int szMessStringNfound
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


; empty  array
arrA: []

; array with initial values
arrB: ["one" "two" "three"]

; adding an element to an existing array
arrB: arrB ++ "four"
print arrB

; another way to add an element
append 'arrB "five"
print arrB

; retrieve an element at some index
print arrB\1


# create two streams (the ursa equivalent of arrays)
# a contains the numbers 1-10, b contains 11-20
decl int<> a b
decl int i
for (set i 1) (< i 11) (inc i)
        append i a
end for
for (set i 11) (< i 21) (inc i)
        append i b
end for

# append the values in b to a
append b a

# output a to the console
out a endl console


int[] array_concat(int[]a,int[]b){
	int[] c = new int[a.length + b.length];
	Memory.copy(c, a, a.length * sizeof(int));
	Memory.copy(&c[a.length], b, b.length * sizeof(int));
	return c;
}
void main(){
	int[] a = {1,2,3,4,5};
	int[] b = {6,7,8};
	int[] c = array_concat(a,b);
	foreach(int i in c){
		stdout.printf("%d\n",i);
	}
}


myArray := Object() ; could use JSON-syntax sugar like {key: value}
myArray[1] := "foo"
myArray[2] := "bar"
MsgBox % myArray[2]

; Push a value onto the array
myArray.Insert("baz")


Option Explicit

Sub MainConcat_Array()
Dim Aray_1() As Variant, Aray_2() As Variant
Dim Result() As Variant

    Aray_1 = Array(1, 2, 3, 4, 5, #11/24/2017#, "azerty")
    Aray_2 = Array("A", "B", "C", 18, "End")
    Result = Concat_Array(Aray_1, Aray_2)
    Debug.Print "With Array 1 : " & Join(Aray_1, ", ")
    Debug.Print "And Array 2 : " & Join(Aray_2, ", ")
    Debug.Print "The result is Array 3 : " & Join(Result, ", ")
End Sub

Function Concat_Array(A1() As Variant, A2() As Variant) As Variant()
Dim TmpA1() As Variant, N As Long, i As Long

    N = UBound(A1) + 1
    TmpA1 = A1
    ReDim Preserve TmpA1(N + UBound(A2))
    For i = N To UBound(TmpA1)
        TmpA1(i) = A2(i - N)
    Next
    Concat_Array = TmpA1
End Function


Function ArrayConcat(arr1, arr2)
    ReDim ret(UBound(arr1) + UBound(arr2) + 1)
    For i = 0 To UBound(arr1)
        ret(i) = arr1(i)
    Next
    offset = Ubound(arr1) + 1
    For i = 0 To UBound(arr2)
        ret(i + offset) = arr2(i)
    Next
    ArrayConcat = ret
End Function

arr1 = array(10,20,30)
arr2 = array(40,50,60)
WScript.Echo "arr1 = array(" & Join(arr1,", ") & ")"
WScript.Echo "arr2 = array(" & Join(arr2,", ") & ")"
arr3 = ArrayConcat(arr1, arr2)
WScript.Echo "arr1 + arr2 = array(" & Join(arr3,", ") & ")"


#include <Array.au3> ;Include extended Array functions (_ArrayDisplay)

Local $aInputs[1] ;Create the Array with just 1 element

While True ;Endless loop
	$aInputs[UBound($aInputs) - 1] = InputBox("Array", "Add one value") ;Save user input to the last element of the Array
	If $aInputs[UBound($aInputs) - 1] = "" Then ;If an empty string is entered, then...
		ReDim $aInputs[UBound($aInputs) - 1] ;...remove them from the Array and...
		ExitLoop ;... exit the loop!
	EndIf
	ReDim $aInputs[UBound($aInputs) + 1] ;Add an empty element to the Array
WEnd

_ArrayDisplay($aInputs) ;Display the Array


    Dim iArray1() As Integer = {1, 2, 3}
    Dim iArray2() As Integer = {4, 5, 6}
    Dim iArray3() As Integer = Nothing

    iArray3 = iArray1.Concat(iArray2).ToArray


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

// starts here
pub fn main() {
    mut arr1 := [1,2,3,4]
    arr2 := [5,6,7,8]

    arr1 << arr2
    println(arr1)
}


var arr1 = [1,2,3]
var arr2 = [4,5,6]
System.print(arr1 + arr2)


sub arrayConcatenation(a(), b())
	local ta, tb, nt, i

	ta = arraysize(a(), 1)
	tb = arraysize(b(), 1)

	nt = ta + tb

	redim a(nt)

	for i = ta + 1 to nt
		a(i) = b(i - ta)
	next i

	return nt
end sub

//===============================

SIZE = 5

dim a(SIZE)
dim b(SIZE)

for i = 1 to SIZE
	a(i) = i
	b(i) = i + SIZE
next i

nt = arrayConcatenation(a(), b())

for i = 1 to nt
	print a(i);
	if i < nt print ", ";
next i
print


BEGIN {
  # to make an array, assign elements to it
  array[1] = "first"
  array[2] = "second"
  array[3] = "third"
  alen = 3  # want the length? store in separate variable

  # or split a string
  plen = split("2 3 5 7 11 13 17 19 23 29", primes)
  clen = split("Ottawa;Washington DC;Mexico City", cities, ";")

  # retrieve an element
  print "The 6th prime number is " primes[6]

  # push an element
  cities[clen += 1] = "New York"

  dump("An array", array, alen)
  dump("Some primes", primes, plen)
  dump("A list of cities", cities, clen)
}

function dump(what, array, len,    i) {
  print what;

  # iterate an array in order
  for (i = 1; i <= len; i++) {
    print "  " i ": " array[i]
  }
}


	org $8000

	ld hl,TestArray1		; pointer to first array
	ld de,ArrayRam			; pointer to ram area
	ld bc,6			        ; size of first array
	ldir

	; DE is already adjusted past the last entry
	;	of the first array

	ld hl,TestArray2		; pointer to second array
	ld bc,4				; size of second array
	ldir

	call Monitor_MemDump
	db 32				; hexdump 32 bytes (only the bytes from the arrays will be shown in the output for clarity)
	dw ArrayRam			; start dumping from ArrayRam

	ret				; return to basic

ArrayRam:
	ds 24,0	                        ;24 bytes of ram initialized to zero

	org $9000
TestArray2:
	byte $23,$45,$67,$89
	; just to prove that this doesn't rely on the arrays
	;	being "already concatenated" I've stored them
	;	in the reverse order.
TestArray1:
	byte $aa,$bb,$cc,$dd,$ee,$ff


1→{L₁}
2→{L₁+1}
3→{L₁+2}
4→{L₁+3}
Disp {L₁}►Dec,i
Disp {L₁+1}►Dec,i
Disp {L₁+2}►Dec,i
Disp {L₁+3}►Dec,i


module Main;
import
	System.Collections.ArrayList as Array,
	System.Console as Console;

type
	Vector =  array {math} * of integer;

procedure Concat(x,y: Vector): Vector;
var
	i,k: integer;
	res: Vector;
begin
	res := new Vector(len(x) + len(y));
	k := 0;
	for i := 0 to len(x) - 1 do
		res[k] := x[i];inc(k)
	end;
	for i := 0 to len(y) - 1 do
		res[k] := y[i];inc(k)
	end;
	return res
end Concat;

procedure Concat2(x,y: Array): Array;
var
	i: integer;
	res: Array;
begin
	res := new Array(x.Count + y.Count);
	for i := 0 to x.Count - 1 do
		res.Add(x[i]);
	end;
	for i := 0 to y.Count - 1 do
		res.Add(y[i]);
	end;
	return res
end Concat2;

procedure WriteVec(x: Vector);
var
	i: integer;
begin
	for i := 0 to len(x) - 1 do;
		write(x[i]:3)
	end;
	writeln;
end WriteVec;

procedure WriteAry(x: Array);
var
	i: integer;
begin
	for i := 0 to x.Count - 1 do;
		Console.Write("{0,3}",x[i])
	end;
	writeln;
end WriteAry;

var
	a,b: Vector;
	x,y: Array;
begin
	a := [1,2,3,4];
	b := [6,7,8,9];
	WriteVec(Concat(a,b));

	x := new Array(4);
	y := new Array(4);
	x.Add(2);x.Add(4);x.Add(6);x.Add(8);
	y.Add(3);y.Add(5);y.Add(9);y.Add(11);

	WriteAry(Concat2(x,y));
end Main.


DATA "January", "February", "March", "April", "May", "June", "July"
DATA "August", "September", "October", "November", "December"

LOCAL dat$[11]
FOR i = 0 TO 11
    READ dat$[i]
    PRINT dat$[i]
NEXT


10 LET x=10
20 LET y=20
30 DIM a(x)
40 DIM b(y)
50 DIM c(x+y)
60 FOR i=1 TO x
70 LET c(i)=a(i)
80 NEXT i
90 FOR i=1 TO y
100 LET c(x+i)=b(i)
110 NEXT i
120 FOR i=1 TO x+y
130 PRINT c(i);", ";
140 NEXT i


 OPTION BASE 1
 DIM myArray(100) AS INTEGER


# numeric array
dim numbers(10)
for t = 0 to 9
  numbers[t] = t + 1
next t

# string array
dim words$(10)
# assigning an array with a list
words$ = {"one","two","three","four","five","six","seven","eight","nine","ten"}

gosub display

# resize arrays (always preserves values if larger)
redim numbers(11)
redim words$(11)
numbers[10] = 11
words$[10] = "eleven"
gosub display

end

display:
# display arrays
# using ? to get size of array
for t = 0 to numbers[?]-1
  print numbers[t] + "=" + words$[t]
next t
return


::arrays.cmd
@echo off
setlocal ENABLEDELAYEDEXPANSION
set array.1=1
set array.2=2
set array.3=3
set array.4=4
for /L %%i in (1,1,4) do call :showit array.%%i !array.%%i!
set c=-27
call :mkarray marry 5 6 7 8
for /L %%i in (-27,1,-24) do call :showit "marry^&%%i" !marry^&%%i!
endlocal
goto :eof

:mkarray
set %1^&%c%=%2
set /a c += 1
shift /2
if "%2" neq "" goto :mkarray
goto :eof

:showit
echo %1 = %2
goto :eof


      REM Declare arrays, dimension is maximum index:
      DIM array(6), array%(6), array$(6)

      REM Entire arrays may be assigned in one statement:
      array() = 0.1, 1.2, 2.3, 3.4, 4.5, 5.6, 6.7
      array%() = 0, 1, 2, 3, 4, 5, 6
      array$() = "Zero", "One", "Two", "Three", "Four", "Five", "Six"

      REM Or individual elements may be assigned:
      array(2) = PI
      array%(3) = RND
      array$(4) = "Hello world!"

      REM Print out sample array elements:
      PRINT array(2)  TAB(16) array(3)  TAB(32) array(4)
      PRINT array%(2) TAB(16) array%(3) TAB(32) array%(4)
      PRINT array$(2) TAB(16) array$(3) TAB(32) array$(4)


/* Put the value 42 into array g at index 3 */
g[3] = 42
/* Look at some other elements in g */
g[2]
0
g[4342]
0
/* Look at the elements of another array */
a[543]
0
/* Array names don't conflict with names of ordinary (scalar) identifiers */
g
0
g = 123
g
123
g[3]
42


% Define an array(containing the numbers 1-3) named arr in the group $
in $ let arr hold 1 2 3

% Replace the value at index 0 in array to "Index 0"
set $arr index 0 to "Index 0"

% Will display "Index 0"
display $arr index 0

% There is no automatic garbage collection
delete $arr


myArray as (int) = (1, 2, 3) // Size based on initialization
fixedArray as (int) = array(int, 1) // Given size(1 in this case)

myArray[0] = 10

myArray = myArray + fixedArray // Append arrays

print myArray[0]


# Stranding:
arr ← 1‿2‿'a'‿+‿5
# General List Syntax:
arr1 ← ⟨1,2,'a',+,5⟩
•Show arr ≡ arr1 # both arrays are the same.
•Show arr
•Show arr1

# Taking nth element(⊑):
•Show 3⊑arr

# Modifying the array(↩):
arr ↩ "hello"⌾(4⊸⊑) arr


( tbl$(mytable,100)
& 5:?(30$mytable)
& 9:?(31$mytable)
& out$(!(30$mytable))
& out$(!(-169$mytable))      { -169 mod 100 == 31 }
& out$!mytable               { still index 31 }
& tbl$(mytable,0)
& (!mytable & out$"mytable still exists"
  | out$"mytable is gone"
  )
);


===========[
ARRAY DATA STRUCTURE

AUTHOR: Keith Stellyes
WRITTEN: June 2016

This is a zero-based indexing array data structure, it assumes the following
precondition:

>INDEX<|NULL|VALUE|NULL|VALUE|NULL|VALUE|NULL

(Where >< mark pointer position, and | separates addresses)

It relies heavily on [>] and [<] both of which are idioms for
finding the next left/right null

HOW INDEXING WORKS:
It runs a loop _index_ number of times, setting that many nulls
to a positive, so it can be skipped by the mentioned idioms.
Basically, it places that many "milestones".

EXAMPLE:
If we seek index 2, and our array is {1 , 2 , 3 , 4 , 5}

FINDING INDEX 2:
   (loop to find next null, set to positive, as a milestone
   decrement index)

index
  2  |0|1|0|2|0|3|0|4|0|5|0
  1  |0|1|1|2|0|3|0|4|0|5|0
  0  |0|1|1|2|1|3|0|4|0|5|0

===========]

=======UNIT TEST=======
 SET ARRAY {48 49 50}
>>++++++++++++++++++++++++++++++++++++++++++++++++>>
+++++++++++++++++++++++++++++++++++++++++++++++++>>
++++++++++++++++++++++++++++++++++++++++++++++++++
<<<<<<++ Move back to index and set it to 2
=======================

===RETRIEVE ELEMENT AT INDEX===

=ACCESS INDEX=
[>>[>]+[<]<-] loop that sets a null to a positive for each iteration
              First it moves the pointer from index to first value
               Then it uses a simple loop that finds the next null
              it sets the null to a positive (1 in this case)
               Then it uses that same loop reversed to find the first
                 null which will always be one right of our index
                 so we decrement our index
               Finally we decrement pointer from the null byte to our
              index and decrement it

>>            Move pointer to the first value otherwise we can't loop

[>]<          This will find the next right null which will always be right
              of the desired value; then go one left

.             Output the value (In the unit test this print "2"

[<[-]<]       Reset array

===ASSIGN VALUE AT INDEX===

STILL NEED TO ADJUST UNIT TESTS

NEWVALUE|>INDEX<|NULL|VALUE etc

[>>[>]+[<]<-] Like above logic except it empties the value and doesn't reset
>>[>]<[-]

[<]<          Move pointer to desired value note that where the index was stored
              is null because of the above loop

[->>[>]+[<]<] If NEWVALUE is GREATER than 0 then decrement it & then find the
              newly emptied cell and increment it

[>>[>]<+[<]<<-] Move pointer to first value find right null move pointer left
                then increment where we want our NEWVALUE to be stored then
                return back by finding leftmost null then decrementing pointer
                twice then decrement our NEWVALUE cell


int myArray2[10] = { 1, 2, 0 }; /* the rest of elements get the value 0 */
float myFloats[] ={1.2, 2.5, 3.333, 4.92, 11.2, 22.0 }; /* automatically sizes */


#include <array>
#include <vector>

// These headers are only needed for the demonstration
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>

// This is a template function that works for any array-like object
template <typename Array>
void demonstrate(Array& array)
{
  // Array element access
  array[2] = "Three";  // Fast, but unsafe - if the index is out of bounds you
                       // get undefined behaviour
  array.at(1) = "Two"; // *Slightly* less fast, but safe - if the index is out
                       // of bounds, an exception is thrown

  // Arrays can be used with standard algorithms
  std::reverse(begin(array), end(array));
  std::for_each(begin(array), end(array),
    [](typename Array::value_type const& element) // in C++14, you can just use auto
    {
      std::cout << element << ' ';
    });

  std::cout << '\n';
}

int main()
{
  // Compile-time sized fixed-size array
  auto fixed_size_array = std::array<std::string, 3>{ "One", "Four", "Eight" };
  // If you do not supply enough elements, the remainder are default-initialized

  // Dynamic array
  auto dynamic_array = std::vector<std::string>{ "One", "Four" };
  dynamic_array.push_back("Eight"); // Dynamically grows to accept new element

  // All types of arrays can be used more or less interchangeably
  demonstrate(fixed_size_array);
  demonstrate(dynamic_array);
}


import ceylon.collection {

	ArrayList
}

shared void run() {

	// you can get an array from the Array.ofSize named constructor
	value array = Array.ofSize(10, "hello");
	value a = array[3];
	print(a);
	array[4] = "goodbye";
	print(array);

	// for a dynamic list import ceylon.collection in your module.ceylon file
	value list = ArrayList<String>();
	list.push("hello");
	list.push("hello again");
	print(list);
}


int array[0]; // instantiate int array
array << 1; // append item
array << 2 << 3; // append items
4 => array[3]; // assign element(4) to index(3)
5 => array.size; // resize
array.clear(); // clear elements
<<<array.size()>>>; // print in cosole array size
[1,2,3,4,5,6,7] @=> array;
array.popBack(); // Pop last element


array :: {String}
array = {"Hello", "World"}


   // Declare and initialize two-dimensional array
   Local arr1 := { { "NITEM","N",10,0 }, { "CONTENT","C",60,0} }
   // Create an empty array
   Local arr2 := {}
   // Declare three-dimensional array
   Local arr3[2,100,3]
   // Create an array
   Local arr4 := Array(50)

   // Array can be dynamically resized:
   arr4 := ASize( arr4, 80 )


;clojure is a language built with immutable/persistent data structures. there is no concept of changing what a vector/list
;is, instead clojure creates a new array with an added value using (conj...)
;in the example below the my-list does not change.

user=> (def my-list (list 1 2 3 4 5))

user=> my-list
(1 2 3 4 5)

user=> (first my-list)
1

user=> (nth my-list 3)
4

user=> (conj my-list 100) ;adding to a list always adds to the head of the list
(100 1 2 3 4 5)

user=> my-list ;it is impossible to change the list pointed to by my-list
(1 2 3 4 5)

user=> (def my-new-list (conj my-list 100))

user=> my-new-list
(100 1 2 3 4 5)

user=> (cons 200 my-new-list) ;(cons makes a new list, (conj will make a new object of the same type as the one it is given
(200 100 1 2 3 4 5)

user=> (def my-vec [1 2 3 4 5 6])

user=> (conj my-vec 300) ;adding to a vector always adds to the end of the vector
[1 2 3 4 5 6 300]


       IDENTIFICATION DIVISION.
       PROGRAM-ID. arrays.

       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  fixed-length-table.
           03  fixed-table-elt      PIC X OCCURS 5 TIMES.

       01  table-length             PIC 9(5) VALUE 1.
       01  variable-length-table.
           03  variable-table-elt   PIC X OCCURS 1 TO 5 TIMES
               DEPENDING ON table-length.

       01  initial-value-area.
           03  initial-values.
               05  FILLER           PIC X(10) VALUE "One".
               05  FILLER           PIC X(10) VALUE "Two".
               05  FILLER           PIC X(10) VALUE "Three".
           03 initial-value-table REDEFINES initial-values.
              05  initial-table-elt PIC X(10) OCCURS 3 TIMES.

       01  indexed-table.
           03  indexed-elt          PIC X OCCURS 5 TIMES
               INDEXED BY table-index.

       PROCEDURE DIVISION.
           *> Assigning the contents of an entire table.
           MOVE "12345" TO fixed-length-table

           *>  Indexing an array (using an index)
           MOVE 1 TO table-index
           MOVE "1" TO indexed-elt (table-index)

           *> Pushing a value into a variable-length table.
           ADD 1 TO table-length
           MOVE "1" TO variable-table-elt (2)

           GOBACK
           .


array1 = []
array1[0] = "Dillenidae"
array1[1] = "animus"
array1[2] = "Kona"
alert "Elements of array1: " + array1 # Dillenidae,animus,Kona

array2 = ["Cepphus", "excreta", "Gansu"]
alert "Value of array2[1]: " + array2[1] # excreta


(let ((array (make-array 10)))
  (setf (aref array 0) 1
          (aref array 1) 3)
  (print array))


MODULE TestArray;
(* Implemented in BlackBox Component Builder *)

	IMPORT Out;

	(* Static array *)

	PROCEDURE DoOneDim*;
		CONST M = 5;
		VAR a: ARRAY M OF INTEGER;
	BEGIN
		a[0] := 100; (* set first element's value of array a to 100 *)
		a[M-1] := -100; (* set M-th element's value of array a to -100 *)
		Out.Int(a[0], 0); Out.Ln;
		Out.Int(a[M-1], 0); Out.Ln;
	END DoOneDim;

	PROCEDURE DoTwoDim*;
		VAR b: ARRAY 5, 4 OF INTEGER;
	BEGIN
		b[1, 2] := 100; (* second row, third column element *)
		b[4, 3] := -100; (* fifth row, fourth column element *)
		Out.Int(b[1, 2], 0); Out.Ln;
		Out.Int(b[4, 3], 0); Out.Ln;
	END DoTwoDim;

END TestArray.


load:   LDA  ary
        ADD  sum
        STA  sum

        LDA  load
        ADD  one
        STA  load

        SUB  end
        BRZ  done

        JMP  load

done:   LDA  sum
        STP

one:         1
end:    LDA  ary+10

sum:         0

ary:         1
             2
             3
             4
             5
             6
             7
             8
             9
             10


# create an array with one object in it
a = ["foo"]

# Empty array literals always need a type specification:
[] of Int32 # => Array(Int32).new

# The array's generic type argument T is inferred from the types of the elements inside the literal. When all elements of the array have the same type, T equals to that. Otherwise it will be a union of all element types.
[1, 2, 3]         # => Array(Int32)
[1, "hello", 'x'] # => Array(Int32 | String | Char)

# An explicit type can be specified by immediately following the closing bracket with of and a type, each separated by whitespace. This overwrites the inferred type and can be used for example to create an array that holds only some types initially but can accept other types later.
array_of_numbers = [1, 2, 3] of Float64 | Int32 # => Array(Float64 | Int32)
array_of_numbers << 0.5                         # => [1, 2, 3, 0.5]

array_of_int_or_string = [1, 2, 3] of Int32 | String # => Array(Int32 | String)
array_of_int_or_string << "foo"                      # => [1, 2, 3, "foo"]

# percent array literals
%w(one two three) # => ["one", "two", "three"]
%i(one two three) # => [:one, :two, :three]


// All D arrays are capable of bounds checks.

import std.stdio, core.stdc.stdlib;
import std.container: Array;

void main() {
    // GC-managed heap allocated dynamic array:
    auto array1 = new int[1];
    array1[0] = 1;
    array1 ~= 3; // append a second item
    // array1[10] = 4; // run-time error
    writeln("A) Element 0: ", array1[0]);
    writeln("A) Element 1: ", array1[1]);

    // Stack-allocated fixed-size array:
    int[5] array2;
    array2[0] = 1;
    array2[1] = 3;
    // array2[2] = 4; // compile-time error
    writeln("B) Element 0: ", array2[0]);
    writeln("B) Element 1: ", array2[1]);

    // Stack-allocated dynamic fixed-sized array,
    // length known only at run-time:
    int n = 2;
    int[] array3 = (cast(int*)alloca(n * int.sizeof))[0 .. n];
    array3[0] = 1;
    array3[1] = 3;
    // array3[10] = 4; // run-time error
    writeln("C) Element 0: ", array3[0]);
    writeln("C) Element 1: ", array3[1]);

    // Phobos-defined  heap allocated not GC-managed array:
    Array!int array4;
    array4.length = 2;
    array4[0] = 1;
    array4[1] = 3;
    // array4[10] = 4; // run-time exception
    writeln("D) Element 0: ", array4[0]);
    writeln("D) Element 1: ", array4[1]);
}


# use [] to create numeric arrays of int, float, double or complex types:
a = [ 1, 2, 3 ]  # a vector
b = [ 1, 2; 3, 4 ] # a 2X2 matrix

# use {} to create normal arrays of any types:
c = { 1, 2, 'abc' }

d = a[1]
e = b[0,1] # first row, second column
f = c[1]


main(){
	// Dart uses Lists which dynamically resize by default
	final growable = [ 1, 2, 3 ];

        // Add to the list using the add method
	growable.add(4);

	print('growable: $growable');

	// You can pass an int to the constructor to create a fixed sized List
	final fixed = List(3);

	// We must assign each element individually using the Subscript operator
	// using .add would through an error
	fixed[0] = 'one';
	fixed[1] = 'two';
	fixed[2] = 'three';

	print('fixed: $fixed');

	// If we want to create a fixed list all at once we can use the of constructor
	// Setting growable to false is what makes it fixed
	final fixed2 = List.of( [ 1.5, 2.5, 3.5 ], growable: false);

	print('fixed2: $fixed2');

	// A potential gotcha involving the subscript operator [] might surprise JavaScripters
	// One cannot add new elements to a List using the subscript operator
	// We can only assign to existing elements, even if the List is growable

	final gotcha = [ 1, 2 ];
	// gotcha[2] = 3 would cause an error in Dart, but not in JavaScript
	// We must first add the new element using .add
	gotcha.add(3);
	// Now we can modify the existing elements with the subscript
	gotcha[2] = 4;

	print('gotcha: $gotcha');

}


;
;       Arrays for DBL version 4 by Dario B.
;

.DEFINE NR,5

        RECORD

VNUM1,  5D8             ;array of number
VNUM2,  [5]D8           ;array of number
VNUM3,  [5,2]D8         ;two-dimensional array of number

VALP1,  5A10            ;array of strings
VALP2,  [5]A10          ;array of strings
VALP3,  [5,2]A10        ;two-dimensional array of strings

VALP4,  [NR]A10         ;array of strings

    PROC
;------------------------------------------------------------------

        ;Valid uses of arrays
        VNUM1(1)=12345678

        VNUM2(1)=VNUM1(1)               ; = 12345678
        VNUM2[2]=VNUM1(1)               ; = 12345678

        VNUM2[3]=VNUM2[1](3:2)          ; = 34

        VNUM3[1,1]=1
        VNUM3[1,2]=2
        VNUM3[2,1]=3

        VALP1(1)="ABCDEFGHIJ"

        VALP2(2)=VALP1(1)               ; = "ABCDEFGHIJ"
        VALP2[2]=VALP1(1)               ; = "ABCDEFGHIJ"

        VALP2[3](3:2)=VALP2[1](3:2)     ; = "  CD      "

        VALP3[1,1]="ABCDEFGHIJ"
        VALP3[1,2]=VALP3[1,1]           ;= "ABCDEFGHIJ"
        VALP3[2,1](3:2)=VALP3[1,2](3:2) ;= "   CD      "

        VALP4[1]="ABCDEFGHIJ"

        ;Clear arrays
        CLEAR VNUM1(1:5*8),VNUM3(1:5*2*8)
        VNUM2(1:5*8)=
        CLEAR VALP1(1:5*8),VALP2(1:5*10)
        VALP3(1:5*2*10)=


procedure TForm1.Button1Click(Sender: TObject);
var
  StaticArray: array[1..10] of Integer; // static arrays can start at any index
  DynamicArray: array of Integer; // dynamic arrays always start at 0
  StaticArrayText,
  DynamicArrayText: string;
  ixS, ixD: Integer;
begin
  // Setting the length of the dynamic array the same as the static one
  SetLength(DynamicArray, Length(StaticArray));
  // Asking random numbers storing into the static array
  for ixS := Low(StaticArray) to High(StaticArray) do
  begin
    StaticArray[ixS] := StrToInt(
      InputBox('Random number',
               'Enter a random number for position',
               IntToStr(ixS)));
  end;
  // Storing entered numbers of the static array in reverse order into the dynamic
  ixD := High(DynamicArray);
  for ixS := Low(StaticArray) to High(StaticArray) do
  begin
    DynamicArray[ixD] := StaticArray[ixS];
    Dec(ixD);
  end;
  // Concatenating the static and dynamic array into a single string variable
  StaticArrayText := '';
  for ixS := Low(StaticArray) to High(StaticArray) do
    StaticArrayText := StaticArrayText + IntToStr(StaticArray[ixS]);
  DynamicArrayText := '';
  for ixD := Low(DynamicArray) to High(DynamicArray) do
    DynamicArrayText := DynamicArrayText + IntToStr(DynamicArray[ixD]);
  end;
  // Displaying both arrays (#13#10 = Carriage Return/Line Feed)
  ShowMessage(StaticArrayText + #13#10 + DynamicArrayText);
end;


set_ns(rosettacode);
set_base(0);

// Create a new dynamic array with length zero, variant and/or mixed datatypes
add_array(myEmptyArray);

// Create a new dynamic array with length zero, of integers with no mixed datatypes
add_array({int}, myIntegerArray);

// Create a new fixed-length array with length 5
add_array(myFiveArray)_len(5)_base(0);   // The value base '_base(0)' is usually defaulted to zero, depends upon thing.

// Create an array with 2 members (length is 2)
add_ary(myStringArray)_value(Item1,Item2);   // '_array' can be shortened to '_ary'

// Assign a value to member [2]
with_ary(myChangeArray)_at(2)_v(5);    // '_value' can be shortened to '_v'

// Add a member to an array with the push function (defaulted at end), length increased by one
[myExpandedArray]_push()_v(9);    // 'with_ary(...)' can be shortened to '[...]'
[myExpandedArray]_append()_v(9);

// Add a member to an array with the push function (at a location), length increased by one
[myExpandedArray]_pushat(3)_v(8);

// Remove a member to an array with the pop function (defaulted at end), length reduced by one
[myExpandedArray]_pop();

// Remove a member to an array with the pop function (at a location), length reduced by one
[myExpandedArray]_popat(3);

// Swap a member to an array with the swap function
[myExpandedArray]_swapfrom(2)_swapto(6);
[myExpandedArray]_swap(2, 6);

// Rectiline a member in an array
[MyCaterpillarArray]_rectilat(4)_rectilup(2);
[MyCaterpillarArray]_rectilup(4, 2);
[MyCaterpillarArray]_rectilat(5)_rectildown(3);
[MyCaterpillarArray]_rectildown(5, 3);

// Null a member to an array with the pluck function (defaulted at end)
[myExpandedArray]_pluck();

// Null a member to an array with the pluck function (at a location)
[myExpandedArray]_pluckat(3);

// Get size of array
[mySizableArray]_size();    // '_len()' can also be used
[myMultidimensialArray]_size()

// Retrieve an element of an array
[myArray]_at(3);
[myArray]_first();    // Retrieve first element in an array
[myArray]_last();     // Retrieve last element in an array

// More transformations of arrays (like append, union, intersection) are available

// For multi-dimensional array use the 'matrix' object

set_matrixorder(row-major);    // set major order as row- or column-major order depends on the thing
set_handrule(right);           // set hand-rule, most things will use right hand-rule

// Create a new dynamic two-dimensional array with length zero, variant and/or mixed datatypes
add_matrix(myMatrix)_dim(2);

// Create a new dynamic three-dimensional array with length zero, of integers with no mixed datatypes
add_matrix({int}, my3DEmptyMatrix)_dim(3);

// Convert an array to a matrix by adding a new dimension with length zero, variant and/or mixed datatypes
with_array(MyConvertedArray)_dim();    // Should now use '_matrix' object rather than '_array'
with_array(MyConvertedArray)_dim(3);   // Add three dimensions to array, should now use '_matrix' object rather than '_array'

// Create a new fixed-length traditional (2D) matrix with 5 rows and 4 columns
add_matrix(myMatrix)_rows(5)_columns(4);
add_matirx(myMatrix)_subs(5, 4);  // check or set major order first

// Create a new fixed-length mutil-dimensional matrix with 5 rows, 4 columns, 6 subscripts, and 8 subscripts
add_matrix(myMatrix)_rows(5)_columns(4)_subs(6)_subs(8);
add_mat(myMatrix)_subs(5, 4, 6, 8);  // check or set major order first, '_matrix' can be shortened to 'mat'

// Create a 4 x 4 identiy matrix:
add_mat(myIdentityMatrix)_subs(4, 4)_identity;    // ...or...

add_mat(myMorphedMatrix)_subs(4, 4)
with_mat(myMorphedMatrix)_trans(morph)_identity();   // More transformations available

// Assign a value to member [2,4]
with_mat(myMatrix)_row(2)_col(4)_value(5);    // ...or...
with_mat(myMatrix)_at(2, 4)_v(5);    // check or set major order first

// Add a member(s) to a matrix using push functions is available
// Remove a member(s) from a matrix with the pop functions is available
// Swap a member(s) in a matrix with the swap functions is available

// Rectiline a single member in a three-dimensional matrix
[MyWobbleMatrix]_rectilat()_row(3)_col(3)_sub(3)_rectilto()_row(-1)_col(1)_sub(0);    // ...or...
[MyWobbleMatrix]_rectilat(3, 3, 3)_rectilto(-1, 1, 0);    // check or set major order first, ...or...
[MyWobbleMatrix]_rectilat(3, 3, 3)_rectilleft(1)_rectilup(1);    / check or set hand-rule, ...or...

// Also 'crab', 'elevate', 'slide' and 'pump' movements are available
// Also 'row', 'pitch', and 'yaw' movements are available
// Also, quaternions calculations are available
// Null a member in a matrix using pluck functions is available

// Get size of a matrix
mat(mySizableMatrix)_size();    // will return an array of the size()
[myMultidimensialArray]_len();  // '_len()' can also be used

// Retrieve an element of a matrix
[myMatrix]_at(3, 2);
[myArray]_first()_atsub(2);    // Retrieve first element of a row/column/subscript of a matrix
[myArray]_last()_atsub(2);     // Retrieve last element of a row/column/subscript of a matrix
[myArray]_origin();    // Retrieve first element in a matrix
[myArray]_end();       // Retrieve last element in a matrix

reset_ns[];


array = newarray(3) //optionally, replace "newarray(5)" with a brackets list of values like "[1, 2, 3]"
array[0] = 42
showln array[2]


// dynamic array, extensible, this a reference type
var d : array of Integer;
d.Add(1);     // has various methods to add, delete, etc.
d.Add(2, 3);

// read and write elements by index
item := d[5];
d[6] := item+1;

// static, fixed-size array, arbitrary lower-bound, this is a value type
var s : array [2..4] of Integer;

// inline array constructor, works for both static and dynamic arrays
s := [1, 2, 3];


//Dyalect supports dynamic arrays
var empty = []
var xs = [1, 2, 3]

//Add elements to an array
empty.Add(0)
empty.AddRange(xs)

//Access array elements
var x = xs[2]
xs[2] = x * x


#create a new list
local :l []

#add something to it
push-to l "Hi"

#add something else to it
push-to l "Boo"

#the list could also have been built up this way:
local :l2 [ "Hi" "Boo" ]

#this prints 2
!print len l

#this prints Hi
!print get-from l 0

#this prints Boo
!print pop-from l


len f[] 3
for i range len f[]
  f[i] = i
.
f[] &= 3
for i range len f[]
  print f[i]
.


array int[10]; //optionally, add a braced list of values. E.g. array int[10]{1, 2, 3};
array[1] = 42;
SysLib.writeStdout(array[1]);


class
	APPLICATION

inherit
	ARGUMENTS

create
	make

feature {NONE} -- Initialization
	make
			-- Run application.
		do
			-- initialize the array, index starts at 1 (not zero) and prefill everything with the letter z
			create my_static_array.make_filled ("z", 1, 50)

			my_static_array.put ("a", 1)
			my_static_array.put ("b", 2)
			my_static_array [3] := "c"

			-- access to array fields
			print (my_static_array.at(1) + "%N")
			print (my_static_array.at(2) + "%N")
			print (my_static_array [3] + "%N")

			-- in Eiffel static arrays can be resized in three ways
			my_static_array.force ("c", 51) -- forces 'c' in position 51 and resizes the array to that size (now 51 places)
			my_static_array.automatic_grow -- adds 50% more indices (having now 76 places)
			my_static_array.grow (100) -- resizes the array to 100 places
		end

	my_static_array: ARRAY [STRING]
end


  %% Create a fixed-size array with entries 0-9 set to 'undefined'
  A0 = array:new(10).
  10 = array:size(A0).

  %% Create an extendible array and set entry 17 to 'true',
  %% causing the array to grow automatically
  A1 = array:set(17, true, array:new()).
  18 = array:size(A1).

  %% Read back a stored value
  true = array:get(17, A1).

  %% Accessing an unset entry returns the default value
  undefined = array:get(3, A1).

  %% Accessing an entry beyond the last set entry also returns the
  %% default value, if the array does not have fixed size
  undefined = array:get(18, A1).

  %% "sparse" functions ignore default-valued entries
  A2 = array:set(4, false, A1).
  [{4, false}, {17, true}] = array:sparse_to_orddict(A2).

  %% An extendible array can be made fixed-size later
  A3 = array:fix(A2).

  %% A fixed-size array does not grow automatically and does not
  %% allow accesses beyond the last set entry
  {'EXIT',{badarg,_}} = (catch array:set(18, true, A3)).
  {'EXIT',{badarg,_}} = (catch array:get(18, A3)).


 DIM A%[100]   ! integer array
 DIM S$[50]    ! string array
 DIM R[50]     ! real array
 DIM R#[70]    ! long real array


--Arrays task for Rosetta Code wiki
--User:Lnettnay

atom dummy
--Arrays are sequences
-- single dimensioned array of 10 elements
sequence xarray = repeat(0,10)
xarray[5] = 5
dummy = xarray[5]
? dummy

--2 dimensional array
--5 sequences of 10 elements each
sequence xyarray = repeat(repeat(0,10),5)
xyarray[3][6] = 12
dummy = xyarray[3][6]
? dummy

--dynamic array use (all sequences can be modified at any time)
sequence dynarray = {}
for x = 1 to 10 do
        dynarray = append(dynarray, x * x)
end for
? dynarray

for x = 1 to 10 do
        dynarray = prepend(dynarray, x)
end for
? dynarray


{ 1 2 3 }
{
  [ "The initial array: " write . ]
  [ [ 42 1 ] dip set-nth ]
  [ "Modified array: " write . ]
  [ "The element we modified: " write [ 1 ] dip nth . ]
} cleave


create MyArray 1 , 2 , 3 , 4 , 5 ,  5 cells allot
here constant MyArrayEnd

30 MyArray 7 cells + !
MyArray 7 cells + @ .    \ 30

: .array  MyArrayEnd MyArray do I @ .  cell +loop ;


' compile with: FBC -s console.
' compile with: FBC -s console -exx to have boundary checks.

Dim As Integer a(5)  ' from s(0) to s(5)
Dim As Integer num = 1
Dim As String s(-num To num) ' s1(-1), s1(0) and s1(1)

Static As UByte c(5) ' create a  array with 6 elements (0 to 5)

'dimension array and initializing it with Data
Dim d(1 To 2, 1 To 5) As Integer => {{1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}}
Print "  The first dimension has a lower bound of"; LBound(d);_
                           " and a upper bound of"; UBound(d)
Print " The second dimension has a lower bound of"; LBound(d,2);_
                           " and a upper bound of"; UBound(d,2)
Print : Print

Dim Shared As UByte u(0 To 3) ' make a shared array of UByte with 4 elements

Dim As UInteger pow() ' make a variable length array
' you must Dim the array before you can use ReDim
ReDim pow(num) ' pow now has 1 element
pow(num) = 10  ' lets fill it with 10 and print it
Print " The value of pow(num) = "; pow(num)

ReDim pow(10)  ' make pow a 10 element array
Print
Print " Pow now has"; UBound(pow) - LBound(pow) +1; " elements"
' the value of pow(num) is gone now
Print " The value of pow(num) = "; pow(num); ", should be 0"

Print
For i As Integer = LBound(pow) To UBound(pow)
    pow(i) = i * i
    Print pow(i),
Next
Print:Print

ReDim Preserve pow(3 To 7)
' the first five elements will be preserved, not elements 3 to 7
Print
Print " The lower bound is now"; LBound(pow);_
      " and the upper bound is"; UBound(pow)
Print " Pow now has"; UBound(pow) - LBound(pow) +1; " elements"
Print
For i As Integer = LBound(pow) To UBound(pow)
    Print pow(i),
Next
Print : Print

'erase the variable length array
Erase pow
Print " The lower bound is now"; LBound(pow);_
     " and the upper bound is "; UBound(pow)
Print " If the lower bound is 0 and the upper bound is -1 it means,"
Print " that the array has no elements, it's completely removed"
Print : Print

'erase the fixed length array
Print " Display the contents of the array d"
For i As Integer = 1 To 2 : For j As Integer = 1 To 5
    Print d(i,j);" ";
Next : Next : Print : Print

Erase d
Print " We have erased array d"
Print "  The first dimension has a lower bound of"; LBound(d);_
                           " and a upper bound of"; UBound(d)
Print " The second dimension has a lower bound of"; LBound(d,2);_
                           " and a upper bound of"; UBound(d,2)
Print
For i As Integer = 1 To 2 : For j As Integer = 1 To 5
    Print d(i,j);" ";
Next : Next
Print
Print " The elements self are left untouched but there content is set to 0"

' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End


a = new array
[email protected] = 10
[email protected] = 20
println[[email protected]]

b = [1, 2, 3]


DIM mynumbers AS INTEGER[]
myfruits AS STRING[]

mynumbers[0] = 1.5
mynumbers[1] = 2.3

myfruits[0] = "apple"
myfruits[1] = "banana"


# Arrays are better called lists in GAP. Lists may have elements of mixed types, e$
v := [ 10, 7, "bob", true, [ "inner", 5 ] ];
# [ 10, 7, "bob", true, [ "inner", 5 ] ]

# List index runs from 1 to Size(v)
v[1];
# 10

v[0];
# error

v[5];
# [ "inner", 5 ]

v[6];
# error

# One can assign a value to an undefined element
v[6] := 100;

# Even if it's not after the last: a list may have undefined elements
v[10] := 1000;
v;
# [ 10, 7, "bob", true, [ "inner", 5 ], 100,,,, 1000 ]

# And one can check for defined values
IsBound(v[10]);
# true

IsBound(v[9]);
# false

# Size of the list
Size(v);
# 10

# Appending a list to the end of another
Append(v, [ 8, 9]);
v;
# [ 10, 7, "bob", true, [ "inner", 5 ], 100,,,, 1000, 8, 9 ]

# Adding an element at the end
Add(v, "added");
v;
# [ 10, 7, "bob", true, [ "inner", 5 ], 100,,,, 1000, 8, 9, "added" ]


[indent=4]
/*
   Arrays, in Genie

   valac --pkg=gee-0.8 arrays.gs
   ./arrays
*/

uses
    Gee

init
    /* allocate a fixed array */
    var arr = new array of int[10]

    /* initialized array of strings */
    initialized:array of string = {"This", "is", "Genie"}

    /* length is an array property */
    stdout.printf("%d\n", arr.length)

    /* read/write access via index */
    arr[1] = 1
    arr[9] = arr[1] + 8
    stdout.printf("%d\n", arr[9])

    print initialized[2]

    /* Dynamic arrays are lists in Genie */
    var dyn = new list of int
    dyn.add(1)
    dyn.add(8)
    dyn.add(dyn[0]+dyn[1])
    stdout.printf("dyn size: %d\n", dyn.size)
    stdout.printf("dyn[2]  : %d\n", dyn[2])


package main

import (
    "fmt"
)

func main() {
    // creates an array of five ints.
    // specified length must be a compile-time constant expression.
    // this allows compiler to do efficient bounds checking.
    var a [5]int

    // since length is compile-time constant, len() is a compile time constant
    // and does not have the overhead of a function call.
    fmt.Println("len(a) =", len(a))

    // elements are always initialized to 0
    fmt.Println("a =", a)

    // assign a value to an element.  indexing is 0 based.
    a[0] = 3
    fmt.Println("a =", a)

    // retrieve element value with same syntax
    fmt.Println("a[0] =", a[0])

    // a slice references an underlying array
    s := a[:4] // this does not allocate new array space.
    fmt.Println("s =", s)

    // slices have runtime established length and capacity, but len() and
    // cap() are built in to the compiler and have overhead more like
    // variable access than function call.
    fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))

    // slices can be resliced, as long as there is space
    // in the underlying array.
    s = s[:5]
    fmt.Println("s =", s)

    // s still based on a
    a[0] = 22
    fmt.Println("a =", a)
    fmt.Println("s =", s)

    // append will automatically allocate a larger underlying array as needed.
    s = append(s, 4, 5, 6)
    fmt.Println("s =", s)
    fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))

    // s no longer based on a
    a[4] = -1
    fmt.Println("a =", a)
    fmt.Println("s =", s)

    // make creates a slice and allocates a new underlying array
    s = make([]int, 8)
    fmt.Println("s =", s)
    fmt.Println("len(s) =", len(s), " cap(s) =", cap(s))

    // the cap()=10 array is no longer referenced
    // and would be garbage collected eventually.
}


[1 2 3]:a; # numeric only array, assigned to a and then dropped
10,:a;     # assign to a [0 1 2 3 4 5 6 7 8 9]
a 0= puts  # pick element at index 0 (stack: 0)
a 10+puts  # append 10 to the end of a
10 a+puts  # prepend 10 to a


def aa = [ 1, 25, 31, -3 ]           // list
def a = [0] * 100                    // list of 100 zeroes
def b = 1..9                         // range notation
def c = (1..10).collect { 2.0**it }  // each output element is 2**(corresponding invoking list element)

// There are no true "multi-dimensional" arrays in Groovy (as in most C-derived languages).
// Use lists of lists in natural ("row major") order as a stand in.
def d = (0..1).collect { i -> (1..5).collect { j -> 2**(5*i+j) as double } }
def e = [ [  1.0,  2.0,  3.0,  4.0 ],
          [  5.0,  6.0,  7.0,  8.0 ],
          [  9.0, 10.0, 11.0, 12.0 ],
          [ 13.0, 14.0, 15.0, 16.0 ] ]

println aa
println b
println c
println()
d.each { print "["; it.each { elt -> printf "%7.1f ", elt }; println "]" }
println()
e.each { print "["; it.each { elt -> printf "%7.1f ", elt }; println "]" }


10 DATA 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
20 DIM A(9)        ' Array with size 10 (9 is maximum subscript), all elements are set to 0
30 FOR I = 0 TO 9
40     READ A(I)   ' Initialize by reading data
50 NEXT I
60 PRINT A(4)      ' Get 4th element of array
70 A(4) = 400      ' Set 4th element of array
80 PRINT A(4)


$array = [];

$array[] = 1;
$array["key"] = 3;

$array[0] = 2;

echo $array[0];
echo $array["key"];


   // Declare and initialize two-dimensional array
   local arr1 := { { "NITEM", "N", 10, 0 }, { "CONTENT", "C", 60, 0 } }
   // Create an empty array
   local arr2 := {}
   // Declare three-dimensional array
   local arr3[ 2, 100, 3 ]
   // Create an array
   local arr4 := Array( 50 )

   // Array can be dynamically resized:
   arr4 := ASize( arr4, 80 )


import Data.Array.IO

main = do arr <- newArray (1,10) 37 :: IO (IOArray Int Int)
          a <- readArray arr 1
          writeArray arr 1 64
          b <- readArray arr 1
          print (a,b)


let a    arr 2  # fixed size
let a[0] 123    # index starting at 0
let a[1] "test" # can hold different types

println a[1]


REAL :: n = 3, Astat(n), Bdyn(1, 1)

Astat(2) = 2.22222222
WRITE(Messagebox, Name) Astat(2)

ALLOCATE(Bdyn, 2*n, 3*n)
Bdyn(n-1, n) = -123
WRITE(Row=27) Bdyn(n-1, n)

ALIAS(Astat, n-1,   last2ofAstat, 2)
WRITE(ClipBoard) last2ofAstat      ! 2.22222222 0


// Create an array of fixed size
U8 array[10] = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;

// The first element of a HolyC array is indexed at 0. To set a value:
array[0] = 123;

// Access an element
Print("%d\n", array[0]);


record aThing(a, b, c)       # arbitrary object (record or class) for illustration

procedure main()
    A0 := []                 # empty list
    A0 := list()             # empty list (default size 0)
    A0 := list(0)            # empty list (literal size 0)

    A1 := list(10)           # 10 elements, default initializer &null
    A2 := list(10, 1)        # 10 elements, initialized to 1

    # literal array construction - arbitrary dynamically typed members
    A3 := [1, 2, 3, ["foo", "bar", "baz"], aThing(1, 2, 3), "the end"]

    # left-end workers
    # NOTE: get() is a synonym for pop() which allows nicely-worded use of put() and get() to implement queues
    #
    Q := [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    x := pop(A0)        # x is 1
    x := get(A0)        # x is 2
    push(Q,0)
    # Q is now [0,3, 4, 5, 6, 7, 8, 9, 10]

    # right-end workers
    x := pull(Q)        # x is 10
    put(Q, 100)         # Q is now [0, 3, 4, 5, 6, 7, 8, 9, 100]

    # push and put return the list they are building
    # they also can have multiple arguments which work like repeated calls

    Q2 := put([],1,2,3)    # Q2 is [1,2,3]
    Q3 := push([],1,2,3)   # Q3 is [3,2,1]
    Q4 := push(put(Q2),4),0] # Q4 is [0,1,2,3,4] and so is Q2

    # array access follows with A as the sample array
    A := [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

    # get element indexed from left
    x := A[1]           # x is 10
    x := A[2]           # x is 20
    x := A[10]          # x is 100

    # get element indexed from right
    x := A[-1]          # x is 100
    x := A[-2]          # x is 90
    x := A[-10]         # x is 10

    # copy array to show assignment to elements
    B := copy(A)

    # assign element indexed from left
    B[1] := 11
    B[2] := 21
    B[10] := 101
    # B is now [11, 21, 30, 50, 60, 60, 70, 80, 90, 101]

    # assign element indexed from right - see below
    B[-1] := 102
    B[-2] := 92
    B[-10] := 12
    # B is now [12, 21, 30, 50, 60, 60, 70, 80, 92, 102]

    # list slicing
    # the unusual nature of the slice - returning 1 less element than might be expected
    # in many languages - is best understood if you imagine indexes as pointing to BEFORE
    # the item of interest. When a slice is made, the elements between the two points are
    # collected. eg in the A[3 : 6] sample, it will get the elements between the [ ] marks
    #
    # sample list:              10  20 [30  40  50] 60  70  80  90  100
    # positive indexes:        1   2   3   4   5   6   7   8   9   10  11
    # non-positive indexes:  -10  -9  -8  -7  -6  -5  -4  -3  -2  -1   0
    #
    # I have deliberately drawn the indexes between the positions of the values.
    # The nature of this indexing brings simplicity to string operations
    #
    # list slicing can also use non-positive indexes to access values from the right.
    # The final index of 0 shown above shows how the end of the list can be nominated
    # without having to know it's length
    #
    # NOTE: list slices are distinct lists, so assigning to the slice
    # or a member of the slice does not change the values in A
    #
    # Another key fact to understand: once the non-positive indexes and length-offsets are
    # resolved to a simple positive index, the index pair (if two are given) are swapped
    # if necessary to yield the elements between the two.
    #
    S := A[3 : 6]       # S is [30, 40, 50]
    S := A[6 : 3]       # S is [30, 40, 50]   not illegal or erroneous
    S := A[-5 : -8]     # S is [30, 40, 50]
    S := A[-8 : -5]     # S is [30, 40, 50]   also legal and meaningful

    # list slicing with length request
    S := A[3 +: 3]      # S is [30, 40, 50]
    S := A[6 -: 3]      # S is [30, 40, 50]
    S := A[-8 +: 3]     # S is [30, 40, 50]
    S := A[-5 -: 3]     # S is [30, 40, 50]
    S := A[-8 -: -3]    # S is [30, 40, 50]
    S := A[-5 +: -3]    # S is [30, 40, 50]
end


main
	//Fixed-length arrays.
	f $= array.integer[1]()
	f[0] $= 2
	print(f[0])

	//Dynamic arrays.
	d $= list.integer()
	d[+] $= 2
	print(d[1])
}


foo := list("foo", "bar", "baz")
foo at(1) println // bar
foo append("Foobarbaz")
foo println
foo atPut(2, "barbaz") // baz becomes barbaz


   1                          NB. a stand-alone scalar value is an array without any axis
1
   NB. invoking any array produces that array as the result
   {. array=: 1 3, 6#0        NB. create, name, then get head item of the array: 1 3 0 0 0 0 0 0
1
   0 { array                  NB. another way to get the head item
1
   aword=: 'there'            NB. a literal array
   0 1 3 2 2 { aword          NB. multiple items can be drawn in a single action
three
   ]twoD=: 3 5 $ 'abcdefghijklmnopqrstuvwxyz'
abcde
fghij
klmno
   1 { twoD                   NB. item 1 from twoD - a list of three items
fghij
   1 {"1 twoD                 NB. item 1 from each rank-1 item of twoD (i.e. column 1)
bgl
   (<2 2){ twoD               NB. bracket indexing is not used in J
m
   'X' 1} aword               NB. amend item 1
tXere
   aword=: 'X' 1 4} aword     NB. in-place amend of items 1 and 4
tXerX
   'X' (0 0;1 1;2 2)} twoD    NB. amend specified items
Xbcde
fXhij
klXno


int[] array = new int[10]; //optionally, replace "new int[10]" with a braced list of ints like "{1, 2, 3}"
array[0] = 42;
System.out.println(array[3]);


// Create a new array with length 0
var myArray = new Array();

// Create a new array with length 5
var myArray1 = new Array(5);

// Create an array with 2 members (length is 2)
var myArray2 = new Array("Item1","Item2");

// Create an array with 2 members using an array literal
var myArray3 = ["Item1", "Item2"];

// Assign a value to member [2] (length is now 3)
myArray3[2] = 5;

var x = myArray[2] + myArray.length;   // 8

// You can also add a member to an array with the push function (length is now 4)
myArray3.push('Test');

// Elisions are supported, but are buggy in some implementations
var y = [0,1,,];  // length 3, or 4 in buggy implementations


# Create a new array with length 0
[]

# Create a new array of 5 nulls
[][4] = null   # setting the element at offset 4 expands the array

# Create an array having the elements 1 and 2 in that order
[1,2]

# Create an array of integers from 0 to 10 inclusive
[ range(0; 11) ]

# If a is an array (of any length), update it so that a[2] is 5
a[2] = 5;

# Append arrays a and b
a + b

# Append an element, e, to an array a
a + [e]

##################################################
# In the following, a is assumed to be [0,1,2,3,4]

# It is not an error to use an out-of-range index:
a[10]  # => null

# Negative indices count backwards from after the last element:
a[-1]  # => 4

# jq supports simple slice operations but
# only in the forward direction:
a[:1]  # => [0]
a[1:]  # => [1,2,3,4]
a[2:4] # => [2,3]
a[4:2] # null


/* Arrays in Jsi */
// Create a new array with length 0
var myArray = new Array();
;myArray;

// In Jsi, typeof [] is "array".  In ECMAScript, typeof [] is "object"
;typeof [];

// Create a new array with length 5
var myArray1 = new Array(5);
;myArray1;

// Create an array with 2 members (length is 2)
var myArray2 = new Array("Item1","Item2");
;myArray2;
;myArray2.length;

// Create an array with 2 members using an array literal
var myArray3 = ["Item1", "Item2"];
;myArray3;

// Assign a value to member [2] (length is now 3)
myArray3[2] = 5;
;myArray3;
;myArray3.length;

var x = myArray3[2] + myArray3.length;   // 8
;x;

// You can also add a member to an array with the push function (length is now 4)
myArray3.push('Test');
;myArray3;
;myArray3.length;

// Empty array entries in a literal is a syntax error, elisions not allowed
//var badSyntax = [1,2,,4];

/*
=!EXPECTSTART!=
myArray ==> []
typeof [] ==> array
myArray1 ==> [ undefined, undefined, undefined, undefined, undefined ]
myArray2 ==> [ "Item1", "Item2" ]
myArray2.length ==> 2
myArray3 ==> [ "Item1", "Item2" ]
myArray3 ==> [ "Item1", "Item2", 5 ]
myArray3.length ==> 3
x ==> 8
myArray3 ==> [ "Item1", "Item2", 5, "Test" ]
myArray3.length ==> 4
=!EXPECTEND!=
*/


julia> A = cell(3)   # create an heterogeneous array of length 3
3-element Array{Any,1}:
 #undef
 #undef
 #undef

julia> A[1] = 4.5 ; A[3] =  "some string" ; show(A)
{4.5,#undef,"some string"}

julia> A[1]          # access a value. Arrays are 1-indexed
4.5

julia> push!(A, :symbol) ; show(A)    # append an element
{4.5,#undef,"some string",:symbol}

julia> A[10]         # error if the index is out of range
ERROR: BoundsError()


//creates an array of length 3
Array:New array[3]:Number;

function main() {
  Var:Number length;
  Array:GetLength(array, length)  //retrieve length of array
  Konsol:Log(length)

  array[0] = 5;                   //assign value
  Konsol:Log(array[0])            //retrieve value and display
}


fun main(x: Array<String>) {
    var a = arrayOf(1, 2, 3, 4)
    println(a.asList())
    a += 5
    println(a.asList())
    println(a.reversedArray().asList())
}


V a = Int(input())
V b = Int(input())

print(‘a + b = ’(a + b))
print(‘a - b = ’(a - b))
print(‘a * b = ’(a * b))
print(‘a / b = ’(a I/ b))
print(‘a % b = ’(a % b))
print(‘a ^ b = ’(a ^ b))


*        Arithmetic/Integer        04/09/2015
ARITHINT CSECT
         USING  ARITHINT,R12
         LR     R12,R15
ADD      L      R1,A
         A      R1,B               r1=a+b
         XDECO  R1,BUF
         MVI    BUF,C'+'
         XPRNT  BUF,12
SUB      L      R1,A
         S      R1,B               r1=a-b
         XDECO  R1,BUF
         MVI    BUF,C'-'
         XPRNT  BUF,12
MUL      L      R1,A
         M      R0,B               r0r1=a*b
         XDECO  R1,BUF             so r1 has the lower part
         MVI    BUF,C'*'
         XPRNT  BUF,12
DIV      L      R0,A
         SRDA   R0,32              to shift the sign
         D      R0,B               r1=a/b and r0 has the remainder
         XDECO  R1,BUF             so r1 has quotient
         MVI    BUF,C'/'
         XPRNT  BUF,12
MOD      L      R0,A
         SRDA   R0,32              to shift the sign
         D      R0,B               r1=a/b and r0 has the remainder
         XDECO  R0,BUF             so r0 has the remainder
         MVI    BUF,C'R'
         XPRNT  BUF,12
RETURN   XR     R15,R15
         BR     R14
         CNOP   0,4
A        DC     F'53'
B        DC     F'11'
BUF      DC     CL12' '
         YREGS
         END    ARITHINT


// Create a new array with length 0
{def myArray1 {A.new}}
-> []

// Create an array with 2 members (length is 2)
{def myArray2 {A.new Item1 Item2}}
-> [Item1,Item2]

// Edit a value in an array
{def myArray3 {A.new 1 2 3}}
{A.set! 1 hello {myArray3}}
-> [1,hello,3]

// Add a value at the head of an array
{def myArray4 {A.new 1 2 3}}-> myArray4
{A.addfirst! hello {myArray4}}
-> [hello,1,2,3]

// Add a value at the tail of an array
{def myArray5 {A.new 1 2 3}}
{A.addlast! hello {myArray5}}
-> [1,2,3,hello]

and so on...