Why are variables "i" and "j" used for counters?
Asked Answered
P

23

179

I know this might seem like an absolutely silly question to ask, yet I am too curious not to ask...

Why did "i" and "j" become THE variables to use as counters in most control structures?

Although common sense tells me they are just like X, which is used for representing unknown values, I can't help to think that there must be a reason why everyone gets taught the same way over and over again.

Is it because it is actually recommended for best practices, or a convention, or does it have some obscure reason behind it?

Just in case, I know I can give them whatever name I want and that variables names are not relevant.

Panfish answered 9/11, 2010 at 19:45 Comment(16)
i=iteration while j=after interationMagdamagdaia
strange 'c' was not choosen? as in the Intel 'cx' counter register.Likeminded
I seen n a lot standing for number. occasionally i see z. i dont see j as much as i see n and z.Pesthouse
Is this the only SO question with no single-digit-scoring answers?Cath
Cartesian coordinatesEgbert
interesting question, never thought of it..Richy
i have always thinked to it as "i = integer" but as soon you have at least 3 loops you should use your fantasy so i, j, e, n, etc... ;)Baccalaureate
I use N, as on ZX Spectrum, it was normal to pres N twice and get NEXT n :) - it stuck and it won't go away.Ashjian
As an aside, I tend to use xi and xj as I avoid one letter variables names - they are hard to search for in your code.Privy
@snmcdonald Actually, i and j predates Intel being involved with computing. Besides, cx is a newfangled thing -- in my time there was ah, bc and de as general registers. Then there was f for flags and... i for index! :-) All index based ops used i.Manly
The j part should be obvious.Wingding
Why do actual questions become community wikis just because they're popular? This feels very reminiscent of communism. If somebody invents something really cool, the government steals the invention to share with the community.Wingding
Closed wrong way: the answers here are more informative than to the other qn...Arce
Maybe the other question should be closed and merged with this one. The phrasing of a question is also very important. For some reason in 29 days it got 44k views in comparison to 2k in 1 year.Panfish
I think someone felt sorry for the letter j. Living in the shadow of its' well used and complex neighbour i it has never received any real attention.Belgrade
@AndreasGrech: Wtf? integers ARE real.Unity
O
328

It comes ultimately from mathematics: the summation notation traditionally uses i for the first index, j for the second, and so on. Example (from http://en.wikipedia.org/wiki/Summation):

\sum_{i=1}^{n} i = \frac{n^2 + n}{2}

It's also used that way for collections of things, like if you have a bunch of variables x1, x2, ... xn, then an arbitrary one will be known as xi.

As for why it's that way, I imagine SLaks is correct and it's because I is the first letter in Index.

Osteitis answered 9/11, 2010 at 19:45 Comment(31)
agreed. WAAAY older than FortranRostrum
-1: "because I is the first letter in Index". No earthly way. It's the mathematics thing.Pressman
@SLott: And why is i used in math?Masao
@Slaks: That's a good question. I actually think that "i" might come from integer more than index. I also think it's easy to write on a chalkboard. Back in the 70's we were cautioned to be sure that we wrote our "i" and "j" in a perfectly distinctive manner. Indeed, we were told to draw our "i" exactly like a backwards "j" to be perfectly clear about it.Pressman
Huh. I always imagined it was "i" for "iterator".Last
Nowadays I use ii, jj, kk as my index variables, because "i" is the square root of -1, and "j" is the current.Last
@S.Lott: I doubt it comes from integer. We use ℤ (blackboard bold Z) for the integers because it stands for the German word Zahlen, which means numbers. Assuming that the summation notation arose at around the same time, the German-based notation would be expected—and the German word for index is Index, which also begins with an i. And I can't think of many letters which are particularly hard to write on a chalkboard. Well, except ξ :-)Oran
Honestly, this answer is ridiculous. "This convention exists because this convention has existed before." I'm not disputing that it comes from math (it does), but nobody seems to know where the convention first originated from. I've been asking this question for 10 years... nobody knows.Wommera
"This convention exists because this convention has existed before." That's kind of how etymology works: nobody knows why a particular noise had a particular meaning in PIE. It would be nice to explain the mathematical convention, but the question is "why are they used as counters in control structures", so until someone produces an answer that goes back further, this is the best. It does at least speculate why it's used in mathematics. A proper mathematical historian could find out, maybe using a binary chop. Euclid didn't use it, I bet von Neumann did. How about Cauchy? He used indexes a lotCalan
@Antal: I'm really disappointed that HTML doesn't have entity names &squiggle; for xi and &othersquiggle; for zeta. That's what we called them.Calan
I still remember the day I asked my Physics 101 instructor "What is that scribble you seem to be using as a variable?"Osteitis
@Steve: I've heard squiggle for zeta and double squiggle for xi, I think. I'm not convinced that the Greeks weren't just playing a practical joke on the future :-) On a slightly more topical note, I wonder if there's been any work on mathematical etymology before. It'd be interesting to find out where things like for "normal subgroup" or for "and" come from.Oran
@Antal: Ask Abel and Boole respectively ;-)Calan
@jon_darkstar, the convention may be older than FORTRAN but FORTRAN used them as implicit type declarations putting the convention if you will into code. No doubt though it was highly convenient for I in Integer.Beget
The oldest I found is by Henri Poincaré in 1909: gutenberg.org/ebooks/15267 PDF page 35Sestertium
@starblue: I also found that, and it's a really neat site, but I didn't see i and j listed, unfortunately.Oran
@Antal That was for your question in the comment w.r.t. (Heyting ca 1930).Sestertium
@Antal s-j: I'm pretty sure the bolded Z actually stands for "zählen" (very similar word). This word is the verb that means "to count" which would make it even more relevant to this conversation.Rap
@highriseo: Wikipedia gives the etymology as zahlen, as opposed to *zählen. In a (very) quick Google search, the other things I could find confirmed that.Oran
It's also a good example for bad notation habits from math leaking into programming.Repletion
I think it was Lagrange who recommended using a,b,c for constants of a function, and x,y,z for variables of a function. i,j,k denote the 'directions' of a vector, and the factors of a formal sum like this can be construed as degrees of freedom [directions, by another name] of the equation.Pirate
@sakra, why do you describe this as a "bad notation habit" (irregardless of where it comes from)?Osteitis
@Zack, short variable names and in particular one letter variable names are too cryptic.Repletion
This answer is nonsense. The fact that summations roll on i often is just as intriguing as the fact that for loops do.Emmalynn
@sakra, I couldn't disagree more; long variable names can hinder readability just as easily as short ones can, and array indices in particular need to be short so they aren't in the way of comprehending the larger expression.Osteitis
@Repletion Research has shown that identifier length does improve code comprehension, and can even hinder it (bit.ly/dHGD1i, bit.ly/hd8GBa). So, which is the bad notation habit now?Manly
@Daniel C. Sobral: The second paper you quote does not speak out for using single letter identifiers.Repletion
@Repletion But it goes the other way, saying large identifiers are harmful.Manly
@sakra: Single-letter variables in math are essential, since not only do they often have no intrinsic meaning, but would also render an expression completely unreadable with more verbose names. It makes sense therefore to treat mathematically purposed variables in programming in a similar way, by giving them terse names that do not distract from the larger structures that they form. Can you imagine try to express something like this with longer names? en.wikipedia.org/wiki/Frobenius_method#ExplanationTropo
beause of the density of meaningful i names in order of relevance - iterator, index, integer - I predict a new word will evovle to describe iterator variables used in control structures. Itex - short sweet and it has an x in it which is cool.Dysphemism
it's because engineers use i,j,k for the direction vectors for the 3 axisJaguar
P
200

I believe it dates back to Fortran. Variables starting with I through Q were integer by default, the others were real. This meant that I was the first integer variable, and J the second, etc., so they fell towards use in loops.

Poplar answered 9/11, 2010 at 19:45 Comment(8)
I think this comes from the way mathematicians seem to like to use i, j, k as handy subscripts for summation and matrix multiplication indices and what-not. I remember reading in an early Fortran II manual something about that. (Yes, Fortran II.)Pressman
Yes, FORTRAN originates these conventions.Beget
I was taught I through N not Q. Google seems to mostly agree. (different versions of FORTRAN?)Calamity
And everything else in Fortran was, by default, real. Which leads to the joke "God is real, unless declared integer".Pure
Nice answer. This is my favourite on the page. It begs the follow up question as to why Fortran was designed like that?Peanuts
@Peanuts - because mathematicians had been using i,j for at least a century beforehand.Damascus
because i stands for integer - duh! - and in the Fortran 66/77 I used to write it was also i through n. Until I started using Erlang I would always start integer variables with a lower case n, like nFlags. But in Erlang nFlags is an atom and NFlags is just wrong, so the final trace of Fortran has slipped through my fingers (cue tiny violins)Gilmer
We all learned very early to start our Fortran programs with 'implicit none' to disable the behavior.Millsaps
T
195

Mathematicians were using i,j,k to designate integers in algebra (subscripts, series, summations etc) long before (e.g 1836 or 1816) computers were around (this is the origin of the FORTRAN variable type defaults). The habit of using letters from the end of the alphabet (...,x,y,z) for unknown variables and from the beginning (a,b,c...) for constants is generally attributed to Rene Descartes, (see also here) so I assume i,j,k...n (in the middle of the alphabet) for integers is likely due to him too.

Tallahassee answered 18/1, 2009 at 0:54 Comment(4)
To me, this is clearly the best answer. (Honorable mention for Michael Borgwardt's answer, which also cites mathematical convention but isn't as specific.) I'm sorry yours isn't the accepted one. All I can do is give it my upvote.Jaundiced
This is exactly the reason that the we need to be able to vote for a community accepted answer (and yeah I know this belongs on uservoice).Depersonalization
Heh. I occasionally update the link to an old google book in this answer because google keeps chopping stuff around. By chance, I note the 1816 document now linked includes Charles Babbage (presumably he of difference engine/analytical engine fame) as an author. So arguably it's an example of the first use of an integer variable "i" by a computer programmer :^)Tallahassee
..OK the 1816 link doesn't go to page with "i" used on it, but they're there.Tallahassee
P
129

i = integer

Comes from Fortran where integer variables had to start with the letters I through N and real variables started with the other letters. Thus I was the first and shortest integer variable name. Fortran was one of the earliest programming languages in widespread use and the habits developed by programmers using it carried over to other languages.

EDIT: I have no problem with the answer that it derives from mathematics. Undoubtedly that is where the Fortran designers got their inspiration. The fact is, for me anyway, when I started to program in Fortran we used I, J, K, ... for loop counters because they were short and the first legally allowed variable names for integers. As a sophomore in H.S. I had probably heard of Descartes (and a very few others), but made very little connection to mathematics when programming. In fact, the first course I took was called "Fortran for Business" and was taught not by the math faculty, but the business/econ faculty.

For me, at least, the naming of variables had little to do with mathematics, but everything due to the habits I picked up writing Fortran code that I carried into other languages.

Photocomposition answered 9/11, 2010 at 19:45 Comment(11)
I through N in F77, but close enough. Also I think this is more likely the reason rather than i == iterator or i == indexSuspicious
I'm pretty sure it was FORTRAN.Margarito
Ya, fortran..... It rots the mind. We have a programmer that uses i ii and iii as loop variable names. The other symptom is 6 character variable/function names with no vowels.Chitwood
@tvan, I'm pretty sure variables starting with I through N defaulted to integer, but you could still declare them real hence the joke "God is real, unless declared integer". +1 anyway, since my recollection from so many years ago may possibly NOT be perfect.Cousins
Hey, the FORTRAN guys got it off the mathematicians!Tallahassee
I love historical artifacts like this. It adds depth to programming, and makes me feel connected to the past.Cassondracassoulet
@Pax -- declarations didn't come along until F66 (en.wikipedia.org/wiki/Fortran#FORTRAN).Photocomposition
@Pax - your memory is correct, though as @Photocomposition says only for the later versions of FORTRAN.Carrier
Well there you go, I assummed it was an abreivation for indexSkeen
I agree with @timday. Using i as an index of a series has been a practice by mathematicians for at least 2 centuries.Vacate
Not i for iteration? if i stands for integer, then what do j and k stand for?Unity
M
91

i stands for Index.
j comes after i.

Masao answered 9/11, 2010 at 19:45 Comment(6)
I think he was talking about alphabet, try to use some imagination :)Mellott
@Jack: I think @Pete was joking ;-)Corkhill
@Cpfohl: yep, just wanted to be boring :DMellott
@Pete Kirkham: Thank you very much Pete, it was the best laugh I had in the past month.Appease
@Masao ... I believe your right it does i=Index which comes from index notation used in Math en.wikipedia.org/wiki/Index_notation or here is a nice reference physics.ucsb.edu/~physCS31/fall2010/index-notation.pdfHeiduc
@Slaks: I guessing because people disagreed with you, and this is, after all, a subjective questions calling for a high degree of postulation.Gaytan
E
63

These symbols were used as matrix indexes in mathematics long before electronic computers were invented.

Englis answered 9/11, 2010 at 19:45 Comment(0)
C
52

I think it's most likely derived from index (in the mathematical sense) - it's used commonly as an index in sums or other set-based operations, and most likely has been used that way since before there were programming languages.

Carisa answered 17/1, 2009 at 23:39 Comment(3)
Good answer. This (to me) indeed seems like the most probable explanation.Agamemnon
Yup. The mathematic notation for a sum like Y = Σ Xi precedes every programming language.Dictatorship
I am thinking of index each time I use i. But originally I use it mainly because all code I look at elsewhere use it, and that may be inherited from Fortran programmers...Bignoniaceous
A
47

There's a preference in maths for using consecutive letters in the alphabet for "anonymous" variables used in a similar way. Hence, not just "i, j, k", but also "f, g, h", "p, q, r", "x, y, z" (rarely with "u, v, w" prepended), and "α, β, γ".

Now "f, g, h" and "x, y, z" are not used freely: the former is for functions, the latter for dimensions. "p, q, r" are also often used for functions.

Then there are other constraints on available sequences: "l" and "o" are avoided, because they look too much like "1" and "0" in many fonts. "t" is often used for time, "d & δ" for differentials, and "a, s, m, v" for the physical measures of acceleration, displacement, mass, and velocity. That leaves not so many gaps of three consecutive letters without unwanted associations in mathematics for indices.

Then, as several others have noticed, conventions from mathematics had a strong influence on early programming conventions, and "α, β, γ" weren't available in many early character sets.

Arce answered 9/11, 2010 at 19:45 Comment(1)
Agreed. Although, a, b, c is a fairly commonly used sequence despite a having multiple meanings...Lipstick
P
32

I found another possible answer that could be that i, j, and k come from Hamilton's Quaternions.

alt text

Euler picked i for the imaginary unit.

Hamilton needed two more square roots of -1: ii = jj = kk = ijk = -1

Hamilton was really influential, and quaternions were the standard way to do 3D analysis before 1900. By then, mathematicians were used to thinking of (ijk) as a matched set. Vector calculus replaced quaternionic analysis in the 1890s because it was a better way to write Maxwell's equations. But people tended to write vector quantities as like this: (3i-2j+k) instead of (3,-2,1). So (ijk) became the standard basis vectors in R^3.

Finally, physicists started using group theory to describe symmetries in systems of differential equations. So (ijk) started to connote "vectors that get swapped around by permutation groups," then drifted towards "index-like things that take on all possible values in some specified set," which is basically what they mean in a for loop.

Panfish answered 9/11, 2010 at 19:45 Comment(1)
at last a different approach to the question, interesting point +1Copperas
L
30

by discarding (a little biased)

a seems an array
b seems another array 
c seems a language name
d seems another language name
e seems exception
f looks bad in combination with "for" (for f, a pickup?)
g seems g force
h seems height

i seems an index                    
j seems i (another index)

k seems a constant k
l seems a number one (1) 
m seems a matrix
n seems a node
o seems an output
p sounds like a pointer
q seems a queue
r seems a return value
s seems a string
t looks like time
u reserved for UVW mapping or electic phase 
v reserved for UVW mapping or electic phase or a vector
w reserved for UVW mapping or electic phase or a weight
x seems an axis (or an unknown variable)
y seems an axis
z seems a third axis
Levant answered 9/11, 2010 at 19:45 Comment(3)
I see n as number, usually the number of elements in a set.Inconceivable
Oh men, and what XXX seem to be? )) +1 for the creativity ;)Evalyn
Sometimes i'm glad that most of the time i don't have to bother with what sorts of mnemonics other people come up with in their heads for things like that...Arnettaarnette
M
21

One sunny afternoon, Archimedes what pondering (as was usual for sunny afternoons) and ran into his buddy Eratosthenes.

Archimedes said, "Archimedes to Eratosthenes greeting! I'm trying to come up with a solution to the ratio of several spherical rigid bodies in equilibrium. I wish to iterate over these bodies multiple times, but I'm having a frightful time keeping track of how many iterations I've done!"

Eratosthenes said, "Why Archimedes, you ripe plum of a kidder, you could merely mark successive rows of lines in the sand, each keeping track of the number of iterations you've done within iteration!"

Archimedes cried out to the world that his great friend was undeniably a shining beacon of intelligence for coming up with such a simple solution. But Archimedes remarked that he likes to walk in circles around his sand pit while he ponders. Thus, there was risk of losing track of which row was on top, and which was on bottom.

"Perhaps I should mark these rows with a letter of the alphabet just off to the side so that I will always know which row is which! What think you of that?" he asked, then added, "But Eratosthenes... whatever letters shall I use?"

Eratosthenes was sure he didn't know which letters would be best, and said as much to Archimedes. But Archimedes was unsatisfied and continued to prod the poor librarian to choose, at least, the two letters that he would require for his current sphere equilibrium solution.

Eratosthenes, finally tired of the incessant request for two letters, yelled, "I JUST DON'T KNOW!!!"

So Archimedes chose the first two letters in Eratosthenes' exclamatory sentence, and thanked his friend for the contribution.


These symbols were quickly adopted by ancient Greek Java developers, and the rest is, well... history.

Montgolfier answered 9/11, 2010 at 19:45 Comment(2)
... and had the letter j.Marshy
Wow, that nearly reads like a Tortoise and Achilles's story from Hofstadter's G.E.B.Semolina
D
15

i think it's because a lot of loops use an Int type variable to do the counting, like

for (int i = 0; etc

and when you type, you actually speak it out in your head (like when you read), so in your mind, you say 'int....'

and when you have to make up a letter right after that 'int....' , you say / type the 'i' because that is the first letter you think of when you've just said 'int'

like you spell a word to kids who start learning reading you spell words for them by using names, like this:

WORD spells William W, Ok O, Ruby R, Done D

So you say Int I, Double d, Float f, string s etc. based on the first letter.

And j is used because when you have done int I, J follows right after it.

Disputatious answered 9/11, 2010 at 19:45 Comment(1)
That's a great way to confuse the crap out of a kid; you really teach yours to spell like that?!Disciplinarian
D
14

I think it's a combination of the other mentioned reasons :

For starters, 'i' was commonly used by mathematicians in their notation, and in the early days of computing with languages that weren't binary (ie had to be parsed and lexed in some fashion), the vast majority of users of computers were also mathematicians (... and scientists and engineers) so the notation fell into use in computer languages for programming loops, and has kind of just stuck around ever since.

Combine this with the fact that screen space in those very early days was very limited, as was memory, it made sense to keep shorter variable names.

Deer answered 9/11, 2010 at 19:45 Comment(0)
R
13

Possibly historical ?

FORTRAN, aurguably the first high level language, defined i,j,k,l,m as Integer datatypes by default, and loops could only be controlled by integer variable, the convention continues ?

eg:

do 100 i= j,100,5 .... 100 continue ....

Reathareave answered 17/1, 2009 at 23:48 Comment(1)
FWIW, I usually skip the letter l because it looks too much like the number 1.Sacroiliac
V
13

i = iterator, i = index, i = integer

Which ever you figure "i" stands for it still "fits the bill".

Also, unless you have only a single line of code within that loop, you should probably be naming the iterator/index/integer variable to something more meaningful. Like: employeeIndex

BTW, I usually use "i" in my simple iterator loops; unless of course it contains multiple lines of code.

Viperous answered 2/6, 2009 at 1:24 Comment(0)
R
13

Well from Mathematics: (for latin letters)

a,b: used as constants or as integers for a rational number
c: a constant
d: derivative
e: Euler's number
f,g,h: functions
i,j,k: are indexes (also unit vectors and the quaternions)
l: generally not used. looks like 1
m,n: are rows and columns of matrices or as integers for rational numbers
o: also not used (unless you're in little o notation)
p,q: often used as primes
r: sometimes a spatial change of variable other times related to prime numbers
s,t: spatial and temporal variables or s is used as a change of variable for t
u,v,w: change of variable
x,y,z: variables

Redhanded answered 9/11, 2010 at 19:45 Comment(0)
C
13

i = iota, j = jot; both small changes.

iota is the smallest letter in the greek alphabet; in the English language it's meaning is linked to small changes, as in "not one iota" (from a phrase in the New Testament: "until heaven and earth pass away, not an iota, not a dot, will pass from the Law" (Mt 5:18)).

A counter represents a small change in a value.

And from iota comes jot (iot), which is also a synonym for a small change.

cf. http://en.wikipedia.org/wiki/Iota

Corm answered 9/11, 2010 at 19:45 Comment(0)
L
11

Many possible main reasons, I guess:

  • mathematicians use i and j for Natural Numbers in formulas (the ones that use Complex Numbers rarely, at least), so this carried over to programming
  • from C, i hints to int. And if you need another int then i2 is just way too long, so you decide to use j.
  • there are languages where the first letter decides the type, and i is then an integer.
Loathly answered 9/11, 2010 at 19:45 Comment(0)
V
10

It comes from Fortran, where i,j,k,l,m,n are implicitly integers.

Vicenta answered 9/11, 2010 at 19:45 Comment(0)
H
7

It definitely comes from mathematics, which long preceded computer programming.

So, where did if come from in math? My completely uneducated guess is that it's as one fellow said, mathematicians like to use alphabetic clusters for similar things -- f, g, h for functions; x, y, z for numeric variables; p, q, r for logical variables; u, v, w for other sets of variables, especially in calculus; a, b, c for a lot of things. i, j, k comes in handy for iterative variables, and that about exhausts the possibilities. Why not m, n? Well, they are used for integers, but more often the end points of iterations rather than the iterative variables themselves.

Someone should ask a historian of mathematics.

Hance answered 9/11, 2010 at 19:45 Comment(0)
C
6

Counters are so common in programs, and in the early days of computing, everything was at a premium...
Programmers naturally tried to conserve pixels, and the 'i' required fewer pixels than any other letter to represent. (Mathematicians, being lazy, picked it for the same reason - as the smallest glyph).
As stated previously, 'j' just naturally followed...

:)

Cathicathie answered 9/11, 2010 at 19:45 Comment(4)
In the early days of computing, pixels didn't exist.Masao
@Slaks, that is one winning comment. Just see the grin on my face reading it, and the votes. Nice!Semolina
"Programmers naturally tried to conserve pixels, and the 'i' required fewer pixels than any other letter to represent." <<< that is hilarious.Tret
...and thus, premature optimization was born!Cathicathie
S
4

I use it for a number of reasons.

  • Usually my loops are int based, so you make a complete triangle on the keyboard typing "int i" with the exception of the space I handle with my thumb. This is a very fast sequence to type.

  • The "i" could stand for iterator, integer, increment, or index, each of which makes logical sense.

With my personal uses set aside, the theory of it being derived from FORTRAN is correct, where integer vars used letters I - N.

Swashbuckler answered 17/1, 2009 at 23:42 Comment(0)
C
4

I learned FORTRAN on a Control Data Corp. 3100 in 1965. Variables starting with 'I' through 'N' were implied to be integers. Ex: 'IGGY' and 'NORB' were integers, 'XMAX' and 'ALPHA' were floating-point. However, you could override this through explicit declaration.

Chesney answered 9/11, 2010 at 19:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.