We know that, somehow, we use i
and j
variables in loops very commonly. If one need a double for
loop, it's very likely to use something like the following:
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
// do some stuff...
}
}
However, if I need a third for
loop in these loops, I don't have any naming convention for the third iterator. I, likely use the following variables: r
, k
, ii
, jj
etc...
Is there a naming convention for the third (and so on...) loop's iterator?
In the "while" example, the iterator is declared outside the loop, so it will continue to exist after the loop is done. This may cause issues if this same iterator is used again at some later point.
Iterators power for loops Instead, Python's for loops use iterators. Iterators are the things that power iterables. You can get an iterator from any iterable. And you can use an iterator to manually loop over the iterable it came from.
This RFC proposes to instead align the convention with the iter module: the name of an iterator type should be the same as the method that produces the iterator. For example: iter would yield an Iter.
"i" is a temporary variable used to store the integer value of the current position in the range of the for loop that only has scope within its for loop. You could use any other variable name in place of "i" such as "count" or "x" or "number".
The most important thing for readability should be obvious names.
i and j aren't the most obvious, but may be ok for simple cases. Consider this (admittedly somewhat ill thought out) example;
static void Main(string[] args)
{
for(int i = 0; i < 100; i++)
for (int j = 0; j < 100; j++)
for (int k = 0; k < 100; k++)
Console.WriteLine("" + i + "-" + j + "-" + k);
}
vs
static void Main(string[] args)
{
for(int survey = 0; survey < 100; survey++)
for (int question = 0; question < 100; question++)
for (int option = 0; option < 100; option++)
Console.WriteLine("" + survey + "-" + question + "-" + option);
}
It's quite easy to see which makes more sense to read. But while we're at it, how about making it even more readable while eliminating your naming problem even more;
static void Main(string[] args)
{
for(int survey = 0; survey < 100; survey++)
PrintSurvey(survey);
}
private static void PrintSurvey(int survey)
{
for (int question = 0; question < 100; question++)
PrintQuestion(survey, question);
}
private static void PrintQuestion(int survey, int question)
{
for (int option = 0; option < 100; option++)
PrintOption(survey, question, option);
}
private static void PrintOption(int survey, int question, int option)
{
Console.WriteLine("" + survey + "-" + question + "-" + option);
}
Maybe overkill/verbose for this simple loop, just wanted to make the point that there are more ways you can deal with the naming problem for nested loops than just finding unique names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With