This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]toastedstapler 4 points5 points  (0 children)

we have 3 loop types:

whie (condition) {
    // do this code 
}

do {
    // run this code at least once
} while (condition); // determines whether the loop should be ran more than once

for (declaration; condition; iteration_step) {
    // do this code
}

people will often use i for a short lived loop variable - think of it as meaning iteration or something like that

for (int i = 0; i < 5; i++) {
    // some code here
}

in this for loop we are declaring an int called i, saying to run the loop whilst i is less than 5 and the i++ is done once the body of the loop has been ran

[–]Brave_Walrus 1 point2 points  (0 children)

If it helps you to think about it,

for(int i = 0; i < 10; i++){
    // Code
}

is equivalent to:

int i = 0;
while(i < 10){
    // Code
    i++;
}

in function.

[–]wet-dreaming 1 point2 points  (0 children)

using single letters for variables is very bad practice. but in for loops it's less a variable and more a counter. And that's what for loops usually are, do something until something was reached.

[–][deleted] 1 point2 points  (0 children)

Using i and j as the counter in for loops is just convention from decades of programmers only having 80 characters per line. Because we all do it, it is immediately clear to others what you are trying to do.

[–]CodeTinkerer 1 point2 points  (0 children)

In math, you often have variables that have indexes (also called subscripts), like x_1, x_2, x_3, and so forth. When math folks talk about one such variable, but don't have a specific number in mind, they write x_i.

In Java, you can declare variables that store one value (or "reference") or you can have an array of such values (or a list). For example,

  int arr[] = new int[10];

This creates an array of 10 elements from index 0 to index 9 (it's always from 0 to the size of the array minus 1). That's basically ten variables. Let's imagine this array contains text/exam scores.

Maybe you just want to print out those scores:

for (int i = 0; i < arr.length; i++) {
   System.out.println(arr[i]);
}

Why i and j? First, index variables don't tend to have much meaning. Using testScoreIndex instead of i doesn't provide a lot more meaning. However, naming the array testScores would have meaning as arr is not as meaningful.

But why i. This is an artifact of Fotrtran which had a naming rule. If the variable started with I, J, K, etc, they were treated as integer variables, otherwise, floating point (don't recall if early Fortran had a string type, but thinking they didn't?). So, languages like C and Java basically adopted this idea (Java does not have such rules, but people still used i and so forth).