I ran through questions with similar titles but could not find them anywhere. Suppose I have a for loop (regardless of the programming language)
for (i=0; i < n; i++)
for (j=0; j < m; j++)
k = ...
print("k is: " + k)
I now want to calculate k
based ONLY on i
and j
where k
is the iteration count. So for example when n=2
and m=2
than we should get
k is 0
k is 1
k is 2
k is 3
Is this possible only using i
and j
or do I need to introduce another variable which gets incremented each time? This question is more theoretical as one can always simply solve an actual problem by using a counter. Note: starting at one in the print is also good.
You cannot do it without knowing either m or n
k = i * m + j
Or
k = i + j * n
And to start by 1:
k = i * m + j + 1
or
k = i + j * n + 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.