Two counters in a for loop for C#
12,480
Solution 1
If I am understanding correctly, you want this:
for (int j = mediumNum, k = 0; j < hardNum && k < mediumNum; j++, k++)
Solution 2
It might express your intent better to use a while
loop, perhaps making the code a little easier to read:
int j = mediumNum;
int k = 0;
while (j < hardNum && k < mediumNum)
{
//...
j++;
k++;
}
Solution 3
This is what you want
for (int j = mediumNum, k = 0; j < hardNum && k < mediumNum; j++, k++)
Solution 4
I wonder if you know for sure that both loops always terminate at the same time. If not, the body of the loop will have to account for that.
int j;
int k;
for (j = mediumNum, k = 0; j < hardNum && k < mediumNum; j++, k++);
Author by
Sarp Kaya
Updated on June 20, 2022Comments
-
Sarp Kaya almost 2 years
Hi couldn't find it for C#, I am trying something like that
for (int j = mediumNum; j < hardNum; j++; && int k = 0; k < mediumNum; k++);
but it does not work. Any valid method???
-
Tony Hopkinson almost 12 yearsI agree, well described intent is much better than jam eveything on to one line.
-
Paul Phillips almost 12 years@RobertHarvey Yes, although I would probably never use it
-
Paul Phillips almost 12 yearsI prefer the
while
loop for clarity; nesting it on one line is hard to scan. -
David almost 12 years@PaulPhillips: The community at large seems to prefer your solution :) Probably because it's kind of clever. I've never seen that comma notation in the loop arguments like that. Can't say I can think of a need for it off the top of my head (though I can't even think of the last time I used
for
instead offoreach
these days), but it's interesting to know it exists.