Loop over multiple arrays simultaneously: Difference between revisions

m
imported>Arakov
 
(44 intermediate revisions by 24 users not shown)
Line 41:
 
=={{header|11l}}==
<langsyntaxhighlight lang="11l">L(x, y, z) zip(‘abc’, ‘ABC’, ‘123’)
print(x‘’y‘’z)</langsyntaxhighlight>
 
{{out}}
Line 52:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Loop over multiple arrays simultaneously 09/03/2017
LOOPSIM CSECT
USING LOOPSIM,R12 base register
Line 75:
PG DC CL80' ' buffer
YREGS
END LOOPSIM</langsyntaxhighlight>
{{out}}
<pre>
Line 103:
and if they are not, it will simply read from the wrong addresses.
 
<langsyntaxhighlight lang="8080asm"> org 100h
lxi b,0 ; Let (B)C be the array index
outer: lxi d,As ; Use DE to walk the array-of-arrays
Line 148:
Alen: equ $-A3
;;; Zero-terminated array-of-arrays
As: dw A1,A2,A3,0</langsyntaxhighlight>
 
{{out}}
Line 170:
base addresses of the arrays into <code>bx</code> one by one.
 
<langsyntaxhighlight lang="asm"> cpu 8086
bits 16
org 100h
Line 200:
;;; Array of arrays
As: dw A1,A2,A3
Aslen: equ ($-As)/2 ; Length of array of arrays (in words)</langsyntaxhighlight>
 
 
Line 212:
 
=={{header|ACL2}}==
<langsyntaxhighlight Lisplang="lisp">(defun print-lists (xs ys zs)
(if (or (endp xs) (endp ys) (endp zs))
nil
Line 223:
(rest zs)))))
 
(print-lists '("a" "b" "c") '(A B C) '(1 2 3))</langsyntaxhighlight>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC Main()
CHAR ARRAY a="abc",b="ABC"
BYTE ARRAY c=[1 2 3]
Line 235:
PrintF("%C%C%B%E",a(i+1),b(i+1),c(i))
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Loop_over_multiple_arrays_simultaneously.png Screenshot from Atari 8-bit computer]
Line 245:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
 
procedure Array_Loop_Test is
Line 257:
(Index))(2));
end loop;
end Array_Loop_Test;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 271:
 
1.8-8d] - due to extensive use of '''format'''[ted] ''transput''}}
<langsyntaxhighlight lang="algol68">[]UNION(CHAR,INT) x=("a","b","c"), y=("A","B","C"),
z=(1,2,3);
FOR i TO UPB x DO
printf(($ggd$, x[i], y[i], z[i], $l$))
OD</langsyntaxhighlight>
{{out}}
<pre>
Line 284:
 
=={{header|ALGOL W}}==
<langsyntaxhighlight lang="algolw">begin
% declare the three arrays %
string(1) array a, b ( 1 :: 3 );
Line 294:
% loop over the arrays %
for i := 1 until 3 do write( i_w := 1, s_w := 0, a(i), b(i), c(i) );
end. </langsyntaxhighlight>
 
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 307 ⟶ 357:
vectors, zeroes for numeric vectors) to match the longest vector.
 
<syntaxhighlight lang APL="apl">f ← ↓∘⍉∘↑</langsyntaxhighlight>
 
{{out}}
Line 323 ⟶ 373:
If we have a generic Applescript '''map''' function, we can use it to write a generic '''zipListsWith''', which applies a given function over lists derived from the nth members of an arbitrary list of (equal-length) lists. (Where lists are of uneven length, items beyond the maximum shared length are ignored).
 
<langsyntaxhighlight AppleScriptlang="applescript">-- ZIP LISTS WITH FUNCTION ---------------------------------------------------
 
-- zipListsWith :: ([a] -> b) -> [[a]] -> [[b]]
Line 413 ⟶ 463:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<pre>aA1
Line 421 ⟶ 471:
But a transpose function might be simpler:
 
<langsyntaxhighlight Applescriptlang="applescript">-- CONCAT MAPPED OVER A TRANSPOSITION ----------------------------------------
on run
Line 495 ⟶ 545:
on unlines(xs)
intercalate(linefeed, xs)
end unlines</langsyntaxhighlight>
{{Out}}
<pre>aA1
Line 503 ⟶ 553:
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">parts: ["abc" "ABC" [1 2 3]]
 
loop 0..2 'x ->
print ~"|parts\0\[x]||parts\1\[x]||parts\2\[x]|"</langsyntaxhighlight>
 
{{out}}
Line 518 ⟶ 568:
[http://www.autohotkey.com/docs/commands/StringSplit.htm StringSplit]
creates a pseudo-array
<langsyntaxhighlight lang="autohotkey">List1 = a,b,c
List2 = A,B,C
List3 = 1,2,3
Line 543 ⟶ 593:
Result .= List1_%A_Index% List2_%A_Index% List3_%A_Index% "`n"
Return, Result
}</langsyntaxhighlight>
An array that is too short on creation will return empty strings when
trying to retrieve further elements. The 2nd Message box shows:
Line 556 ⟶ 606:
([http://l.autohotkey.com/docs/Objects.htm Objects]) and the
[http://l.autohotkey.net/docs/commands/For.htm For loop].
<langsyntaxhighlight AHKlang="ahk">List1 := ["a", "b", "c"]
List2 := ["A", "B", "C"]
List3 := [ 1 , 2 , 3 ]
Line 572 ⟶ 622:
Result .= value . List2[key] . List3[key] "`n"
Return, Result
}</langsyntaxhighlight>
The output from this script is identical to the first one.
 
=={{header|AWK}}==
<langsyntaxhighlight lang="awk">BEGIN {
split("a,b,c", a, ",");
split("A,B,C", b, ",");
Line 584 ⟶ 634:
print a[i] b[i] c[i];
}
}</langsyntaxhighlight>
 
=={{header|Axe}}==
Line 590 ⟶ 640:
L₃ for simplicity. In practice, one would want to arrange the arrays to
all fit within L₁ to avoid volatility issues with L₂ and L₃.
<langsyntaxhighlight lang="axe">'a'→{L₁}
'b'→{L₁+1}
'c'→{L₁+2}
Line 601 ⟶ 651:
For(I,0,2)
Disp {L₁+I}►Char,{L₂+I}►Char,{L₃+I}►Dec,i
End</langsyntaxhighlight>
 
=={{header|Babel}}==
Line 607 ⟶ 657:
First, you could transpose the lists:
 
<langsyntaxhighlight lang="babel">main: { (('a' 'b' 'c')('A' 'B' 'C')('1' '2' '3'))
simul_array }
 
simul_array!:
{ trans
{ { << } each "\n" << } each }</langsyntaxhighlight>
 
The 'trans' operator substitutes nil in the portions of each transposed
Line 624 ⟶ 674:
each list using a user-defined cdrall operator:
 
<langsyntaxhighlight lang="babel">main: { (('a' 'b' 'c')('A' 'B' 'C')('1' '2' '3'))
simul_array }
 
Line 642 ⟶ 692:
{ zap 0 last }
{ nil }
if} each }</langsyntaxhighlight>
 
This solution is formally identical to the first and will handle lists
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
<lang freebasic>
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
DECLARE a2$[] = {"A", "B", "C"} TYPE STRING
Line 662 ⟶ 722:
INCR i
WEND
</langsyntaxhighlight>
 
==={{header|BASIC256}}===
<syntaxhighlight lang="basic">arraybase 1
=={{header|BASIC256}}==
dim arr1$(3) : arr1$ = {"a", "b", "c"}
{{trans|FreeBASIC}}
<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</lang>
{{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}
<lang bbcbasic> DIM array1$(2), array2$(2), array3%(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"
array2$() = "A", "B", "C"
Line 691 ⟶ 762:
FOR index% = 0 TO 2
PRINT array1$(index%) ; array2$(index%) ; array3%(index%)
NEXT</langsyntaxhighlight>
 
==={{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}}==
This solution accounts for arrays of varying lengths, and if they are interspersed with undefined characters by replacing them with spaces.
<langsyntaxhighlight Beadslang="beads">beads 1 program 'Loop over multiple arrays simultaneously'
calc main_init
const
Line 703 ⟶ 1,046:
const largest = max(tree_hi(x), tree_hi(y), tree_hi(z))
loop reps:largest count:i //where u_cc defines what to use for undefined characters
log to_str(x[i], u_cc:' ') & to_str(y[i], u_cc:' ') & to_str(z[i], u_cc:' ')</langsyntaxhighlight>
{{out}}
<pre>aA1
Line 714 ⟶ 1,057:
For arrays of differing lengths, you'd need to manually check for an out-of-range index and deal with it appropriately.
 
<langsyntaxhighlight lang="befunge">0 >:2g,:3g,:4gv
@_^#`2:+1,+55,<
abc
ABC
123</langsyntaxhighlight>
 
=={{header|C}}==
Line 727 ⟶ 1,070:
application-specific way.
 
<langsyntaxhighlight lang="c">#include <stdio.h>
 
char a1[] = {'a','b','c'};
Line 737 ⟶ 1,080:
printf("%c%c%i\n", a1[i], a2[i], a3[i]);
}
}</langsyntaxhighlight>
 
(Note: Some compilers may require a flag to accept this modern C code,
Line 750 ⟶ 1,093:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang="csharp">class Program
{
static void Main(string[] args)
Line 762 ⟶ 1,105:
Console.WriteLine("{0}{1}{2}", a[i], b[i], c[i]);
}
}</langsyntaxhighlight>
 
 
Using Enumerable.Zip (stops when either source runs out of elements):
 
<langsyntaxhighlight lang="csharp">
int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };
Line 773 ⟶ 1,116:
second));
 
</syntaxhighlight>
</lang>
 
 
Like how a perl programmer would write it (still using Zip):
 
<langsyntaxhighlight lang="csharp">
Console.WriteLine((new[] { 1, 2, 3, 4 }).Zip(new[] { "a", "b", "c" },
(f, s) => f + " " + s));
</syntaxhighlight>
</lang>
 
 
Custom implementation for arrays of different lengths that pads with spaces after the end of the shorter arrays:
<langsyntaxhighlight lang="csharp">
public static void Multiloop(char[] A, char[] B, int[] C)
{
Line 792 ⟶ 1,135:
Console.WriteLine($"{(i < A.Length ? A[i] : ' ')}, {(i < B.Length ? B[i] : ' ')}, {(i < C.Length ? C[i] : ' ')}");
}
</syntaxhighlight>
</lang>
usage:
<langsyntaxhighlight lang="csharp">Multiloop(new char[] { 'a', 'b', 'c', 'd' }, new char[] { 'A', 'B', 'C' }, new int[] { 1, 2, 3, 4, 5 });</langsyntaxhighlight>
 
=={{header|C++}}==
With <code>std::vector</code>s:
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <vector>
 
Line 816 ⟶ 1,159:
std::cout << *lIt << *uIt << *nIt << "\n";
}
}</langsyntaxhighlight>
 
Using static arrays:
<langsyntaxhighlight lang="cpp">#include <iostream>
 
int main(int argc, char* argv[])
Line 835 ⟶ 1,178:
"\n";
}
}</langsyntaxhighlight>
 
===C++11===
With <code>std::vector</code>s:
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <vector>
 
Line 859 ⟶ 1,202:
std::cout << *ilow << *iup << *inum << "\n";
}
}</langsyntaxhighlight>
 
Using static arrays:
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <iterator>
 
Line 882 ⟶ 1,225:
std::cout << *ilow << *iup << *inum << "\n";
}
}</langsyntaxhighlight>
 
With <code>std::array</code>s:
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <array>
 
Line 905 ⟶ 1,248:
std::cout << *ilow << *iup << *inum << "\n";
}
}</langsyntaxhighlight>
 
With <code>std::array</code>s by indexes:
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <array>
#include <algorithm>
Line 930 ⟶ 1,273:
std::cout << lowers[i] << uppers[i] << nums[i] << "\n";
}
}</langsyntaxhighlight>
 
===C++23===
<syntaxhighlight lang="cpp">#include <array>
#include <ranges>
#include <format>
#include <iostream>
int main() {
auto a1 = std::array{"a", "b", "c"};
auto a2 = std::array{"A", "B", "C"};
auto a3 = std::array{1, 2, 3};
 
for(const auto& [x, y, z] : std::ranges::views::zip(a1, a2, a3))
{
std::cout << std::format("{}{}{}\n", x, y, z);
}
}</syntaxhighlight>
 
=={{header|Chapel}}==
 
<langsyntaxhighlight lang="chapel">var a1 = [ "a", "b", "c" ];
var a2 = [ "A", "B", "C" ];
var a3 = [ 1, 2, 3 ];
 
for (x,y,z) in zip(a1, a2, a3) do
writeln(x,y,z);</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(doseq [s (map #(str %1 %2 %3) "abc" "ABC" "123")]
(println s))</langsyntaxhighlight>
The sequence stops when the shortest list is exhausted.
 
 
<langsyntaxhighlight lang="clojure">
(apply map str ["abc" "ABC" "123"])
("aA1" "bB2" "cC3")
</syntaxhighlight>
</lang>
 
=={{header|COBOL}}==
<langsyntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. Loop-Over-Multiple-Tables.
 
Line 975 ⟶ 1,335:
 
GOBACK
.</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
 
=== Using functional application ===
<langsyntaxhighlight lang="lisp">(mapc (lambda (&rest args)
(format t "~{~A~}~%" args))
'(|a| |b| |c|)
'(a b c)
'(1 2 3))</langsyntaxhighlight>
If lists are different lengths, it stops after the shortest one.
 
=== Using LOOP ===
<langsyntaxhighlight lang="lisp">
(loop for x in '("a" "b" "c")
for y in '(a b c)
for z in '(1 2 3)
do (format t "~a~a~a~%" x y z))
</syntaxhighlight>
</lang>
 
=== Using DO ===
<langsyntaxhighlight lang="lisp">
(do ((x '("a" "b" "c") (rest x)) ;
(y '("A" "B" "C" "D") (rest y)) ;
Line 1,002 ⟶ 1,362:
((or (null x) (null y) (null z))) ; Break condition
(format t "~a~a~a~%" (first x) (first y) (first z))) ; On every loop print first elements
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,012 ⟶ 1,372:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.range;
 
void main () {
foreach (a, b, c; zip("abc", "ABC", [1, 2, 3]))
writeln(a, b, c);
}</langsyntaxhighlight>
{{out}}
<pre>aA1
Line 1,025 ⟶ 1,385:
On default it stops when the shortest range is exhausted
(same as StoppingPolicy.shortest):
<langsyntaxhighlight lang="d">import std.stdio, std.range;
 
void main () {
Line 1,045 ⟶ 1,405:
foreach (p; zip(sp.requireSameLength, a1, a2))
writeln(p.tupleof);
}</langsyntaxhighlight>
{{out}}
<pre>11
Line 1,060 ⟶ 1,420:
 
There is also std.range.lockstep:
<langsyntaxhighlight lang="d">import std.stdio, std.range;
 
void main() {
Line 1,074 ⟶ 1,434:
foreach (index, a, b; lockstep(arr1, arr2))
writefln("Index %s: a = %s, b = %s", index, a, b);
}</langsyntaxhighlight>
Lower level code that stops at the shortest length:
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
void main () {
Line 1,085 ⟶ 1,445:
foreach (i; 0 .. min(s1.length, s2.length, a1.length))
writeln(s1[i], s2[i], a1[i]);
}</langsyntaxhighlight>
{{out}}
<pre>aA1
Line 1,091 ⟶ 1,451:
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">program LoopOverArrays;
 
{$APPTYPE CONSOLE}
Line 1,108 ⟶ 1,468:
 
Readln;
end.</langsyntaxhighlight>
 
=={{header|Diego}}==
<syntaxhighlight lang ="diego">set namespaceset_namespace(rosettacode);
 
add_mat(myMatrix)_row(a,b,c)_row(A,B,C)_row(1,2,3);
add_var(output,columnArray);
 
with_mat(myMatrix)_foreach()_bycol()_var(columnArray)
Line 1,122 ⟶ 1,482:
me_msg([output]);
 
reset_namespace[];</langsyntaxhighlight>
 
Diego has no issue when arrays are of a different length, the "missing" array entries will be handled as empty. Note, the <code>matrix</code> will become a <code>clump</code>, but can still be treated as a <code>matrix</code>.
<syntaxhighlight lang ="diego">set nsset_ns(rosettacode);
 
add_clump(myClump)_row(a,b,c,d,e,f)_row(A,B,C,D,E,F)_row(-1,0,1,2,3); // The default spread is presumed to be 'origin'
add_var(output,columnArray);
 
with_clump(myClump)_foreach()_bycol()_var(columnArray)
with_var(output)_append()_flat([columnArray])_append(\n);
;
;
 
me_msg([output]);
 
reset_ns[];</langsyntaxhighlight>
{{out}}
<pre>
Line 1,143 ⟶ 1,503:
cC1
dD2
E3
e3
F
f
</pre>
 
Line 1,152 ⟶ 1,512:
element.
 
<langsyntaxhighlight lang="delphi">const a1 = ['a', 'b', 'c'];
const a2 = ['A', 'B', 'C'];
const a3 = [1, 2, 3];
Line 1,158 ⟶ 1,518:
var i : Integer;
for i := 0 to 2 do
PrintLn(Format('%s%s%d', [a1[i], a2[i], a3[i]]));</langsyntaxhighlight>
 
=={{header|E}}==
Line 1,167 ⟶ 1,527:
indexes as keys, so a not entirely awful idiom exists:
 
<langsyntaxhighlight lang="e">def a1 := ["a","b","c"]
def a2 := ["A","B","C"]
def a3 := ["1","2","3"]
Line 1,173 ⟶ 1,533:
for i => v1 in a1 {
println(v1, a2[i], a3[i])
}</langsyntaxhighlight>
 
This will obviously fail if a2 or a3 are shorter than a1, and omit items
Line 1,180 ⟶ 1,540:
Given a parallel iteration utility, we might write this:
 
<langsyntaxhighlight lang="e">for [v1, v2, v3] in zip(a1, a2, a3) {
println(v1, v2, v3)
}</langsyntaxhighlight>
 
<code>zip</code> cannot yet be defined for all collections
Line 1,192 ⟶ 1,552:
collections.
 
<langsyntaxhighlight lang="e">def zip {
to run(l1, l2) {
def zipped {
Line 1,219 ⟶ 1,579:
zipped
}
}</langsyntaxhighlight>
 
(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}}==
<langsyntaxhighlight lang="scheme">
;; looping over different sequences : infinite stream, string, list and vector
;; loop stops as soon a one sequence ends.
Line 1,239 ⟶ 1,609:
1004 "E" 4 s
1005 "F" 5 t
</syntaxhighlight>
</lang>
 
=={{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}}==
<langsyntaxhighlight lang="efene">@public
run = fn () {
lists.foreach(fn ((A, B, C)) { io.format("~s~n", [[A, B, C]]) },
lists.zip3("abc", "ABC", "123"))
}
</syntaxhighlight>
</lang>
 
If the lists are not all the same length, an error is thrown.
=={{header|Eiffel}}==
<langsyntaxhighlight lang="eiffel">
example (a_array: READABLE_INDEXABLE [BOUNDED [ANY]]): STRING
-- Assemble output for a 2-dim array in `a_array'
Line 1,286 ⟶ 1,711:
>>
end
</syntaxhighlight>
</lang>
{{out}}
aA1
Line 1,306 ⟶ 1,731:
=={{header|Ela}}==
 
<langsyntaxhighlight lang="ela">open monad io list imperative
xs = zipWith3 (\x y z -> show x ++ show y ++ show z) ['a','b','c']
Line 1,317 ⟶ 1,742:
return $ each print xss
 
print_and_calc xs ::: IO</langsyntaxhighlight>
 
The code above can be written shorter. First there is no need in lists
Line 1,324 ⟶ 1,749:
composition operator:
 
<langsyntaxhighlight lang="ela">xs = zipWith3 (\x -> (x++) >> (++)) "abc" "ABC"
"123"</langsyntaxhighlight>
 
=={{header|Elena}}==
ELENA 56.0x :
<langsyntaxhighlight lang="elena">import system'routines;
import extensions;
 
Line 1,338 ⟶ 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,344 ⟶ 1,769:
console.readChar()
}</langsyntaxhighlight>
 
Using zipBy extension:
<langsyntaxhighlight lang="elena">import system'routines.
import extensions.
 
Line 1,358 ⟶ 1,783:
.zipBy(a3, (first,second => first + second.toString() ));
zipped.forEach::(e)
{ console.writeLine:e };
console.readChar();
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,372 ⟶ 1,797:
=={{header|Elixir}}==
'''string list:'''
<langsyntaxhighlight lang="elixir">l1 = ["a", "b", "c"]
l2 = ["A", "B", "C"]
l3 = ["1", "2", "3"]
IO.inspect List.zip([l1,l2,l3]) |> Enum.map(fn x-> Tuple.to_list(x) |> Enum.join end)
#=> ["aA1", "bB2", "cC3"]</langsyntaxhighlight>
 
'''char_list:'''
<langsyntaxhighlight lang="elixir">l1 = 'abc'
l2 = 'ABC'
l3 = '123'
IO.inspect List.zip([l1,l2,l3]) |> Enum.map(fn x-> Tuple.to_list(x) end)
#=> ['aA1', 'bB2', 'cC3']</langsyntaxhighlight>
 
When the length of the list is different:
<langsyntaxhighlight lang="elixir">iex(1)> List.zip(['abc','ABCD','12345']) |> Enum.map(&Tuple.to_list(&1))
['aA1', 'bB2', 'cC3']
iex(2)> List.zip(['abcde','ABC','12']) |> Enum.map(&Tuple.to_list(&1))
['aA1', 'bB2']</langsyntaxhighlight>
The zipping finishes as soon as any enumerable completes.
 
=={{header|Erlang}}==
Shortest option:
<langsyntaxhighlight lang="erlang">lists:zipwith3(fun(A,B,C)->
io:format("~s~n",[[A,B,C]]) end, "abc", "ABC", "123").</langsyntaxhighlight>
However, as every expression in Erlang has to return something, printing text returns 'ok'. A list with as many 'ok's as there are lines printed will thus be created. The technically cleanest way to do things would be with
<tt>lists:foreach/2</tt>, which also guarantees evaluation
order:
<langsyntaxhighlight lang="erlang">lists:foreach(fun({A,B,C}) ->
io:format("~s~n",[[A,B,C]]) end,
lists:zip3("abc", "ABC", "123")).</langsyntaxhighlight>
If the lists are not all the same length, an error is thrown.
 
Line 1,408 ⟶ 1,833:
are.
If they are all "strings", it's quite easy:
<syntaxhighlight lang="euphoria">
<lang Euphoria>
sequence a, b, c
 
Line 1,418 ⟶ 1,843:
puts(1, a[i] & b[i] & c[i] & "\n")
end for
</syntaxhighlight>
</lang>
 
If not, and the other sequence is known to contain only integers:
 
<syntaxhighlight lang="euphoria">
<lang Euphoria>
sequence a, b, c
 
Line 1,432 ⟶ 1,857:
printf(1, "%s%s%g\n", {a[i], b[i], c[i]})
end for
</syntaxhighlight>
</lang>
 
A general solution for any arbitrary strings of characters or numbers
Line 1,438 ⟶ 1,863:
printed out. One possible answer is as follows, if you know that only
alphanumeric characters are used:
<syntaxhighlight lang="euphoria">
<lang Euphoria>
for i = 1 to length(a) do
if (a[i] >= '0' and a[i] <= '9') then
Line 1,451 ⟶ 1,876:
printf(1, "%s%s%s\n", {a[i], b[i], c[i]})
end for
</syntaxhighlight>
</lang>
Just as in Java, using single quotes around a character gives you its
"char value". In Euphoria, though, it is simply that character's code
Line 1,460 ⟶ 1,885:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">for c1,c2,n in Seq.zip3 ['a';'b';'c'] ['A';'B';'C']
[1;2;3] do
printfn "%c%c%d" c1 c2 n</langsyntaxhighlight>
 
When one sequence is exhausted, any remaining elements in the other
Line 1,468 ⟶ 1,893:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">"abc" "ABC" "123" [ [ write1 ] tri@ nl ]
3each</langsyntaxhighlight>
 
=={{header|Fantom}}==
 
This will stop when it reaches the end of the shortest list.
<langsyntaxhighlight lang="fantom">
class LoopMultiple
{
Line 1,488 ⟶ 1,913:
}
}
</syntaxhighlight>
</lang>
 
=={{header|Fermat}}==
<langsyntaxhighlight lang="fermat">[a] := [('a','b','c')];
[b] := [('A','B','C')];
[c] := [(1,2,3)];
Line 1,499 ⟶ 1,924:
;{instead of a numerical ASCII code, and the}
;{:1 causes the integer to take up exactly one}
;{space, ie. no leading or trailing spaces.}</langsyntaxhighlight>
{{out}}</pre>aA1
bB2
Line 1,505 ⟶ 1,930:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">create a char a , char b , char c ,
create b char A , char B , char C ,
create c char 1 , char 2 , char 3 ,
Line 1,523 ⟶ 1,948:
loop
drop drop drop
;</langsyntaxhighlight>
 
=={{header|Fortran}}==
 
<langsyntaxhighlight lang="fortran">program main
implicit none
 
Line 1,542 ⟶ 1,967:
 
end program main
</syntaxhighlight>
</lang>
 
If the arrays are of different length (say, array ns has no third element), then when its turn comes the next unit of storage along from the second element will be accessed, its content interpreted as an integer, and its decimal value printed... If however, array bound checking is activated (or there is a memory access protection scheme that would detect this), a feature unavailable via many compilers and not the default on the rest, then an error will be detected and the run will be terminated, possibly with a somewhat helpful message.
 
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}}==
<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</lang>
 
{{out}}
<pre>
aA1
bB2
cC3
 
aA1
bB2
</pre>
 
=={{header|Frink}}==
<langsyntaxhighlight lang="frink">a1 = ["a", "b", "c"]
a2 = ["A", "B", "C"]
a3 = ["1", "2", "3"]
m = [a1, a2, a3]
for row = m.transpose[]
println[join["",row]]</langsyntaxhighlight>
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">import lists.zip3
 
for x <- zip3( ['a', 'b', 'c'], ['A', 'B', 'C'], [1, 2, 3] )
println( x.mkString() )</langsyntaxhighlight>
 
{{out}}
Line 1,611 ⟶ 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
<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</lang>
</syntaxhighlight>
 
{{output}}
Output:
<pre>
aA1
bB2
Cc3
cC3
</pre>
 
=={{header|GAP}}==
<langsyntaxhighlight lang="gap">
# The Loop function will apply some function to every tuple built by
taking
Line 1,668 ⟶ 2,055:
aC3
bD1
aE2</langsyntaxhighlight>
 
=={{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,683 ⟶ 2,095:
conditions are meaningful in your application and explicitly handle
whatever errors are plausible.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,695 ⟶ 2,107:
fmt.Printf("%v%c%v\n", a1[i], a2[i], a3[i])
}
}</langsyntaxhighlight>
 
=={{header|Golfscript}}==
<langsyntaxhighlight lang="golfscript">["a" "b" "c"]:a;
["A" "B" "C"]:b;
["1" "2" "3"]:c;
[a b c]zip{puts}/</langsyntaxhighlight>
 
If there are arrays of different size, the shorter are treated as
Line 1,708 ⟶ 2,120:
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def synchedConcat = { a1, a2, a3 ->
assert a1 && a2 && a3
assert a1.size() == a2.size()
assert a2.size() == a3.size()
[a1, a2, a3].transpose().collect { "${it[0]}${it[1]}${it[2]}" }
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">def x = ['a', 'b', 'c']
def y = ['A', 'B', 'C']
def z = [1, 2, 3]
 
synchedConcat(x, y, z).each { println it }</langsyntaxhighlight>
 
{{out}}
Line 1,729 ⟶ 2,141:
=={{header|Harbour}}==
'''Using FOR EACH ... NEXT statement'''
<langsyntaxhighlight lang="visualfoxpro">
PROCEDURE Main()
LOCAL a1 := { "a", "b", "c" }, ;
Line 1,740 ⟶ 2,152:
NEXT
RETURN
</syntaxhighlight>
</lang>
Output:
aA1
Line 1,751 ⟶ 2,163:
'''Using list comprehension'''
 
<langsyntaxhighlight lang="haskell">{-# LANGUAGE ParallelListComp #-}
 
main = sequence [ putStrLn [x, y, z] | x <- "abd" | y <- "ABC" | z <- "123"]</lang>
main :: IO [()]
main =
sequence
[ putStrLn [x, y, z]
| x <- "abc"
| y <- "ABC"
| z <- "123"
]</syntaxhighlight>
 
'''Using Transpose'''
Line 1,758 ⟶ 2,178:
In this special case of transposing strings.
 
<langsyntaxhighlight lang="haskell">import Data.List
main = mapM putStrLn $ transpose ["abdabc", "ABC", "123"]</langsyntaxhighlight>
 
'''Using ZipWith*'''
 
<langsyntaxhighlight lang="haskell">import Data.List
main = mapM putStrLn $ zipWith3 (\a b c -> [a,b,c]) "abc" "ABC" "123"</langsyntaxhighlight>
 
'''Using applicative ZipLists'''
 
ZipLists generalize zipWith to any number of parameters
<langsyntaxhighlight lang="haskell">import Control.Applicative (ZipList (ZipList, getZipList))
 
main = sequence $ getZipList $ (\x y z -> putStrLn [x, y, z]) <$> ZipList "abd" <*> ZipList "ABC" <*> ZipList "123"</lang>
main :: IO ()
main =
mapM_ putStrLn $
getZipList
( (\x y z -> [x, y, z])
<$> ZipList "abc"
<*> ZipList "ABC"
<*> ZipList "123"
)
<> 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}}==
<langsyntaxhighlight lang="haxe">using Lambda;
using Std;
 
Line 1,794 ⟶ 2,238:
Sys.println(a[i] + b[i] + c[i].string());
}
}</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">CHARACTER :: A = "abc"
REAL :: C(3)
 
Line 1,804 ⟶ 2,248:
DO i = 1, 3
WRITE() A(i), "ABC"(i), C(i)
ENDDO</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
 
The first solution uses co-expressions to produce parallel evaluation.
<langsyntaxhighlight Iconlang="icon">procedure main()
a := create !["a","b","c"]
b := create !["A","B","C"]
c := create !["1","2","3"]
while write(@a,@b,@c)
end</langsyntaxhighlight>
 
The second solution is more like other procedural languages
and also handles unequal list lengths.
<langsyntaxhighlight Iconlang="icon">link numbers # for max
 
procedure main()
Line 1,828 ⟶ 2,272:
every i := 1 to max(*a,*b,*c) do
write(a[i]|"","\t",b[i]|"","\t",c[i]|"")
end</langsyntaxhighlight>
 
{{libheader|Icon Programming Library}}
[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:
<langsyntaxhighlight Jlang="j"> ,.&:(":"0@>)/ 'abc' ; 'ABC' ; 1 2 3
aA1
bB2
cC3</langsyntaxhighlight>
This approach works by representing the digits as characters.
 
Where arrays are all the same type (all numeric or all string):
<langsyntaxhighlight Jlang="j"> ,.&:>/ 'abc' ; 'ABC' ; '123'
aA1
bB2
cC3</langsyntaxhighlight>
 
Both of these implementations reject arrays with conflicting lengths.
Line 1,852 ⟶ 2,308:
Other options include:
 
<langsyntaxhighlight Jlang="j"> |: 'abc', 'ABC' ,:;":&> 1 2 3
aA1
bB2
cC3</langsyntaxhighlight>
<langsyntaxhighlight Jlang="j"> |: 'abc', 'ABC',: '123'
aA1
bB2
cC3</langsyntaxhighlight>
These implementations pad short arrays with spaces.
 
Or:
 
<langsyntaxhighlight Jlang="j"> |:>]&.>L:_1 'abc';'ABC';<1 2 3
┌─┬─┬─┐
│a│A│1│
Line 1,871 ⟶ 2,327:
├─┼─┼─┤
│c│C│3│
└─┴─┴─┘</langsyntaxhighlight>
 
This implementation puts each item from each of the original lists
Line 1,883 ⟶ 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}}==
<langsyntaxhighlight lang="java">String[][] list1 = {{"a","b","c"}, {"A", "B", "C"}, {"1", "2", "3"}};
for (int i = 0; i < list1.length; i++) {
for (String[] lista : list1) {
Line 1,891 ⟶ 2,362:
}
System.out.println();
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Line 1,898 ⟶ 2,369:
This loops over the indices of the first array,
and uses that to index into the others.
<langsyntaxhighlight lang="javascript">var a = ["a","b","c"],
b = ["A","B","C"],
c = [1,2,3],
Line 1,905 ⟶ 2,376:
for (i = 0; i < a.length; i += 1) {
output += a[i] + b[i] + c[i] + "\n";
}</langsyntaxhighlight>
If the b or c arrays are too "short",
you will see the string "undefined" appear in the output.
Line 1,911 ⟶ 2,382:
Alternatively, we can nest a couple of calls to '''.forEach()''': one for the array of three arrays, and one for each of the three index positions:
 
<langsyntaxhighlight JavaScriptlang="javascript">var lstOut = ['', '', ''];
 
[["a", "b", "c"], ["A", "B", "C"], ["1", "2", "3"]].forEach(
Line 1,924 ⟶ 2,395:
);
 
// lstOut --> ["aA1", "bB2", "cC3"]</langsyntaxhighlight>
 
===Functional composition===
Line 1,936 ⟶ 2,407:
Reduce / fold:
 
<langsyntaxhighlight JavaScriptlang="javascript">(function (lstArrays) {
 
return lstArrays.reduce(
Line 1,952 ⟶ 2,423:
["A", "B", "C"],
["1", "2", "3"]
]);</langsyntaxhighlight>
 
A fixed arity ZipWith:
 
<langsyntaxhighlight JavaScriptlang="javascript">(function (x, y, z) {
 
// function of arity 3 mapped over nth items of each of 3 lists
Line 1,971 ⟶ 2,442:
return zipWith3(concat, x, y, z).join('\n')
 
})(["a", "b", "c"], ["A", "B", "C"], [1, 2, 3]);</langsyntaxhighlight>
 
Or we could write a generic '''zipListsWith''' applying some supplied function overs lists derived from the nth members of an arbitrary list of (equal-length) lists.
 
<langsyntaxhighlight JavaScriptlang="javascript">(function () {
'use strict';
 
Line 1,999 ⟶ 2,470:
)
.join('\n');
})();</langsyntaxhighlight>
{{Out}}
<syntaxhighlight lang="javascript">aA1
<lang JavaScript>aA1
bB2
cC3</langsyntaxhighlight>
 
====ES6====
 
By transposition:
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 2,040 ⟶ 2,511:
map(concat, transpose(xs))
);
})();</langsyntaxhighlight>
{{Out}}
<pre>aA1
Line 2,054 ⟶ 2,525:
The first array determines the number of items in the output;
nulls are used for padding.
<langsyntaxhighlight lang="jq"># zip/0 emits [] if input is [].
 
def zip:
. as $in
| [range(0; $in[0]|length) as $i | $in | map( .[$i] ) ];</langsyntaxhighlight>
 
Example 1:
Line 2,095 ⟶ 2,566:
that pads all arrays shorter than the longest with nulls.
Here is such a variant:
<syntaxhighlight lang="jq">
<lang jq>
# transpose a possibly jagged matrix
def transpose:
Line 2,104 ⟶ 2,575:
([]; . + [ [ $row[$i] ] + $t[$i] ])
end;
</syntaxhighlight>
</lang>
 
=={{header|Jsish}}==
<langsyntaxhighlight lang="javascript">/* Loop over multiple arrays, in Jsish */
var a1 = ['a', 'b', 'c'];
var a2 = ['A', 'B', 'C'];
Line 2,143 ⟶ 2,614:
undefinedundefinedundefinedundefined7
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 2,151 ⟶ 2,622:
=={{header|Julia}}==
'''With a higher order function''':
<langsyntaxhighlight lang="julia">foreach(println, ('a', 'b', 'c'), ('A', 'B', 'C'), (1, 2, 3))</langsyntaxhighlight>
 
'''With a loop''':
<langsyntaxhighlight lang="julia">for (i, j, k) in zip(('a', 'b', 'c'), ('A', 'B', 'C'), (1, 2, 3))
println(i, j, k)
end</langsyntaxhighlight>
 
{{out}}
Line 2,164 ⟶ 2,635:
 
=={{header|K}}==
<langsyntaxhighlight Klang="k">{,/$x}'+("abc";"ABC";1 2 3)</langsyntaxhighlight>
 
{{out}}
Line 2,177 ⟶ 2,648:
 
The following is a more general approach where
<syntaxhighlight lang="k">
<lang K>
&/#:'x
</syntaxhighlight>
</lang>
 
calculates the minimum length of the arrays
and is used to index the first elements in each array.
 
<syntaxhighlight lang="k">
<lang K>
{+x[;!(&/#:'x)]}("abc";"ABC";"1234")
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,198 ⟶ 2,669:
then the arrays must be converted to strings.
 
<syntaxhighlight lang="k">
<lang K>
{a:,/'($:'x);+a[;!(&/#:'a)]}("abc";"ABC";1 2 3 4)
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="kotlin">import kotlin.comparisons.minOf
<lang scala>// version 1.0.6
 
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]}")
}</langsyntaxhighlight>
 
{{out}}
Line 2,230 ⟶ 2,700:
 
=={{header|Lambdatalk}}==
<langsyntaxhighlight lang="scheme">
1) loop over 3 sentences of equal length and returning 3 sentences
 
Line 2,283 ⟶ 2,753:
e d
s
</syntaxhighlight>
</lang>
 
=={{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}}==
<langsyntaxhighlight lang="lisp">
(lists:zipwith3
(lambda (i j k)
Line 2,293 ⟶ 2,802:
'(A B C)
'(1 2 3))
</syntaxhighlight>
</lang>
 
If any of the data lists differ in size from the other,
Line 2,305 ⟶ 2,814:
function with something like <code lisp>(: lists map
...)</code>.
 
=={{header|Liberty BASIC}}==
<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</lang>
 
=={{header|Lisaac}}==
<langsyntaxhighlight Lisaaclang="lisaac">Section Header
 
+ name := ARRAY_LOOP_TEST;
Line 2,343 ⟶ 2,842:
'\n'.print;
};
);</langsyntaxhighlight>
 
=={{header|LiveCode}}==
Arrays
<langsyntaxhighlight LiveCodelang="livecode">command loopArrays
local lowA, uppA, nums, z
put "a,b,c" into lowA
Line 2,362 ⟶ 2,861:
put z
 
end loopArrays</langsyntaxhighlight>
"list" processing
<langsyntaxhighlight LiveCodelang="livecode">command loopDelimitedList
local lowA, uppA, nums, z
put "a,b,c" into lowA
Line 2,376 ⟶ 2,875:
put z
 
end loopDelimitedList</langsyntaxhighlight>
Output - both behave similarly for this exercise.
<pre>aA1
Line 2,393 ⟶ 2,892:
{{works with|UCB Logo}}
 
<langsyntaxhighlight lang="logo">show (map [(word ?1 ?2 ?3)] [a b c] [A B C] [1 2 3])
; [aA1 bB2 cC3]
 
(foreach [a b c] [A B C] [1 2 3] [print (word ?1 ?2 ?3)]) ; as above,
one per line</langsyntaxhighlight>
 
=={{header|Lua}}==
This can be done with a simple for loop:
<langsyntaxhighlight lang="lua">
a1, a2, a3 = {'a' , 'b' , 'c' } , { 'A' , 'B' , 'C' } , { 1 , 2 , 3 }
for i = 1, 3 do print(a1[i]..a2[i]..a3[i]) end
</syntaxhighlight>
</lang>
but it may be more enlightening
(and in line with the spirit of the challenge) to use the generic for:
<langsyntaxhighlight lang="lua">
function iter(a, b, c)
local i = 0
Line 2,417 ⟶ 2,916:
 
for u, v, w in iter(a1, a2, a3) do print(u..v..w) end
</syntaxhighlight>
</lang>
=={{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}}==
<langsyntaxhighlight Maplelang="maple"># Set up
L := [["a", "b", "c"],["A", "B", "C"], ["1", "2", "3"]];
M := Array(1..3, 1..3, L);
Line 2,434 ⟶ 2,953:
end proc:
 
multi_loop(M);</langsyntaxhighlight>
{{out}}
<pre>
Line 2,444 ⟶ 2,963:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
This can be done with a built-in function:
<langsyntaxhighlight lang="mathematica">MapThread[Print, {{"a", "b", "c"}, {"A", "B", "C"}, {1, 2, 3}}];</langsyntaxhighlight>
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}}==
<syntaxhighlight lang="text">
:- module multi_array_loop.
:- interface.
Line 2,468 ⟶ 3,003:
print_elems(A, B, C, !IO) :-
io.format("%c%c%i\n", [c(A), c(B), i(C)], !IO).
</syntaxhighlight>
</lang>
The foldl_corresponding family of procedures all throw a
software_error/1
Line 2,474 ⟶ 3,009:
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE MultiArray EXPORTS Main;
 
IMPORT IO, Fmt;
Line 2,490 ⟶ 3,025:
Fmt.Int(arr3[i]) & "\n");
END;
END MultiArray.</langsyntaxhighlight>
 
=={{header|MUMPS}}==
Pieces of String version
<syntaxhighlight lang="mumps">
<lang MUMPS>
LOOPMULT
N A,B,C,D,%
Line 2,504 ⟶ 3,039:
K A,B,C,D,%
Q
</syntaxhighlight>
</lang>
When there aren't enough elements,
a null string will be returned from the $Piece function.
Line 2,517 ⟶ 3,052:
 
Local arrays version
<syntaxhighlight lang="mumps">
<lang MUMPS>
LOOPMULU
N A,B,C,D,%
Line 2,527 ⟶ 3,062:
S %=$O(A("")) F Q:%="" W !,$G(A(%)),$G(B(%)),$G(C(%)) S %=$O(A(%))
K A,B,C,D,%
</syntaxhighlight>
</lang>
 
The commented out line will throw an <UNDEFINED> error when trying
Line 2,553 ⟶ 3,088:
=={{header|Nanoquery}}==
{{trans|Java}}
<langsyntaxhighlight Nanoquerylang="nanoquery">list1 = {{"a","b","c"}, {"A","B","C"}, {"1","2","3"}}
for i in range(0, len(list1) - 1)
for lista in list1
Line 2,559 ⟶ 3,094:
end for
println
end for</langsyntaxhighlight>
 
=={{header|Nemerle}}==
It "feels" better to use zip() for this,
unfortunately the built in zip() only takes two lists.
<langsyntaxhighlight Nemerlelang="nemerle">using System;
using System.Console;
 
Line 2,588 ⟶ 3,123:
WriteLine($"$x$y$z");
}
}</langsyntaxhighlight>
 
Alternately: {{trans|C#}}
<langsyntaxhighlight Nemerlelang="nemerle">using System.Console;
 
module LoopMult
Line 2,606 ⟶ 3,141:
WriteLine("{0}{1}{2}", first[i], second[i], third[i]);
}
}</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols nobinary
 
Line 2,654 ⟶ 3,189:
return smp
</syntaxhighlight>
</lang>
{{out}}
<pre style="overflow:scroll">
Line 2,670 ⟶ 3,205:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">(map println '(a b c) '(A B C) '(1 2
3))</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">let
a = @['a','b','c']
b = @["A","B","C"]
Line 2,680 ⟶ 3,215:
 
for i in 0..2:
echo a[i], b[i], c[i]</langsyntaxhighlight>
 
=={{header|NS-HUBASIC}}==
<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</lang>
 
=={{header|Oberon-2}}==
Works with oo2c version 2
<langsyntaxhighlight lang="oberon2">
MODULE LoopMArrays;
IMPORT
Line 2,726 ⟶ 3,244:
DoLoop
END LoopMArrays.
</syntaxhighlight>
</lang>
Output:<br/>
<pre>
Line 2,735 ⟶ 3,253:
 
=={{header|Objeck}}==
<langsyntaxhighlight lang="objeck">
class MultipleArrayAccess {
function : Main(args : String[]) ~ Nil {
Line 2,749 ⟶ 3,267:
}
}
</syntaxhighlight>
</lang>
 
If the arrays are different lengths,
Line 2,756 ⟶ 3,274:
=={{header|OCaml}}==
an immediate solution:
<langsyntaxhighlight lang="ocaml">let a1 = [| 'a'; 'b'; 'c' |]
and a2 = [| 'A'; 'B'; 'C' |]
and a3 = [| '1'; '2'; '3' |] ;;
Line 2,765 ⟶ 3,283:
print_char a3.(i);
print_newline()
) a1 ;;</langsyntaxhighlight>
 
a more generic solution could be to use a function
which iterates over a list of arrays:
 
<langsyntaxhighlight lang="ocaml">let n_arrays_iter ~f = function
| [] -> ()
| x::xs as al ->
Line 2,780 ⟶ 3,298:
let ai = List.map (fun a -> a.(i)) al in
f ai
done</langsyntaxhighlight>
 
this function raises Invalid_argument exception if arrays have different
Line 2,786 ⟶ 3,304:
and has this signature:
 
<langsyntaxhighlight lang="ocaml">val n_arrays_iter : f:('a list -> unit) -> 'a
array list -> unit</langsyntaxhighlight>
 
how to use it with arrays a1, a2 and a3 defined before:
 
<langsyntaxhighlight lang="ocaml">let () =
n_arrays_iter [a1; a2; a3] ~f:(fun l ->
List.iter print_char l;
print_newline());
;;</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 2,801 ⟶ 3,319:
If arrays don't have the same size, zipAll reduces to the minimum size
 
<langsyntaxhighlight Oforthlang="oforth">[ "a", "b", "c" ] [ "A", "B", "C" ] [ 1, 2, 3 ]
zipAll(3) apply(#[ apply(#print) printcr ])</langsyntaxhighlight>
 
{{out}}
Line 2,812 ⟶ 3,330:
 
=={{header|ooRexx}}==
<syntaxhighlight lang="oorexx">
<lang ooRexx>
x = .array~of("a", "b", "c")
y = .array~of("A", "B", "C")
Line 2,820 ⟶ 3,338:
say x[i]y[i]z[i]
end
</syntaxhighlight>
</lang>
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">for
I in [a b c]
J in ['A' 'B' 'C']
Line 2,829 ⟶ 3,347:
do
{System.showInfo I#J#K}
end</langsyntaxhighlight>
 
The loop will stop when the shortest list is exhausted.
Line 2,835 ⟶ 3,353:
=={{header|PARI/GP}}==
This version stops when the shortest vector is exhausted.
<langsyntaxhighlight lang="parigp">loopMultiple(V)={
my(l=#V[1]);
for(i=2,#V,l=min(l,#V[i]));
Line 2,844 ⟶ 3,362:
print()
)
};</langsyntaxhighlight>
 
This version prints blanks when a vector is exhausted.
<langsyntaxhighlight lang="parigp">loopMultiple(V)={
my(l=0);
for(i=1,#V,l=max(l,#V[i]));
Line 2,860 ⟶ 3,378:
print()
)
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
Line 2,866 ⟶ 3,384:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub zip (&@)
{
my $code = shift;
Line 2,878 ⟶ 3,396:
my @a3 = qw( 1 2 3 );
 
zip { print @_,"\n" }\(@a1, @a2, @a3);</langsyntaxhighlight>
 
This implementation will stop producing items when the shortest array
Line 2,888 ⟶ 3,406:
If the arguments were not all the same length, attempts to retrieve non-existent elements could trigger a fatal run-time error, were it not for the min(). In print3, fairly obviously, we only extract up to the shortest length. The builtin columnize() routine can perform a similar task: I have provided a space defval and replaced the 3rd array with a string to ensure we get strings back, and extended it to show how columnize uses that default value for missing entries off the end of the first two arrays.
 
<!--<langsyntaxhighlight Phixlang="phix">-->
<span style="color: #008080;">procedure</span> <span style="color: #000000;">print3</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">c</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">min</span><span style="color: #0000FF;">({</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)})</span> <span style="color: #008080;">do</span>
Line 2,897 ⟶ 3,415:
<span style="color: #000000;">print3</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"abc"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ABC"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">})</span>
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">columnize</span><span style="color: #0000FF;">({</span><span style="color: #008000;">"abc"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"ABC"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"1234"</span><span style="color: #0000FF;">},{},</span><span style="color: #008000;">' '</span><span style="color: #0000FF;">)</span>
<!--</langsyntaxhighlight>-->
 
{{out}}
Line 2,908 ⟶ 3,426:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
( "abc" "ABC" "123" )
Line 2,923 ⟶ 3,441:
nl
endfor
</syntaxhighlight>
</lang>
 
=={{header|PHP}}==
<langsyntaxhighlight PHPlang="php">$a = array('a', 'b', 'c');
$b = array('A', 'B', 'C');
$c = array('1', '2', '3'); //These don't *have* to be strings, but it
Line 2,936 ⟶ 3,454:
foreach ($a as $key => $value){
echo "{$a[$key]}{$b[$key]}{$c[$key]}\n";
}</langsyntaxhighlight>
 
This implementation throws an exception if the arrays are not all the
Line 2,948 ⟶ 3,466:
If the lists/arrays are of uneven lengths, then the elements in the longer arrays are skipped.
 
<langsyntaxhighlight Picatlang="picat">import util.
 
go =>
Line 2,972 ⟶ 3,490:
println([A,B,C,D].join(''))
end,
nl.</langsyntaxhighlight>
 
{{out}}
Line 2,991 ⟶ 3,509:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(mapc prinl
'(a b c)
'(A B C)
(1 2 3) )</langsyntaxhighlight>
The length of the first argument list controls the operation.
If subsequent lists are longer, their remaining values are ignored.
Line 3,003 ⟶ 3,521:
avoids the usual off-by-one errors
 
<syntaxhighlight lang="pike">
<lang Pike>
array a1 = ({ "a", "b", "c" });
array a2 = ({ "A", "B", "C" });
Line 3,010 ⟶ 3,528:
foreach(a1; int index; string char_dummy)
write("%s%s%s\n", a1[index], a2[index], a3[index]);
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,019 ⟶ 3,537:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">
declare P(3) character (1) initial ('a', 'b', 'c'),
Q(3) character (1) initial ('A', 'B', 'C'),
Line 3,027 ⟶ 3,545:
put skip edit (P(i), Q(i), R(i)) (2 A, F(1));
end;
</syntaxhighlight>
</lang>
 
=={{header|PostScript}}==
{{libheader|initlib}}
<langsyntaxhighlight lang="postscript">
% transpose is defined in initlib like this.
/transpose {
Line 3,043 ⟶ 3,561:
% using it.
[[/a /b /c] [/A /B /C] [1 2 3]] transpose
</syntaxhighlight>
</lang>
 
=={{header|PowerBASIC}}==
<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</lang>
 
=={{header|PowerShell}}==
A cheap and chEasy 'zip' function:
<syntaxhighlight lang="powershell">
<lang PowerShell>
function zip3 ($a1, $a2, $a3)
{
Line 3,083 ⟶ 3,576:
}
}
</syntaxhighlight>
</lang>
<syntaxhighlight lang="powershell">
<lang PowerShell>
zip3 @('a','b','c') @('A','B','C') @(1,2,3)
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,095 ⟶ 3,588:
c C 3
</pre>
<syntaxhighlight lang="powershell">
<lang PowerShell>
zip3 @('a','b','c') @('A','B','C') @(1,2,3) | ForEach-Object {$_.Item1 + $_.Item2 + $_.Item3}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,107 ⟶ 3,600:
=={{header|Prolog}}==
Works with SWI-Prolog
<langsyntaxhighlight Prologlang="prolog">multiple_arrays(L1, L2, L3) :-
maplist(display, L1, L2, L3).
 
display(A,B,C) :-
writef('%s%s%s\n', [[A],[B],[C]]).
</syntaxhighlight>
</lang>
{{out}}
<pre> ?- multiple_arrays("abc", "ABC", "123").
Line 3,125 ⟶ 3,618:
false.
</pre>
 
=={{header|PureBasic}}==
<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</lang>
 
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}}==
Using <tt>zip()</tt>:
<langsyntaxhighlight lang="python">>>> print ( '\n'.join(''.join(x) for x in
zip('abc', 'ABC', '123')) )
aA1
bB2
cC3
>>></langsyntaxhighlight>
If lists are different lengths, <tt>zip()</tt> stops after
the shortest one.
 
Using <tt>map()</tt>:
<langsyntaxhighlight lang="python">>>> print(*map(''.join, zip('abc', 'ABC', '123')), sep='\n')
aA1
bB2
cC3
>>></langsyntaxhighlight>
If lists are different lengths, <tt>map()</tt> in Python 2.x pretends that the shorter lists were extended with
<tt>None</tt> items; <tt>map()</tt> in Python 3.x stops after the shortest one.
 
Using <tt>itertools.imap()</tt> (Python 2.x):
<langsyntaxhighlight lang="python">from itertools import imap
 
def join3(a,b,c):
print a+b+c
 
imap(join3,'abc','ABC','123')</langsyntaxhighlight>
If lists are differnt lengths, <tt>imap()</tt> stops after
the shortest is exhausted.
Line 3,188 ⟶ 3,652:
fillvalue argument which defaults to <tt>None</tt> (similar to the behavior of
''map()'' in Python 2.x):
<langsyntaxhighlight lang="python">>>> from itertools import zip_longest
>>> print ( '\n'.join(''.join(x) for x in zip_longest('abc',
'ABCD', '12345', fillvalue='#')) )
Line 3,196 ⟶ 3,660:
#D4
##5
>>></langsyntaxhighlight>
(The Python 2.X equivalent is itertools.izip_longest)
 
Line 3,203 ⟶ 3,667:
The code presented here will loop as many times as the number of characters in the first nest (i.e. "abc" in the example). If either of the other two nests are shorter than the first then the program will report a problem.
 
<langsyntaxhighlight Quackerylang="quackery"> [ rot witheach
[ emit
over i^ peek emit
Line 3,210 ⟶ 3,674:
2drop ] is task ( $ $ $ --> )
 
$ "abc" $ "ABC" $ "123" task</langsyntaxhighlight>
 
{{out}}
Line 3,220 ⟶ 3,684:
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">multiloop <- function(...)
{
# Retrieve inputs and convert to a list of character strings
Line 3,240 ⟶ 3,704:
}
}
multiloop(letters[1:3], LETTERS[1:3], 1:3)</langsyntaxhighlight>
 
Same thing as a single function call.
But throws error if the arrays differ in length.
 
<syntaxhighlight lang="r">
<lang R>
apply(data.frame(letters[1:3], LETTERS[1:3], 1:3), 1,
function(row) { cat(row, "\n", sep='') })
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 3,255 ⟶ 3,719:
of sequences of any kind at once:
 
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 3,263 ⟶ 3,727:
[i (in-naturals 1)]) ; 1, 2, ... infinitely
(printf "~s: ~s ~s ~s\n" i x y z))
</syntaxhighlight>
</lang>
 
The loop stops as soon as the first sequence terminates -- in the above
Line 3,277 ⟶ 3,741:
 
=== Basic functionality ===
<syntaxhighlight lang="raku" perl6line>for <a b c> Z <A B C> Z 1, 2, 3 -> ($x, $y, $z) {
say $x, $y, $z;
}</langsyntaxhighlight>
 
The <code>Z</code> operator stops emitting items as soon as the shortest input list is exhausted. However, short lists are easily extended by replicating all or part of the list, or by appending any kind of lazy list generator to supply default values as necessary.
Line 3,289 ⟶ 3,753:
Note that we can also factor out the concatenation by making the <tt>Z</tt> metaoperator apply the <tt>~</tt> concatenation operator across each triple:
 
<syntaxhighlight lang="raku" perl6line>.say for <a b c> Z~ <A B C> Z~ 1, 2, 3;</langsyntaxhighlight>
 
We could also use the zip-to-string with the reduction metaoperator:
 
<syntaxhighlight lang="raku" perl6line>.say for [Z~] <a b c>, <A B C>, (1,2,3);</langsyntaxhighlight>
 
We could also write that out "long-hand":
 
<syntaxhighlight lang="raku" perl6line>.say for zip :with(&infix:<~>), <a b c>, <A B C>, (1,2,3);</langsyntaxhighlight>
 
returns the exact same result so if you aren't comfortable with the concise operators, you have a choice.
Line 3,305 ⟶ 3,769:
The common case of iterating over a list and a list of its indices can be done using the same method:
 
<syntaxhighlight lang="raku" perl6line>for ^Inf Z <a b c d> -> ($i, $letter) { ... }</langsyntaxhighlight>
 
or by using the <code>.kv</code> (key and value) method on the list (and dropping the parentheses because the list returned by <code>.kv</code> is a flattened list):
 
<syntaxhighlight lang="raku" perl6line>for <a b c d>.kv -> $i, $letter { ... }</langsyntaxhighlight>
 
=== Iterate until all exhausted ===
Line 3,315 ⟶ 3,779:
If you have different sized lists that you want to pull a value from each per iteration, but want to continue until '''all''' of the lists are exhausted, we have <code>roundrobin</code>.
 
<syntaxhighlight lang="raku" perl6line>.put for roundrobin <a b c>, 'A'..'G', ^5;</langsyntaxhighlight>
{{out|yields}}
<pre>a A 0
Line 3,330 ⟶ 3,794:
When a variable is used in a path notation, we put a colon in front of it. :counter
 
<langsyntaxhighlight Redlang="red">>>blk: [["a" "b" "c"] ["A" "B" "C"] [1 2 3]]
== [["a" "b" "c"] ["A" "B" "C"] [1 2 3]]
 
Line 3,336 ⟶ 3,800:
a A 1
b B 2
c C 3</langsyntaxhighlight>
 
=={{header|REXX}}==
Line 3,344 ⟶ 3,808:
<br><br>
When &nbsp; ''all'' &nbsp; elements are blank, then it signifies the end of the arrays.
<langsyntaxhighlight lang="rexx">/*REXX program shows how to simultaneously loop over multiple arrays.*/
x. = ' '; x.1 = "a"; x.2 = 'b'; x.3 = "c"
y. = ' '; y.1 = "A"; y.2 = 'B'; y.3 = "C"
Line 3,352 ⟶ 3,816:
output = x.j || y.j || z.j
say output
end /*j*/ /*stick a fork in it, we're done.*/</langsyntaxhighlight>
'''output'''
<pre>
Line 3,363 ⟶ 3,827:
In this example, two of the arrays are extended (past the 1<sup>st</sup> example).
<br>Also note that REXX doesn't require quotes around non-negative numbers (they're optional).
<langsyntaxhighlight lang="rexx">/*REXX program shows how to simultaneously loop over multiple arrays.*/
x.=' '; x.1="a"; x.2='b'; x.3="c"; x.4='d'
y.=' '; y.1="A"; y.2='B'; y.3="C";
Line 3,371 ⟶ 3,835:
output=x.j || y.j || z.j
say output
end /*j*/ /*stick a fork in it, we're done.*/</langsyntaxhighlight>
'''output'''
<pre>
Line 3,382 ⟶ 3,846:
 
===dissimilar sized lists===
<langsyntaxhighlight lang="rexx">/*REXX program shows how to simultaneously loop over multiple lists.*/
x = 'a b c d'
y = 'A B C'
Line 3,389 ⟶ 3,853:
output = word(x,j) || word(y,j) || word(z,j)
say output
end /*j*/ /*stick a fork in it, we're done.*/</langsyntaxhighlight>
'''output'''
<pre>
Line 3,399 ⟶ 3,863:
 
===idiomatic method for lists===
<langsyntaxhighlight lang="rexx">/*REXX program shows how to simultaneously loop over multiple lists.*/
x = 'a b c d'
y = 'A B C'
Line 3,405 ⟶ 3,869:
do j=1 for max(words(x), words(y), words(z))
say word(x,j) || word(y,j) || word(z,j)
end /*j*/ /*stick a fork in it, we're done.*/</langsyntaxhighlight>
'''output'''
<pre>
Line 3,416 ⟶ 3,880:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
array1 = ["a", "b", "c"]
array2 = ["A", "B", "C"]
Line 3,424 ⟶ 3,888:
see array1[n] + array2[n] + array3[n] + nl
next
</syntaxhighlight>
</lang>
 
=={{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}}==
<langsyntaxhighlight lang="ruby">['a','b','c'].zip(['A','B','C'], [1,2,3]) {|i,j,k| puts "#{i}#{j}#{k}"}</langsyntaxhighlight>
or
<langsyntaxhighlight lang="ruby">['a','b','c'].zip(['A','B','C'], [1,2,3]) {|a| puts a.join}</langsyntaxhighlight>
 
Both of these loops print <code>aA1</code>, <code>bB2</code>, <code>cC3</code>.
Line 3,436 ⟶ 3,920:
If an argument array is longer, the excess elements are ignored.
If an argument array is shorter, the value <code>nil</code> is supplied.
<langsyntaxhighlight lang="ruby">irb(main):001:0> ['a','b','c'].zip(['A','B'], [1,2,3,4]) {|a| puts a.join}
aA1
bB2
Line 3,442 ⟶ 3,926:
=> nil
irb(main):002:0> ['a','b','c'].zip(['A','B'], [1,2,3,4])
=> [["a", "A", 1], ["b", "B", 2], ["c", nil, 3]]</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<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</lang>
 
=={{header|Rust}}==
 
<langsyntaxhighlight lang="rust">fn main() {
let a1 = ["a", "b", "c"];
let a2 = ["A", "B", "C"];
Line 3,465 ⟶ 3,938:
println!("{}{}{}", x, y, z);
}
}</langsyntaxhighlight>
{{out}}
<pre>aA1
Line 3,472 ⟶ 3,945:
 
=={{header|Salmon}}==
<langsyntaxhighlight Salmonlang="salmon">// First, we'll define a general-purpose zip() to zip
any
// number of lists together.
Line 3,496 ⟶ 3,969:
c := [1, 2, 3];
iterate (x; zip(a, b, c))
print(x[0], x[1], x[2], "\n");;</langsyntaxhighlight>
 
The preceding code will throw an exception if the lists aren't the same
Line 3,504 ⟶ 3,977:
some lists are shorter than the longest:
 
<langsyntaxhighlight Salmonlang="salmon">// First, we'll define a general-purpose zip() to zip
any
// number of lists together.
Line 3,530 ⟶ 4,003:
c := [1, 2, 3];
iterate (x; zip(a, b, c))
print(x[0], x[1], x[2], "\n");;</langsyntaxhighlight>
 
=={{header|Sather}}==
<langsyntaxhighlight lang="sather">class MAIN is
main is
a :ARRAY{STR} := |"a", "b", "c"|;
Line 3,543 ⟶ 4,016:
end;
end;
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">
("abc", "ABC", "123").zipped foreach { (x, y, z) =>
println(x.toString + y + z)
}
</syntaxhighlight>
</lang>
 
=={{header|Scheme}}==
Line 3,560 ⟶ 4,033:
into a new list.
 
<langsyntaxhighlight lang="scheme">
(let ((a '("a" "b" "c"))
(b '("A" "B" "C"))
Line 3,571 ⟶ 4,044:
(newline))
a b c))
</syntaxhighlight>
</lang>
 
Scheme has a <code>vector</code> datatype with constant-time
Line 3,578 ⟶ 4,051:
and <code>vector-map</code>:
 
<langsyntaxhighlight lang="scheme">
(let ((a (vector "a" "b" "c"))
(b (vector "A" "B" "C"))
Line 3,589 ⟶ 4,062:
(newline))
a b c))
</syntaxhighlight>
</lang>
 
Note, the lists or vectors must all be of the same length.
Line 3,595 ⟶ 4,068:
=={{header|Sidef}}==
The simplest way is by using the Array.zip{} method:
<langsyntaxhighlight lang="ruby">[%w(a b c),%w(A B C),%w(1 2 3)].zip { |i,j,k|
say (i, j, k)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,608 ⟶ 4,081:
{{works with|GNU Smalltalk}}
 
<langsyntaxhighlight lang="smalltalk">|a b c|
a := OrderedCollection new addAll: #('a' 'b' 'c').
b := OrderedCollection new addAll: #('A' 'B' 'C').
Line 3,617 ⟶ 4,090:
(b at: i) display.
(c at: i) displayNl.
].</langsyntaxhighlight>
 
If index ''i'' is out of bound, a runtime error is raised.
Line 3,624 ⟶ 4,097:
<br>Also, most Smalltalks (all?) can concatenate non-string args&sup1;.
<br>At least in ST/X, the following works &sup1;:
<langsyntaxhighlight lang="smalltalk">|a b c|
 
a := #('a' 'b' 'c').
Line 3,631 ⟶ 4,104:
1 to: (a size) do: [ :i |
((a at: i),(b at: i),(c at: i)) displayNl.
].</langsyntaxhighlight>
 
Another alternative is to use a multi-collection enumerator,
which hides the element access (transparent to how elements are stored inside the collection):
<langsyntaxhighlight lang="smalltalk">|a b c|
 
a := #('a' 'b' 'c').
Line 3,642 ⟶ 4,115:
a with:b with:c do:[:ai :bi :ci |
(ai,bi,ci) displayNl.
].</langsyntaxhighlight>
 
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}}==
The below code will combine arbitrarily many lists of strings
into a single list with length equal to that of the shortest list.
<syntaxhighlight lang="standard ml">
<lang Standard ML>
(*
* val combine_lists : string list list -> string list
Line 3,659 ⟶ 4,159:
(* ["a1Ax","b2By","c3Cz"] *)
combine_lists[["a","b","c"],["1","2","3"],["A","B","C"],["x","y","z"]];
</syntaxhighlight>
</lang>
 
=={{header|Stata}}==
Use an index variable.
 
<langsyntaxhighlight lang="stata">local u a b c
local v A B C
matrix w=1,2,3
forv i=1/3 {
di "`: word `i' of `u''`: word `i' of `v''`=el("w",1,`i')'"
}</langsyntaxhighlight>
 
=== Mata ===
 
<langsyntaxhighlight lang="stata">mata
u="a","b","c"
v="A","B","C"
Line 3,681 ⟶ 4,181:
printf("%s%s%f\n",u[i],v[i],w[i])
}
end</langsyntaxhighlight>
 
=={{header|SuperCollider}}==
 
Using three variables and indexing (SuperCollider posts the last statement in the REPL)
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
#x, y, z = [["a", "b", "c"], ["A", "B", "C"], ["1", "2", "3"]];
3.collect { |i| x[i] ++ y[i] ++ z[i] }
</syntaxhighlight>
</lang>
 
A more idiomatic way of writing it, independent of the number of dimensions:
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
[["a", "b", "c"], ["A", "B", "C"], ["1", "2", "3"]].flop.collect { |x| x.join }
</syntaxhighlight>
</lang>
 
Or simpler:
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
[["a", "b", "c"], ["A", "B", "C"], ["1", "2", "3"]].flop.collect(_.join)
</syntaxhighlight>
</lang>
 
 
Same with lamination (a concept from APL/[http://rosettacode.org/wiki/Category:J#The_J_language J]):
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
["a", "b", "c"] +++ ["A", "B", "C"] +++ ["1", "2", "3"]
</syntaxhighlight>
</lang>
 
Independent of dimensions:
<syntaxhighlight lang="supercollider">
<lang SuperCollider>
[["a", "b", "c"], ["A", "B", "C"], ["1", "2", "3"]].reduce('+++')
</syntaxhighlight>
</lang>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">let a1 = ["a", "b", "c"]
let a2 = ["A", "B", "C"]
let a3 = [1, 2, 3]
Line 3,719 ⟶ 4,219:
for i in 0 ..< a1.count {
println("\(a1[i])\(a2[i])\(a3[i])")
}</langsyntaxhighlight>
{{out}}
<pre>aA1
Line 3,727 ⟶ 4,227:
=={{header|Tailspin}}==
Simplest iteration with an ordinary "loop" that will error on uneven sizes
<langsyntaxhighlight lang="tailspin">
def x: ['a', 'b', 'c'];
def y: ['A', 'B', 'C'];
Line 3,734 ⟶ 4,234:
1..$x::length -> '$x($);$y($);$z($);
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,742 ⟶ 4,242:
</pre>
A simple transpose method that gives the same output and also errors on uneven sizes
<langsyntaxhighlight lang="tailspin">
templates transpose
def a: $;
Line 3,751 ⟶ 4,251:
[$x, $y, $z] -> transpose... -> '$...;
' -> !OUT::write
</syntaxhighlight>
</lang>
A more complex transpose that uses "foreach" more in line with the task proposal and handles uneven arrays
<langsyntaxhighlight lang="tailspin">
def u: ['a', 'b'];
def v: ['A', 'B', 'C'];
Line 3,774 ⟶ 4,274:
[$u,$v,$w] -> transpose2... -> '$...;
' -> !OUT::write
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,787 ⟶ 4,287:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">set list1 {a b c}
set list2 {A B C}
set list3 {1 2 3}
foreach i $list1 j $list2 k $list3 {
puts "$i$j$k"
}</langsyntaxhighlight>
If lists are different lengths, the manual
[http://www.tcl.tk/man/tcl8.5/TclCmd/foreach.htm] says:
Line 3,803 ⟶ 4,303:
=={{header|TorqueScript}}==
 
<syntaxhighlight lang="torquescript">
<lang Torquescript>
$var[0] = "a b c"
$var[1] = "A B C";
Line 3,810 ⟶ 4,310:
for(%i=0;%i<3;%i++)
echo(getWord($var[0],%i) @ getWord($var[1],%i) @ getWord($var[2],%i));
</syntaxhighlight>
</lang>
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
arr1="a'b'c"
Line 3,821 ⟶ 4,321:
PRINT a,b,c
ENDLOOP
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,833 ⟶ 4,333:
===Pattern language===
 
<langsyntaxhighlight lang="bash">$ txr -c '@(bind a ("a" "b" "c"))
@(bind b ("A" "B" "C"))
@(bind c ("1" "2" "3"))
Line 3,843 ⟶ 4,343:
aA1
bB2
cC3</langsyntaxhighlight>
 
===TXR Lisp, using <code>mapcar</code>===
Line 3,851 ⟶ 4,351:
finally printed in one go.
 
<langsyntaxhighlight lang="bash">$ txr -e '(pprint (mappend (op list) "abc" "ABC" "123"
(repeat "\n")))'
aA1
bB2
cC3</langsyntaxhighlight>
 
===TXR Lisp, using <code>each</code>===
 
<langsyntaxhighlight lang="bash">$ txr -e '(each ((x "abc") (y "ABC") (z "123"))
(put-line `@x@y@z`))'
aA1
bB2
cC3</langsyntaxhighlight>
 
===Translation of Scheme===
Line 3,869 ⟶ 4,369:
{{trans|Scheme}}
 
<langsyntaxhighlight lang="txrlisp">;; Scheme's vector-for-each: a one-liner in TXR
;; that happily works over strings and lists.
;; We don't need "srfi-43".
Line 3,890 ⟶ 4,390:
(display i3)
(newline))
a b c))</langsyntaxhighlight>
 
===Translation of Logo===
Line 3,896 ⟶ 4,396:
{{trans|Logo}}
 
<langsyntaxhighlight lang="txrlisp">(macro-time
(defun question-var-to-meta-num (var)
^(sys:var ,(int-str (cdr (symbol-name var))))))
Line 3,911 ⟶ 4,411:
(defun show (x) (pprinl x))
 
(show (map [(word ?1 ?2 ?3)] [a b c] [A B C] [1 2 3]))</langsyntaxhighlight>
 
{{out}}
Line 3,917 ⟶ 4,417:
 
== {{header|TypeScript}} ==
<langsyntaxhighlight lang="javascript">// Loop over multiple arrays simultaneously
var arr1: string[] = ['a', 'b', 'c'];
var arr2: string[] = ['A', 'B', 'C'];
Line 3,923 ⟶ 4,423:
for (var i = 0; i <= 2; i++)
console.log(`${arr1[i]}${arr2[i]}${arr3[i]}`);
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,941 ⟶ 4,441:
{{works with|Bourne Shell}}
 
<langsyntaxhighlight lang="bash">a=a:b:c
b=A:B:C
c=1:2:3
Line 3,956 ⟶ 4,456:
i=`expr $i + 1`
done
IFS=$oldifs</langsyntaxhighlight>
 
{{out}}
Line 3,978 ⟶ 4,478:
{{works with|Bourne Shell}}
 
<langsyntaxhighlight lang="bash">A='a1 a2 a3'
B='b1 b2 b3'
 
Line 3,986 ⟶ 4,486:
printf "$a $1\n"
shift
done</langsyntaxhighlight>
 
{{out}}
Line 4,002 ⟶ 4,502:
{{works with|ksh93}}
 
<langsyntaxhighlight lang="bash">a=(a b c)
b=(A B C)
c=(1 2 3)
for ((i = 0; i < ${#a[@]}; i++)); do
echo "${a[$i]}${b[$i]}${c[$i]}"
done</langsyntaxhighlight>
 
{{out}}
Line 4,019 ⟶ 4,519:
{{works with|pdksh}}
 
<langsyntaxhighlight lang="bash">set -A a a b c
set -A b A B C
set -A c 1 2 3
Line 4,026 ⟶ 4,526:
echo "${a[$i]}${b[$i]}${c[$i]}"
((i++))
done</langsyntaxhighlight>
 
{{works with|zsh}}
 
<langsyntaxhighlight lang="bash">a=(a b c)
b=(A B C)
c=(1 2 3)
for ((i = 1; i <= $#a; i++)); do
echo "$a[$i]$b[$i]$c[$i]"
done</langsyntaxhighlight>
 
==={{header|C Shell}}===
Line 4,042 ⟶ 4,542:
shell to exit with an error like ''b: Subscript out of range.''
 
<langsyntaxhighlight lang="csh">set a=(a b c)
set b=(A B C)
set c=(1 2 3)
Line 4,049 ⟶ 4,549:
echo "$a[$i]$b[$i]$c[$i]"
@ i += 1
end</langsyntaxhighlight>
 
=={{header|Ursa}}==
Looping over multiple arrays in an interactive session:
<langsyntaxhighlight lang="ursa">> decl string<> a b c
> append (split "abc" "") a
> append (split "ABC" "") b
Line 4,063 ⟶ 4,563:
bB2
cC3
> _</langsyntaxhighlight>
If either of the arrays are smaller than (size a), then an indexerror is thrown. This could be caught with a <code>try...catch</code> block.
 
Line 4,069 ⟶ 4,569:
Compute the transpose of the list formed of the three lists.
If they're of unequal lengths, an exception occurs.
<langsyntaxhighlight Ursalalang="ursala">#show+
 
main = ~&K7 <'abc','ABC','123'></langsyntaxhighlight>
{{out}}
<pre>
Line 4,080 ⟶ 4,580:
 
=={{header|Vala}}==
<langsyntaxhighlight lang="vala">const char a1[] = {'a','b','c'};
const char a2[] = {'A','B','C'};
const int a3[] = {1, 2, 3};
Line 4,087 ⟶ 4,587:
for (int i = 0; i < 3; i++)
stdout.printf("%c%c%i\n", a1[i], a2[i], a3[i]);
}</langsyntaxhighlight>
 
=={{header|VBA}}==
{{works with|VBA|VBA Excel 2013}}
<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 </lang>
{{out}}
<pre>
aA1
bB2
cC3
</pre>
 
=={{header|VBScript}}==
<langsyntaxhighlight lang="vb">' Loop over multiple arrays simultaneously - VBScript - 08/02/2021
 
a = Array("a","b","c")
Line 4,118 ⟶ 4,598:
buf = buf & vbCrLf & a(i) & b(i) & c(i)
Next
WScript.Echo Mid(buf,3) </langsyntaxhighlight>
{{out}}
<pre>
Line 4,126 ⟶ 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")
<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</lang>
 
{{out}}
<pre>aA1
aA1
bB2
cC3
</pre>
 
aA1
bB2
cC3</pre>
 
=={{header|Visual FoxPro}}==
<langsyntaxhighlight lang="vfp">
LOCAL i As Integer, n As Integer, c As String
LOCAL ARRAY a1[3], a2[3], a3[4], a[3]
Line 4,196 ⟶ 4,664:
? "Solution using a cursor"
LIST OFF FIELDS c4
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,213 ⟶ 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 {
println('${arrays[0][i]}${arrays[1][i]}${arrays[2][i]}')
}
}</langsyntaxhighlight>
 
=={{header|Wart}}==
<langsyntaxhighlight lang="wart">each (x X n) (zip '(a b c) '(A B C) '(1 2 3))
prn x X n</langsyntaxhighlight>
 
=={{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.
<langsyntaxhighlight ecmascriptlang="wren">var a1 = ["a", "b", "c"]
var a2 = ["A", "B", "C"]
var a3 = [1, 2, 3]
for (i in a3) System.print("%(a1[i-1])%(a2[i-1])%(i)")</langsyntaxhighlight>
 
{{out}}
Line 4,242 ⟶ 4,710:
{{works with|nasm}}
{{works with|windows}}
<langsyntaxhighlight lang="asm">
extern _printf
 
Line 4,294 ⟶ 4,762:
xor eax, eax
ret
</syntaxhighlight>
</lang>
 
=={{header|XBasic}}==
{{works with|Windows XBasic}}
<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
</lang>
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">string 0; \use zero terminated strings
include c:\cxpl\codes; \intrinsic 'code' declarations
char A1, A2;
Line 4,329 ⟶ 4,778:
CrLf(0);
];
]</langsyntaxhighlight>
 
{{out}}
Line 4,339 ⟶ 4,788:
 
=={{header|Z80 Assembly}}==
<langsyntaxhighlight lang="z80">org &1000
 
 
Line 4,366 ⟶ 4,815:
db "ABC"
array3:
db "123"</langsyntaxhighlight>
 
{{out}}
Line 4,381 ⟶ 4,830:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">foreach a,b,c in (["a".."c"].zip(T("A","B","C"),[1..])){ println(a,b,c) }</langsyntaxhighlight>
or
<langsyntaxhighlight lang="zkl">Utils.zipWith(False,fcn{vm.arglist.concat().println()},
["a".."c"],T("A","B","C"),[1..])</langsyntaxhighlight>
{{out}}
<pre>
Line 4,395 ⟶ 4,844:
 
=={{header|Zig}}==
<lang zig>const std = @import("std");
 
===Limit by minimum length===
const a1: []const u8 = &[_]u8{ 'a', 'b', 'c' };
'''Works with''': 0.10.x
const a2: []const u8 = &[_]u8{ 'A', 'B', 'C' };
const a3: []const u8 = &[_]u8{ '1', '2', '3' };
 
<syntaxhighlight lang="zig">const std = @import("std");
pub fn main() !void {
for (a1) |_, i|
try std.io.getStdOut().writer().print("{c} {c} {d}\n", .{ a1[i], a2[i], a3[i] });
}</lang>
 
const arr1 = [_]u8{ 'a', 'b', 'c' };
=={{header|ZX Spectrum Basic}}==
const arr2 = [_]u8{ 'A', 'B', 'C' };
const arr3 = [_]u8{ '1', '2', '3' };
 
pub fn main() std.fs.File.WriteError!void {
<lang zxbasic>10 LET sza = 3: REM size of a
const stdout = std.io.getStdOut();
20 LET szb = 3: REM size of b
const stdout_w = stdout.writer();
30 LET szc = 3: REM size of c
const n = std.math.min3(arr1.len, arr2.len, arr3.len);
40 DIM a$(sza): DIM b$(szb): DIM c$(szc)
for (arr1[0..n]) |arr1_e, i| {
50 LET max = sza: REM assume a is the biggest
try stdout_w.print("{c} {c} {c}\n", .{ arr1_e, arr2[i], arr3[i] });
60 IF szb > max THEN LET max = szb: REM now try b
}
70 IF szc > max THEN LET max = szc: REM or c
}</syntaxhighlight>
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"</lang>
 
'''Works with''': 0.11.x, 0.12.0-dev.1381+61861ef39
Simplification
 
<syntaxhighlight lang="zig">const std = @import("std");
<lang zxbasic>10 READ size: DIM a$(size): DIM b$(size): DIM c$(size)
 
20 FOR i=1 TO size
const arr1 = [_]u8{ 'a', 'b', 'c' };
30 READ a$(i),b$(i),c$(i)
const arr2 = [_]u8{ 'A', 'B', 'C' };
40 PRINT a$(i);b$(i);c$(i)
const arr3 = [_]u8{ '1', '2', '3' };
50 NEXT i
 
60 DATA 3,"a","A","1","b","B","2","c","C","3"</lang>
pub fn main() std.fs.File.WriteError!void {
const stdout = std.io.getStdOut();
const stdout_w = stdout.writer();
const n = @min(arr1.len, arr2.len, arr3.len);
for (arr1[0..n], arr2[0..n], arr3[0..n]) |arr1_e, arr2_e, arr3_e| {
try stdout_w.print("{c} {c} {c}\n", .{ arr1_e, arr2_e, arr3_e });
}
}</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