0

I assume there is some historical/mathematical reason that whenever I write I for loop, I use i:

for (var i=0; i<10; i++) {
  // do something 10 times
}

I know i is used in mathematics for summations (Σ) and products (∏). Does it just mean "index", or is there some more significant meaning?

Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187
smfoote
  • 5,268
  • 5
  • 30
  • 37

2 Answers2

0

I believe it does just mean "index" in the example mentioned.

I know it's not answering your question and probably stating the obvious but I personally would always try to give the variable name some meaning for readability and avoid this confusion when reading others code e.g.

for (int productCounter = 0; productCounter<10; productCounter++){ // do something 10 times }

  • 1
    Using 14 characters where one is sufficient? I'd rather not read your code, thanks. – Jonathan Leffler Jul 27 '13 at 22:03
  • Ah, but you could read it if you wanted!! Rather than try to work out what i represents. productCounter was just a example, use something less, just not i or x, it makes it so much easier read in a multi developer environment where you are maintaining others code or nested for loops! – Lee Mandeville Jul 29 '13 at 10:57
0

In Fortran, variables starting with letters I through M were automatically of type INTEGER, so people could write:

       DO 10 J = 1, 10
          ...do something 10 times...
10     CONTINUE

Labels were numeric in columns 1-5; column 6 was for the continuation character (if needed), and the code started in column 7 (originally up to column 72; column 73-80 on the punched card were for the card's sequence number in the deck).

Single letter names are convenient. In Fortran, you didn't have to declare the variables before you used them.

Jonathan Leffler
  • 698,132
  • 130
  • 858
  • 1,229