Loop over multiple arrays simultaneously: Difference between revisions

m
m (syntax highlighting fixup automation)
imported>Arakov
 
(35 intermediate revisions by 21 users not shown)
Line 297:
 
If the arrays are not the same length, a subscript range error would occur when a non-existant element was accessed.
 
=={{header|Amazing Hopper}}==
Versión 1: todos los arrays tienen el mismo tamaño:
<syntaxhighlight lang="txt">
#include <jambo.h>
 
Main
Void 'x,y,z'
Set '"a","b","c"' Append to list 'x'
Set '"A","B","C"' Append to list 'y'
Set '1,2,3' Append to list 'z'
i=1
Loop
[i++], Printnl ( Get 'x', Get 'y', Get 'z' )
Back if less-equal (i, 3)
End
</syntaxhighlight>
{{out}}
<pre>
aA1
bB2
cC3
</pre>
Versión 2: los arrays tienen distinto tamaño:
<syntaxhighlight lang="txt">
#include <jambo.h>
 
Main
Void 'x,y,z'
Let list ( x := "a","b","c" )
Let list ( y := "A","B","C","D","E" )
Let list ( z := 1,2,3,4 )
i=1, error=0
Loop
[i++]
Try ; Get 'x', Print it ; Catch 'error'; Print (" ") ; Finish
Try ; Get 'y', Print it ; Catch 'error'; Print (" ") ; Finish
Try ; Get 'z', Print it ; Catch 'error'; Print (" ") ; Finish
Prnl
Back if less-equal (i, 5)
End
</syntaxhighlight>
{{out}}
<pre>
aA1
bB2
cC3
D4
E
</pre>
 
=={{header|APL}}==
Line 650 ⟶ 700:
short lists.
 
=={{header|BaConBASIC}}==
==={{header|Applesoft BASIC}}===
{{trans|ZX Spectrum Basic}}
<syntaxhighlight lang="basic">REM DEFINE THE ARRAYS AND POPULATE THEM
0 SIZE = 3: DIM A$(SIZE),B$(SIZE),C(SIZE): FOR I = 1 TO SIZE:A$(I) = CHR$ (96 + I):B$(I) = CHR$ (64 + I):C(I) = I: NEXT
 
REM LOOP OVER MULTIPLE ARRAYS SIMULTANEOUSLY
1 FOR I = 1 TO SIZE
2 PRINT A$(I)B$(I)C(I)
3 NEXT I
</syntaxhighlight>
==={{header|BaCon}}===
<syntaxhighlight lang="freebasic">
DECLARE a1$[] = {"a", "b", "c"} TYPE STRING
Line 664 ⟶ 724:
</syntaxhighlight>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic">arraybase 1
=={{header|BASIC256}}==
dim arr1$(3) : arr1$ = {"a", "b", "c"}
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">dim arr1$(3) : arr1$ = {"a", "b", "c"}
dim arr2$(3) : arr2$ = {"A", "B", "C"}
dim arr3(3) : arr3 = {1, 2, 3}
 
for i = 01 to 23
print arr1$[i]; arr2$[i]; arr3[i]
next i
print
end</syntaxhighlight>
{{out}}
<pre>
aA1
bB2
cC3
</pre>
 
# For arrays of different lengths we would need to iterate up to the mimimm
# length of all 3 in order to get a contribution from each one. For example:
 
dim arr4$(4) : arr4$ = {"A", "B", "C", "D"}
=={{header|BBC BASIC}}==
dim arr5(2) : arr5 = {1, 2}
 
ub = min(arr1$[?], min((arr4$[?]), (arr5[?])))
for i = 1 To ub
print arr1$[i]; arr4$[i]; arr5[i]
next i
print
end
 
function min(x,y)
if(x < y) then return x else return y
end function</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|BBC BASIC}}===
<syntaxhighlight lang="bbcbasic"> DIM array1$(2), array2$(2), array3%(2)
array1$() = "a", "b", "c"
Line 692 ⟶ 763:
PRINT array1$(index%) ; array2$(index%) ; array3%(index%)
NEXT</syntaxhighlight>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function min(x As Integer, y As Integer) As Integer
Return IIf(x < y, x, y)
End Function
 
Dim arr1(1 To 3) As String = {"a", "b", "c"}
Dim arr2(1 To 3) As String = {"A", "B", "C"}
Dim arr3(1 To 3) As Integer = {1, 2, 3}
 
For i As Integer = 1 To 3
Print arr1(i) & arr2(i) & arr3(i)
Next
 
Print
 
' For arrays of different lengths we would need to iterate up to the mimimm length of all 3 in order
' to get a contribution from each one. For example:
 
Dim arr4(1 To 4) As String = {"A", "B", "C", "D"}
Dim arr5(1 To 2) As Integer = {1, 2}
 
Dim ub As Integer = min(UBound(arr1), min(UBound(arr4), UBound(arr5)))
For i As Integer = 1 To ub
Print arr1(i) & arr2(i) & arr3(i)
Next
 
Print
Sleep</syntaxhighlight>
 
{{out}}
<pre>
aA1
bB2
cC3
 
aA1
bB2
</pre>
 
==={{header|Gambas}}===
'''[https://gambas-playground.proko.eu/?gist=3a69e733694aeab3b72c6a5c0316535b Click this link to run this code]'''
<syntaxhighlight lang="gambas">Public Sub Main()
Dim a1 As String[] = ["a", "b", "c"]
Dim a2 As String[] = ["A", "B", "C"]
Dim a3 As String[] = ["1", "2", "3"]
Dim siC As Short
 
For siC = 0 To a1.Max
Print a1[siC] & a2[siC] & a3[siC]
Next
 
End</syntaxhighlight>
 
Output:
<pre>
aA1
bB2
cC3
</pre>
 
==={{header|Liberty BASIC}}===
<syntaxhighlight lang="lb">a$(1)="a" : a$(2)="b" : a$(3)="c"
b$(1)="A" : b$(2)="B" : b$(3)="C"
c(1)=1 : c(2)=2 : c(3)=3
 
 
for i = 1 to 3
print a$(i);b$(i);c(i)
next</syntaxhighlight>
 
==={{header|NS-HUBASIC}}===
<syntaxhighlight lang="ns-hubasic">10 DIM A$(3)
20 DIM B$(3)
30 DIM C$(3)
40 A$(1)="THIS"
50 A$(2)=" LOOPS"
60 A$(3)=" ARRAYS"
70 B$(1)=" NS-HUBASIC"
80 B$(2)=" OVER"
90 B$(3)=" AT"
100 C$(1)=" PROGRAM"
110 C$(2)=" MULTIPLE"
120 C$(3)=" ONCE."
130 FOR I=1 TO 3
140 PRINT A$(I)B$(I)C$(I)
150 NEXT</syntaxhighlight>
 
==={{header|PowerBASIC}}===
<syntaxhighlight lang="powerbasic">FUNCTION PBMAIN () AS LONG
DIM x(2), y(2) AS STRING * 1
DIM z(2) AS LONG
 
'data
ARRAY ASSIGN x() = ("a", "b", "c")
ARRAY ASSIGN y() = ("A", "B", "C")
ARRAY ASSIGN z() = (1, 2, 3)
 
'set upper bound
C& = UBOUND(x)
IF UBOUND(y) > C& THEN C& = UBOUND(y)
IF UBOUND(z) > C& THEN C& = UBOUND(z)
 
OPEN "output.txt" FOR OUTPUT AS 1
FOR L& = 0 TO C&
IF L& <= UBOUND(x) THEN PRINT #1, x(L&);
IF L& <= UBOUND(y) THEN PRINT #1, y(L&);
IF L& <= UBOUND(z) THEN PRINT #1, TRIM$(STR$(z(L&)));
PRINT #1,
NEXT
CLOSE
END FUNCTION</syntaxhighlight>
 
==={{header|PureBasic}}===
<syntaxhighlight lang="purebasic">OpenConsole()
; Fill arrays
Dim a.s(2)
Dim b.s(2)
Dim c(2)
For Arrayposition = 0 To ArraySize(a())
a(Arrayposition) = Chr(Asc("a") + Arrayposition)
b(Arrayposition) = Chr(Asc("A") + Arrayposition)
c(Arrayposition) = Arrayposition + 1
Next
; loop over them
For Arrayposition = 0 To ArraySize(a())
PrintN(a(Arrayposition) + b(Arrayposition) + Str(c(Arrayposition)))
Next
Input() ;wait for Enter before ending</syntaxhighlight>
 
If they have different lengths there are two cases:<br>
a() is the shortest one: Only elements up to maximum index of a() are
printed <br>
a() is bigger than another one: if exceeding index to much, program
crashes, <br>
else it may work because there is some "free space" after end of
assigned array memory. <br>
For example if a has size 4, line dD4 will also be printed. size 20
leads to an crash <br>
This is because ReDim becomes slow if everytime there is a change to
array size new memory has to be allocated.
 
==={{header|Run BASIC}}===
<syntaxhighlight lang="runbasic">for i = 1 to 3
a$(i) = chr$(i+96)
b$(i) = chr$(i+64)
c(i) = i
next i
 
for i = 1 to 3
print a$(i);b$(i);c(i)
next</syntaxhighlight>
 
==={{header|Visual Basic .NET}}===
Two implementations: one determines the shortest of the arrays and uses a simple For loop with element accesses to each array separately; one uses Enumerable.Zip (which can only zip two sequences at once) twice to create 3-tuples. Enumerable.Zip stops when either source runs out of elements, so the behavior of the two implementations is identical for arrays of different lengths.
<syntaxhighlight lang="vbnet">
Module Program
Sub Main()
Dim a As Char() = {"a"c, "b"c, "c"c}
Dim b As Char() = {"A"c, "B"c, "C"c}
Dim c As Integer() = {1, 2, 3}
 
Dim minLength = {a.Length, b.Length, c.Length}.Min()
For i = 0 To minLength - 1
Console.WriteLine(a(i) & b(i) & c(i))
Next
 
Console.WriteLine()
 
For Each el As (a As Char, b As Char, c As Integer) In a.Zip(b, Function(l, r) (l, r)).Zip(c, Function(x, r) (x.l, x.r, r))
Console.WriteLine(el.a & el.b & el.c)
Next
End Sub
End Module</syntaxhighlight>
 
{{out}}
<pre>aA1
bB2
cC3
 
aA1
bB2
cC3</pre>
 
==={{header|XBasic}}===
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">' Loop over multiple arrays simultaneously
PROGRAM "loopoverarrays"
 
DECLARE FUNCTION Entry()
 
FUNCTION Entry()
DIM arr1$[2], arr2$[2], arr3%[2]
arr1$[0] = "a": arr1$[1] = "b": arr1$[2] = "c"
arr2$[0] = "A": arr2$[1] = "B": arr2$[2] = "C"
arr3%[0] = 1: arr3%[1] = 2: arr3%[2] = 3
FOR i% = 0 TO 2
PRINT arr1$[i%]; arr2$[i%]; FORMAT$("#", arr3%[i%])
NEXT i%
END FUNCTION
END PROGRAM
</syntaxhighlight>
 
==={{header|Yabasic}}===
<syntaxhighlight lang="basic">dim arr1$(3), arr2$(3), arr3(3)
arr1$(1) = "a"
arr1$(2) = "b"
arr1$(3) = "c"
arr2$(1) = "A"
arr2$(2) = "B"
arr2$(3) = "C"
arr3(1) = 1
arr3(2) = 2
arr3(3) = 3
 
for i = 1 to 3
print arr1$(i), arr2$(i), arr3(i)
next
print
 
// For arrays of different lengths we would need to iterate up to the mimimm
// length of all 3 in order to get a contribution from each one. For example:
 
dim arr4$(4), arr5(2)
arr4$(1) = "A"
arr4$(2) = "B"
arr4$(3) = "C"
arr4$(4) = "D"
arr5(1) = 1
arr5(2) = 2
 
ub = min(arraysize(arr1$(),1), min(arraysize(arr4$(),1),arraysize(arr5(),1)))
for i = 1 to ub
print arr1$(i), arr4$(i), arr5(i)
next
end</syntaxhighlight>
{{out}}
<pre>Same as FreeBASIC entry.</pre>
 
==={{header|ZX Spectrum Basic}}===
<syntaxhighlight lang="zxbasic">10 LET sza = 3: REM size of a
20 LET szb = 3: REM size of b
30 LET szc = 3: REM size of c
40 DIM a$(sza): DIM b$(szb): DIM c$(szc)
50 LET max = sza: REM assume a is the biggest
60 IF szb > max THEN LET max = szb: REM now try b
70 IF szc > max THEN LET max = szc: REM or c
80 REM populate our arrays, and as a bonus we already have our demo loop
90 REM we might as well print as we populate showing the arrays in
columns
100 FOR l = 1 TO max
110 IF l <= sza THEN READ a$(l): PRINT a$(l);
120 IF l <= szb THEN READ b$(l): PRINT b$(l);
130 IF l <= szc THEN READ c$(l): PRINT c$(l);
140 PRINT: REM newline
145 NEXT l
150 PRINT "The arrays are shown in columns."
160 PRINT "A$ runs down the left hand side,"
170 PRINT "and C$ runs down the right."
180 STOP
200 DATA "a","b","c","A","B","C","1","2","3"</syntaxhighlight>
 
Simplification
 
<syntaxhighlight lang="zxbasic">10 READ size: DIM a$(size): DIM b$(size): DIM c$(size)
20 FOR i=1 TO size
30 READ a$(i),b$(i),c$(i)
40 PRINT a$(i);b$(i);c$(i)
50 NEXT i
60 DATA 3,"a","A","1","b","B","2","c","C","3"</syntaxhighlight>
 
=={{header|Beads}}==
Line 1,239 ⟶ 1,582:
 
(This will stop when the end of the shortest collection is reached.)
 
=={{header|EasyLang}}==
<syntaxhighlight>
a$[] = [ "a" "b" "c" ]
b$[] = [ "A" "B" "C" ]
c[] = [ 1 2 3 ]
for i = 1 to 3
print a$[i] & b$[i] & c[i]
.
</syntaxhighlight>
 
=={{header|EchoLisp}}==
Line 1,257 ⟶ 1,610:
1005 "F" 5 t
</syntaxhighlight>
 
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module LoopOverMultipleArrays {
void run() {
Char[] chars = ['a', 'b', 'c'];
String[] strings = ["A", "B", "C"];
Int[] ints = [ 1, 2, 3 ];
 
@Inject Console console;
console.print("Using array indexing:");
for (Int i = 0, Int longest = chars.size.maxOf(strings.size.maxOf(ints.size));
i < longest; ++i) {
console.print($|{i < chars.size ? chars[i].toString() : ""}\
|{i < strings.size ? strings[i] : ""}\
|{i < ints.size ? ints[i].toString() : ""}
);
}
 
console.print("\nUsing array iterators:");
val charIter = chars.iterator();
val stringIter = strings.iterator();
val intIter = ints.iterator();
while (True) {
StringBuffer buf = new StringBuffer();
if (Char ch := charIter.next()) {
buf.add(ch);
}
if (String s := stringIter.next()) {
s.appendTo(buf);
}
if (Int n := intIter.next()) {
n.appendTo(buf);
}
if (buf.size == 0) {
break;
}
console.print(buf);
}
}
}
</syntaxhighlight>
 
{{out}}
<pre>
Using array indexing:
aA1
bB2
cC3
 
Using array iterators:
aA1
bB2
cC3
</pre>
 
=={{header|Efene}}==
Line 1,345 ⟶ 1,753:
 
=={{header|Elena}}==
ELENA 56.0x :
<syntaxhighlight lang="elena">import system'routines;
import extensions;
Line 1,355 ⟶ 1,763:
var a3 := new int[]{1,2,3};
for(int i := 0,; i < a1.Length,; i += 1)
{
console.printLine(a1[i], a2[i], a3[i])
Line 1,375 ⟶ 1,783:
.zipBy(a3, (first,second => first + second.toString() ));
zipped.forEach::(e)
{ console.writeLine:e };
Line 1,564 ⟶ 1,972:
 
If instead of reading the action had been to store a value into the array, then in the absence of bound checking, arbitrary damage will be done (to code or data) that will possibly result in something going wrong. And if you're lucky, it will happen swiftly.
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Function min(x As Integer, y As Integer) As Integer
Return IIf(x < y, x, y)
End Function
 
Dim arr1(1 To 3) As String = {"a", "b", "c"}
Dim arr2(1 To 3) As String = {"A", "B", "C"}
Dim arr3(1 To 3) As Integer = {1, 2, 3}
 
For i As Integer = 1 To 3
Print arr1(i) & arr2(i) & arr3(i)
Next
 
Print
 
' For arrays of different lengths we would need to iterate up to the mimimm length of all 3 in order
' to get a contribution from each one. For example:
 
Dim arr4(1 To 4) As String = {"A", "B", "C", "D"}
Dim arr5(1 To 2) As Integer = {1, 2}
 
Dim ub As Integer = min(UBound(arr1), min(UBound(arr4), UBound(arr5)))
For i As Integer = 1 To ub
Print arr1(i) & arr2(i) & arr3(i)
Next
 
Print
Sleep</syntaxhighlight>
 
{{out}}
<pre>
aA1
bB2
cC3
 
aA1
bB2
</pre>
 
=={{header|Frink}}==
Line 1,628 ⟶ 1,995:
</pre>
 
=={{header|GambasFutureBasic}}==
<syntaxhighlight lang="futurebasic">
'''[https://gambas-playground.proko.eu/?gist=3a69e733694aeab3b72c6a5c0316535b Click this link to run this code]'''
void local fn DoIt
<syntaxhighlight lang="gambas">Public Sub Main()
Dim a1 AsCFArrayRef String[]a1 = @[@"a", @"b", @"c"]
Dim a2 AsCFArrayRef String[]a2 = @[@"A", @"B", @"C"]
Dim a3 AsCFArrayRef String[]a3 = @[@"1", @"2", @"3"]
Dim siC As Short
long i, count = len(a1)
for i = 0 to count - 1
print a1[i]a2[i]a3[i]
next
end fn
 
fn DoIt
For siC = 0 To a1.Max
Print a1[siC] & a2[siC] & a3[siC]
Next
 
HandleEvents
End</syntaxhighlight>
</syntaxhighlight>
 
{{output}}
Output:
<pre>
aA1
bB2
Cc3
cC3
</pre>
 
Line 1,686 ⟶ 2,056:
bD1
aE2</syntaxhighlight>
 
=={{header|GDScript}}==
{{works with|Godot|4.0.1}}
 
<syntaxhighlight lang="gdscript">
extends MainLoop
 
# Implementation of zip, same length as the shortest array
func zip(lists: Array[Array]) -> Array[Array]:
var length: int = lists.map(func(arr): return len(arr)).reduce(func(a,b): return min(a,b))
var result: Array[Array] = []
result.resize(length)
for i in length:
result[i] = lists.map(func(arr): return arr[i])
return result
 
func _process(_delta: float) -> bool:
var a: Array[String] = ["a", "b", "c"]
var b: Array[String] = ["A", "B", "C"]
var c: Array[String] = ["1", "2", "3"]
 
for column in zip([a,b,c]):
print(''.join(column))
return true # Exit
</syntaxhighlight>
 
=={{header|Go}}==
Line 1,769 ⟶ 2,164:
 
<syntaxhighlight lang="haskell">{-# LANGUAGE ParallelListComp #-}
 
main = sequence [ putStrLn [x, y, z] | x <- "abd" | y <- "ABC" | z <- "123"]</syntaxhighlight>
main :: IO [()]
main =
sequence
[ putStrLn [x, y, z]
| x <- "abc"
| y <- "ABC"
| z <- "123"
]</syntaxhighlight>
 
'''Using Transpose'''
Line 1,776 ⟶ 2,179:
 
<syntaxhighlight lang="haskell">import Data.List
main = mapM putStrLn $ transpose ["abdabc", "ABC", "123"]</syntaxhighlight>
 
'''Using ZipWith*'''
Line 1,788 ⟶ 2,191:
<syntaxhighlight lang="haskell">import Control.Applicative (ZipList (ZipList, getZipList))
 
main :: IO [()]
main =
sequencemapM_ putStrLn $
getZipList $
( (\x y z -> putStrLn [x, y, z])
<$> ZipList "abdabc"
<*> ZipList "ABC"
<*> ZipList "123"</syntaxhighlight>
)
<> getZipList
( (\w x y z -> [w, x, y, z])
<$> ZipList "abcd"
<*> ZipList "ABCD"
<*> ZipList "1234"
<*> ZipList "一二三四"
)</syntaxhighlight>
{{Out}}
<pre>aA1
bB2
cC3
aA1一
bB2二
cC3三
dD4四</pre>
 
=={{header|Haxe}}==
Line 1,858 ⟶ 2,277:
[http://www.cs.arizona.edu/icon/library/procs/numbers.htm Uses max from
numbers]
 
=={{header|Insitux}}==
 
{{Trans|Clojure}}
 
<syntaxhighlight lang="insitux">(map str "abc" "ABC" "123")
["aA1" "bB2" "cC3"]</syntaxhighlight>
 
<syntaxhighlight lang="insitux">(map str ["a" "b" "c"] ["A" "B" "C"] ["1" "2" "3"])
["aA1" "bB2" "cC3"]</syntaxhighlight>
 
=={{header|J}}==
Since J's primitives are designed for handling what some programmers might think of as "an array monad" of arbitrary rank, a natural approach would be to concatenate the multiple arrays into a single array. In many cases we would already have done so to pass these arrays as an argument to some user defined routine. So, let's first see how that could look:
For arrays of different types:
<syntaxhighlight lang="j"> ,.&:(":"0@>)/ 'abc' ; 'ABC' ; 1 2 3
Line 1,908 ⟶ 2,339:
(An "empty box" is what a programmer in another language might call
"a pointer to a zero length array".)
 
That said, it's also worth noting that a single explicit loop could also be used here. For example,
 
<syntaxhighlight lang=J>
charcols=: {{
'one two three'=. y
for_a. one do.
echo a,(a_index{two),":a_index{three
end.
}}
 
charcols 'abc';'ABC';1 2 3
aA1
bB2
cC3</syntaxhighlight>
 
=={{header|Java}}==
Line 2,228 ⟶ 2,674:
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scalakotlin">//import version 1kotlin.0comparisons.6minOf
 
fun main(args: Array<String>) {
val a1 = charArrayOf('a', 'b', 'c')
val a2 = charArrayOf('A', 'B', 'C')
val a3 = intArrayOf(1, 2, 3)
for (i in 0 .. 2) println("${a1[i]}${a2[i]}${a3[i]}")
println()
// For arrays of different sizes, we wouldcan need toonly iterate up to the mimimm size of all 3the insmallest orderarray.
// to get a contribution from each one.
val a4 = intArrayOf(4, 5, 6, 7)
val a5 = charArrayOf('d', 'e')
val minSize = Math.minminOf(a2.size, Math.min(a4.size, a5.size)) // minimum size of a2, a4 and a5
for (i in 0 until minSize) println("${a2[i]}${a4[i]}${a5[i]}")
}</syntaxhighlight>
 
Line 2,309 ⟶ 2,754:
s
</syntaxhighlight>
 
=={{header|Lang}}==
<syntaxhighlight lang="lang">
$a $= [a, b, c] # Char values
$b $= [A\e, B\e, C\e] # Text values
$c $= [1, 2, 3] # Int values
 
# Repeat loop
$i
repeat($[i], @$a) {
fn.println(parser.op($a[$i] ||| $b[$i] ||| $c[$i]))
}
fn.println()
 
# Foreach loop with zip and reduce
$ele
foreach($[ele], fn.arrayZip($a, $b, $c)) {
fn.println(fn.arrayReduce($ele, \e, fn.concat))
}
fn.println()
 
# Foreach function with combinator
fn.arrayForEach(fn.arrayZip($a, $b, $c), fn.combB(fn.println, fn.combC3(fn.arrayReduce, fn.concat, \e)))
</syntaxhighlight>
 
{{out}}
<pre>
aA1
bB2
cC3
 
aA1
bB2
cC3
 
aA1
bB2
cC3
</pre>
 
=={{header|LFE}}==
Line 2,330 ⟶ 2,814:
function with something like <code lisp>(: lists map
...)</code>.
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">a$(1)="a" : a$(2)="b" : a$(3)="c"
b$(1)="A" : b$(2)="B" : b$(3)="C"
c(1)=1 : c(2)=2 : c(3)=3
 
 
for i = 1 to 3
print a$(i);b$(i);c(i)
next</syntaxhighlight>
 
=={{header|Lisaac}}==
Line 2,443 ⟶ 2,917:
for u, v, w in iter(a1, a2, a3) do print(u..v..w) end
</syntaxhighlight>
=={{header|M2000 Interpreter}}==
While End While can used for iterator type objects. We can use comma to use more than one iterator, or we can use folded While End While. When we use comma the iteration end when any of the iterators before iterate get the false state (no other iteration allowed). So for this example in While End while it is like we use i1 and i2 and i3, but with a comma (this only apply to While structure - and While { } structure - without End While<sup>Superscript text. We can't use and operator because this return Boolean type always. Using the iterator at While we get the object, and Interpreter check if this is an iterator object and go on to advance to next item, or to break the loop. We can use i1^ to get the index of the iteration according to specific object.
 
<syntaxhighlight lang="m2000 interpreter">module Loop_over_multiple_arrays_simultaneously {
r1=("a","b","c",1,2,3,4,5)
r2=("A","B","C", 4)
r3=(1,2,3)
i1=each(r1)
i2=each(r2)
i3=each(r3)
while i1, i2, i3
print array(i1)+array(i2)+array(i3)
end while
}
Loop_over_multiple_arrays_simultaneously
</syntaxhighlight>
{{out}}
<pre> aA1
bB2
cC3</pre>
 
=={{header|Maple}}==
Line 2,471 ⟶ 2,965:
<syntaxhighlight lang="mathematica">MapThread[Print, {{"a", "b", "c"}, {"A", "B", "C"}, {1, 2, 3}}];</syntaxhighlight>
All arguments must be lists of the same length.
 
=={{header|Maxima}}==
<syntaxhighlight lang="maxima">
/* Function that loops over multiple arrays simultaneously depending on the list with less length */
lomas(L):=block(
minlen:lmin(map(length,L)),
makelist(makelist(L[i][j],i,1,length(L)),j,1,minlen))$
 
/* Test case */
lst:[[a,b,c],[A,B,C],[1,2,3]]$
lomas(lst);
</syntaxhighlight>
{{out}}
<pre>
[[a,A,1],[b,B,2],[c,C,3]]
</pre>
 
=={{header|Mercury}}==
Line 2,706 ⟶ 3,216:
for i in 0..2:
echo a[i], b[i], c[i]</syntaxhighlight>
 
=={{header|NS-HUBASIC}}==
<syntaxhighlight lang="ns-hubasic">10 DIM A$(3)
20 DIM B$(3)
30 DIM C$(3)
40 A$(1)="THIS"
50 A$(2)=" LOOPS"
60 A$(3)=" ARRAYS"
70 B$(1)=" NS-HUBASIC"
80 B$(2)=" OVER"
90 B$(3)=" AT"
100 C$(1)=" PROGRAM"
110 C$(2)=" MULTIPLE"
120 C$(3)=" ONCE."
130 FOR I=1 TO 3
140 PRINT A$(I)B$(I)C$(I)
150 NEXT</syntaxhighlight>
 
=={{header|Oberon-2}}==
Line 3,069 ⟶ 3,562:
[[/a /b /c] [/A /B /C] [1 2 3]] transpose
</syntaxhighlight>
 
=={{header|PowerBASIC}}==
<syntaxhighlight lang="powerbasic">FUNCTION PBMAIN () AS LONG
DIM x(2), y(2) AS STRING * 1
DIM z(2) AS LONG
 
'data
ARRAY ASSIGN x() = ("a", "b", "c")
ARRAY ASSIGN y() = ("A", "B", "C")
ARRAY ASSIGN z() = (1, 2, 3)
 
'set upper bound
C& = UBOUND(x)
IF UBOUND(y) > C& THEN C& = UBOUND(y)
IF UBOUND(z) > C& THEN C& = UBOUND(z)
 
OPEN "output.txt" FOR OUTPUT AS 1
FOR L& = 0 TO C&
IF L& <= UBOUND(x) THEN PRINT #1, x(L&);
IF L& <= UBOUND(y) THEN PRINT #1, y(L&);
IF L& <= UBOUND(z) THEN PRINT #1, TRIM$(STR$(z(L&)));
PRINT #1,
NEXT
CLOSE
END FUNCTION</syntaxhighlight>
 
=={{header|PowerShell}}==
Line 3,150 ⟶ 3,618:
false.
</pre>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">OpenConsole()
; Fill arrays
Dim a.s(2)
Dim b.s(2)
Dim c(2)
For Arrayposition = 0 To ArraySize(a())
a(Arrayposition) = Chr(Asc("a") + Arrayposition)
b(Arrayposition) = Chr(Asc("A") + Arrayposition)
c(Arrayposition) = Arrayposition + 1
Next
; loop over them
For Arrayposition = 0 To ArraySize(a())
PrintN(a(Arrayposition) + b(Arrayposition) + Str(c(Arrayposition)))
Next
Input() ;wait for Enter before ending</syntaxhighlight>
 
If they have different lengths there are two cases:<br>
a() is the shortest one: Only elements up to maximum index of a() are
printed <br>
a() is bigger than another one: if exceeding index to much, program
crashes, <br>
else it may work because there is some "free space" after end of
assigned array memory. <br>
For example if a has size 4, line dD4 will also be printed. size 20
leads to an crash <br>
This is because ReDim becomes slow if everytime there is a change to
array size new memory has to be allocated.
 
=={{header|Python}}==
Line 3,450 ⟶ 3,889:
next
</syntaxhighlight>
 
=={{header|RPL}}==
===1993+ versions===
≪ 3 ≪ + + ≫ DOLIST
OBJ→ DROP
≫ '<span style="color:blue">CONCAT3</span>' STO
 
{ "a" "b" "c" } { "A" "B" "C" } { "1" "2" "3" } <span style="color:blue">CONCAT3</span>
{{out}}
<pre>
3: "aA1"
2: "bB2"
1: "cC3"
</pre>
===Older versions===
≪ → a b c
≪ 1 a SIZE '''FOR''' j
a j GET b j GET c j GET + +
'''NEXT'''
≫ ≫'<span style="color:blue">CONCAT3</span>' STO
 
=={{header|Ruby}}==
Line 3,468 ⟶ 3,927:
irb(main):002:0> ['a','b','c'].zip(['A','B'], [1,2,3,4])
=> [["a", "A", 1], ["b", "B", 2], ["c", nil, 3]]</syntaxhighlight>
 
=={{header|Run BASIC}}==
<syntaxhighlight lang="runbasic">for i = 1 to 3
a$(i) = chr$(i+96)
b$(i) = chr$(i+64)
c(i) = i
next i
 
for i = 1 to 3
print a$(i);b$(i);c(i)
next</syntaxhighlight>
 
=={{header|Rust}}==
Line 3,670 ⟶ 4,118:
 
1) concatenation of integer objects as shown above may require a change in the <tt>,</tt> (comma) implementation, to send "asString" to the argument.
 
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
 
pragma annotate( summary, "arrayloop" )
@( description, "Loop over multiple arrays simultaneously" )
@( category, "tutorials" )
@( author, "Ken O. Burtch" )
@( see_also, "http://rosettacode.org/wiki/Loop_over_multiple_arrays_simultaneously" );
pragma license( unrestricted );
 
pragma software_model( nonstandard );
pragma restriction( no_external_commands );
 
procedure arrayloop is
a1 : constant array( 1..3 ) of character := ('a', 'b', 'c');
a2 : constant array( 1..3 ) of character := ('A', 'B', 'C');
a3 : constant array( 1..3 ) of integer := (1, 2, 3);
begin
for i in arrays.first( a1 )..arrays.last( a1 ) loop
put( a1( i ) )
@( a2( i ) )
@( strings.trim( strings.image( a3( i ) ), trim_end.both ) );
new_line;
end loop;
end arrayloop;</syntaxhighlight>
 
=={{header|Standard ML}}==
Line 4,113 ⟶ 4,588:
stdout.printf("%c%c%i\n", a1[i], a2[i], a3[i]);
}</syntaxhighlight>
 
=={{header|VBA}}==
{{works with|VBA|VBA Excel 2013}}
<syntaxhighlight lang="vb">' Loop over multiple arrays simultaneously - VBA - 08/02/2021
 
Sub Main()
a = Array("a","b","c")
b = Array("A","B","C")
c = Array(1,2,3)
For i = LBound(a) To UBound(a)
buf = buf & vbCrLf & a(i) & b(i) & c(i)
Next
Debug.Print Mid(buf,3)
End Sub </syntaxhighlight>
{{out}}
<pre>
aA1
bB2
cC3
</pre>
 
=={{header|VBScript}}==
Line 4,151 ⟶ 4,606:
</pre>
 
=={{header|VBA}}==
{{works with|VBA|VBA Excel 2013}}
<syntaxhighlight lang="vb">' Loop over multiple arrays simultaneously - VBA - 08/02/2021
 
Sub Main()
=={{header|Visual Basic .NET}}==
a = Array("a","b","c")
Two implementations: one determines the shortest of the arrays and uses a simple For loop with element accesses to each array separately; one uses Enumerable.Zip (which can only zip two sequences at once) twice to create 3-tuples. Enumerable.Zip stops when either source runs out of elements, so the behavior of the two implementations is identical for arrays of different lengths.
b = Array("A","B","C")
<syntaxhighlight lang="vbnet">
c = Array(1,2,3)
Module Program
For i = LBound(a) SubTo MainUBound(a)
buf = buf & vbCrLf Dim& a(i) As& Charb(i) =& {"a"c, "b"c, "c"c}(i)
Next
Dim b As Char() = {"A"c, "B"c, "C"c}
Debug.Print Mid(buf,3)
Dim c As Integer() = {1, 2, 3}
End Sub </syntaxhighlight>
 
Dim minLength = {a.Length, b.Length, c.Length}.Min()
For i = 0 To minLength - 1
Console.WriteLine(a(i) & b(i) & c(i))
Next
 
Console.WriteLine()
 
For Each el As (a As Char, b As Char, c As Integer) In a.Zip(b, Function(l, r) (l, r)).Zip(c, Function(x, r) (x.l, x.r, r))
Console.WriteLine(el.a & el.b & el.c)
Next
End Sub
End Module</syntaxhighlight>
 
{{out}}
<pre>aA1
aA1
bB2
cC3
</pre>
 
aA1
bB2
cC3</pre>
 
=={{header|Visual FoxPro}}==
Line 4,238 ⟶ 4,681:
</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">fn main() {
arrays := [['a','b','c'],['A','B','C'],['1','2','3']]
for i in 0..arrays[0].len {
Line 4,252 ⟶ 4,695:
=={{header|Wren}}==
The following script will work as expected provided the lengths of a1 and a2 are at least equal to the length of a3. Otherwise it will produce a 'Subscript out of bounds' error.
<syntaxhighlight lang="ecmascriptwren">var a1 = ["a", "b", "c"]
var a2 = ["A", "B", "C"]
var a3 = [1, 2, 3]
Line 4,319 ⟶ 4,762:
xor eax, eax
ret
</syntaxhighlight>
 
=={{header|XBasic}}==
{{works with|Windows XBasic}}
<syntaxhighlight lang="xbasic">' Loop over multiple arrays simultaneously
PROGRAM "loopoverarrays"
 
DECLARE FUNCTION Entry()
 
FUNCTION Entry()
DIM arr1$[2], arr2$[2], arr3%[2]
arr1$[0] = "a": arr1$[1] = "b": arr1$[2] = "c"
arr2$[0] = "A": arr2$[1] = "B": arr2$[2] = "C"
arr3%[0] = 1: arr3%[1] = 2: arr3%[2] = 3
FOR i% = 0 TO 2
PRINT arr1$[i%]; arr2$[i%]; FORMAT$("#", arr3%[i%])
NEXT i%
END FUNCTION
END PROGRAM
</syntaxhighlight>
 
Line 4,420 ⟶ 4,844:
 
=={{header|Zig}}==
 
===Limit by minimum length===
'''Works with''': 0.10.x
 
<syntaxhighlight lang="zig">const std = @import("std");
 
const a1: []const u8arr1 = &[_]u8{ 'a', 'b', 'c' };
const a2: []const u8arr2 = &[_]u8{ 'A', 'B', 'C' };
const a3: []const u8arr3 = &[_]u8{ '1', '2', '3' };
 
pub fn main() std.fs.File.WriteError!void {
const stdout = std.io.getStdOut();
for (a1) |_, i|
const stdout_w = stdout.writer();
try std.io.getStdOut().writer().print("{c} {c} {d}\n", .{ a1[i], a2[i], a3[i] });
const n = std.math.min3(arr1.len, arr2.len, arr3.len);
for (arr1[0..n]) |arr1_e, i| {
try stdout_w.print("{c} {c} {c}\n", .{ arr1_e, arr2[i], arr3[i] });
}
}</syntaxhighlight>
 
'''Works with''': 0.11.x, 0.12.0-dev.1381+61861ef39
=={{header|ZX Spectrum Basic}}==
 
<syntaxhighlight lang="zxbasiczig">10const LET szastd = 3: REM size of a@import("std");
20 LET szb = 3: REM size of b
30 LET szc = 3: REM size of c
40 DIM a$(sza): DIM b$(szb): DIM c$(szc)
50 LET max = sza: REM assume a is the biggest
60 IF szb > max THEN LET max = szb: REM now try b
70 IF szc > max THEN LET max = szc: REM or c
80 REM populate our arrays, and as a bonus we already have our demo loop
90 REM we might as well print as we populate showing the arrays in
columns
100 FOR l = 1 TO max
110 IF l <= sza THEN READ a$(l): PRINT a$(l);
120 IF l <= szb THEN READ b$(l): PRINT b$(l);
130 IF l <= szc THEN READ c$(l): PRINT c$(l);
140 PRINT: REM newline
150 NEXT l
150 PRINT "The arrays are shown in columns."
160 PRINT "A$ runs down the left hand side,"
170 PRINT "and C$ runs down the right."
180 STOP
200 DATA "a","b","c","A","B","C","1","2","3"</syntaxhighlight>
 
const arr1 = [_]u8{ 'a', 'b', 'c' };
Simplification
const arr2 = [_]u8{ 'A', 'B', 'C' };
const arr3 = [_]u8{ '1', '2', '3' };
 
pub fn main() std.fs.File.WriteError!void {
<syntaxhighlight lang="zxbasic">10 READ size: DIM a$(size): DIM b$(size): DIM c$(size)
const stdout = std.io.getStdOut();
20 FOR i=1 TO size
const stdout_w = stdout.writer();
30 READ a$(i),b$(i),c$(i)
const n = @min(arr1.len, arr2.len, arr3.len);
40 PRINT a$(i);b$(i);c$(i)
for (arr1[0..n], arr2[0..n], arr3[0..n]) |arr1_e, arr2_e, arr3_e| {
50 NEXT i
try stdout_w.print("{c} {c} {c}\n", .{ arr1_e, arr2_e, arr3_e });
60 DATA 3,"a","A","1","b","B","2","c","C","3"</syntaxhighlight>
}
}</syntaxhighlight>
 
===Limit by length of first array===
'''Works with''': 0.10.x
 
This example will print up-to arr1 length (asserts that other arrays are at least that long).
<syntaxhighlight lang="zig">const std = @import("std");
 
const arr1 = [_]u8{ 'a', 'b', 'c' };
const arr2 = [_]u8{ 'A', 'B', 'C' };
const arr3 = [_]u8{ '1', '2', '3' };
 
pub fn main() std.fs.File.WriteError!void {
const stdout = std.io.getStdOut();
const stdout_w = stdout.writer();
for (arr1) |arr1_e, i| {
try stdout_w.print("{c} {c} {c}\n", .{ arr1_e, arr2[i], arr3[i] });
}
}</syntaxhighlight>
 
'''Works with''': 0.11.x, 0.12.0-dev.1381+61861ef39
 
<syntaxhighlight lang="zig">const std = @import("std");
 
const arr1 = [_]u8{ 'a', 'b', 'c' };
const arr2 = [_]u8{ 'A', 'B', 'C' };
const arr3 = [_]u8{ '1', '2', '3' };
 
pub fn main() std.fs.File.WriteError!void {
const stdout = std.io.getStdOut();
const stdout_w = stdout.writer();
for (arr1, 0..) |arr1_e, i| {
try stdout_w.print("{c} {c} {c}\n", .{ arr1_e, arr2[i], arr3[i] });
}
}</syntaxhighlight>
 
===Assert that arrays have equal length===
'''Works with''': 0.11.x, 0.12.0-dev.1381+61861ef39
 
This example will print up-to arr1 length (asserts that other arrays are exactly that long => asserts that lengths are equal).
<syntaxhighlight lang="zig">const std = @import("std");
 
const arr1 = [_]u8{ 'a', 'b', 'c' };
const arr2 = [_]u8{ 'A', 'B', 'C' };
const arr3 = [_]u8{ '1', '2', '3' };
 
pub fn main() std.fs.File.WriteError!void {
const stdout = std.io.getStdOut();
const stdout_w = stdout.writer();
for (arr1, arr2, arr3) |arr1_e, arr2_e, arr3_e| {
try stdout_w.print("{c} {c} {c}\n", .{ arr1_e, arr2_e, arr3_e });
}
}</syntaxhighlight>
Anonymous user