Let's decouple, a bit, the iteration ranges (e.g. for loop control variable k
) and what they are iterating over.
Technically, the loop control variable(s) iterate over a range of integers, e.g. 1..m or 1..n (rather than over elements of the arrays).
So, a loop, via its loop control variable, nominally iterates over a range of integers, not necessarily elements of an array, though it can be used to iterate through array elements, within the body of the loop, by using subscripting/indexing expressions like X(k)
and Z(k)
in terms of the loop control variable.
What exactly does k represent?
There is no reason that the question has to have used the same variable name, k
, for both for-loops — but because it does use k
twice (rather than, say, k1
first loop and k2
later), k
means two different things in two different places. In Loop 1 k
is an index ranging from 1
to m
, which is the range of X
, and in Loop 2, k
is an index ranging from 1
to n
, which is the range of Y
.
m
is the number of elements in the array (the dimension)
Specifically, in the array X
— whereas n
is the number in Y
.
You already realize that the concatenation operation is concatenating X
with Y
not vice versa. Loop 1 then merely copies X
into (the first part of) Z
, character by character, and thus at each k
, a copy from X
into the same position in Z
.
Next, Loop 2 copies Y
into Z
— but where to place the elements in Z
, given that X
has already been copied into Z
?
In words, the answer is that the copy of (concatenation of) Y
should go after the copy of X
in Z
.
In variables, that translates such that the first element of Y
should go to the Z
position at m
because m
is (firstly) the length of X
, and also (secondly), it is where Loop 1 left off/stopped in Z
— in other words, just after loop 1 finishes, m
identifies the boundary between the last position used and the first free position in Z
. Since we want to copy the whole of Y
into Z
, then all the characters of Y
come from k
but go to m + k
in Z
.
So, to recap, m
is not only the size of X
, but also where Loop 1 finished copying into Z
. n
is merely the size of Y
. Note that X
's copy in Z
after Loop 1 now occupies Z(1..m)
, so then, the location where we want Y(1)
to go is Z(m + 1)
, Y(2)
to Z(m + 2)
, and so on, so that characters of Y
are all placed after the entire copy of X
in Z
.
The copy of X
in Z
occupies Z(1..m)
and the copy of Y
in Z
occupies Z(m..m+n)
, which is saying that the copy of X
's comes first and the copy of Y
comes directly after the copy of X
.
(If you work through a real example, e.g. concatenate "hi " with "world", you'll see how this comes together.)