0

I am trying to understand the logic behind how a for loop actually iterates through an array. Take this example, in which I will use Java:

int[] numbers = {5, 6, 7};

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

I do not understand how printing numbers[i] cycles through the array. More specifically, I do not understand how i comes to represent the contents of the array.

3
  • The variable i is just a dummy index which is used to represent the position in the array, as the loop is evaluating. If you still don't grasp this, I recommend hitting up a good Java/programming tutorial, and focus on the syntax of loops. Commented Sep 20, 2018 at 13:33
  • 1
    The numbers[i] construct does not cycle through the array. The for loop construct does. i is the for-loop-scoped variable that holds the current index of the array, upper-bound by < numbers.length and incremented every cycle by one (i++). So numbers[i] is a reference to the array element of numbers at index i. Btw you have a typo in your loop declaration - should be number**s**.length. Commented Sep 20, 2018 at 13:33
  • numbers[0] is the first element of the array, if i = 0 then numbers[i] is the same as numbers[0], that is, the first element of the array. If now i++ is executed, i turns to 1 and numbers[i] is now the same numbers[1] the 2nd element in the array Commented Sep 20, 2018 at 14:08

6 Answers 6

4

I am going to use a slightly different analogy, since a lot of answers are providing you with the correct information.

An array is just a list of sequential boxes containing values. Imagine it is a list of houses, each numbered from 0 (arrays in Java like many other programming languages start at 0 not 1) to n (in your case it is 2).

So if you were someone collecting donations from each house, you would start from the first house, 0, then proceed to the next house 1, then to the next house 2. You would keep track of which house you are visiting now, so that you also know which is the next one, and that is what the integer variable i is doing.

Printing numbers[i] does not make the loop cycle, in the same way that knocking on the first house does not mean you are going to knock at the second house.

The for loop is keeping track of which house numbers you need to visit next. It does it by the 3 statements it has in the same line:

for(int i = 0; i < number.length; i++)

The first statement is saying start from the first house (int i = 0). You could start wherever you like.

The second statement is saying, you want to go up to the last house, irrespective of how many houses there are. (i < number.length). This literally translates to keep looping as long as i is less than the size of the array. You might ask why isn't the condition <=. It is because we start from 0, so the length (size of the array) will be the number of the last house + 1. In your case, length = 2 + 1.

The third statement, is what is making you move to the next house. i++ is shorthand for saying i = i + 1. This statement takes place after every iteration of the loop.

So essentially your for loop first initialises i to 0, checks the condition (the second statement) and if the condition is satisfied does the first iteration, then it finally increments i, to start another iteration if the second condition is still satisfied. This loop is repeated until the second statement of your for expression is not true any more.

Finally all numbers[i] means is, since numbers is an array, the [ ] operator accesses the value at the specified index. So it is like knocking at the house with number i to see who lives there. Feeding the value to System.out.println() prints that value on screen.

Sign up to request clarification or add additional context in comments.

Comments

2

Here's a breakdown of how the for-loop is executed (derived from this certification study guide)

Names as referred to below:

for(initialization code; 
    boolean expression; 
    update statements){
  body
}. 

The for-loop's parts are executed in this sequence:

  1. Initialization code
  2. If boolean expression is true, execute body, else exit the loop
  3. Body executes
  4. Execute update statements
  5. Return to Step 2

So when applied to your example, we can say:

Run initialization:

int i = 0

Iteration 1:

if(i < number.length) // -> if(0 < 3)
//run body
i++ //i becomes 1
//return to step 2 (new iteration)

Iteration 2:

if(i < number.length) // -> if(1 < 3) //i was incremented to 1
//run body
i++ //i becomes 2
//return to step 2 (new iteration)

Iteration 3:

if(i < number.length) // -> if(2 < 3) //i was incremented to 2
//run body
i++ //i becomes 3

Iteration 4 (not run):

//return to step 2 (new iteration)
if(i < number.length) // -> if(3 < 3)  -> condition not met
//condition not met, stop the loop

More specifically, I do not understand how i comes to represent the contents of the array

As you can see above, every time the loop body finishes executing, the update statements are executed, which makes the i variable increment, thus allowing to access a different index of the array.

This is done advisedly, if you change your update statements to i += 2, then some indexes of the array will be skipped.

Comments

1

To access information from an array we must tell the array which part of it we would like to access. To do this we use the syntax

array[index]

When you use a for loop to cycle through an array you are essentially using array[index] to go from the first element to the last.

for (int i = 0; i < array.length; i++) 

Will start at array[0] and got brought to array[lastElement] printing out each element of the array.

Comments

1

The line for(int i = 0; i < number.length; i++) is your clue.

A for-loop, which you are declaring here, specifies three parameters*: An initialization variable, when to continue the loop, and what to do after each iteration:

  • int i = 0 is the initialization variable. It's an integer with value 0 that only exists inside the for-loop.
  • i < number.length tells the for-loop that it should continue to run any operation inside the for-loop so long as this condition holds. In this case, it means that as long as i is less than the 'length' (or 'size') of your numbers array, it should keep running. That is, as long as i is less than 3.
  • i++ tells the for-loop what to do after each iteration. In this case, you're telling the for-loop to increase the variable i by 1.
  • System.out.println() is a method that prints stuff to the terminal
  • numbers[i] describes that you want whatever element is in the ith index in the numbers array. That is, when i is 2, you want the element in the 2nd index. When i is 1, you want he element in the 1st index. Important note: Java arrays are zero-indexed, which means that the first element in the array has index 0, the second element has index 1, and so on.

What happens in your loop is in other words that you are declaring a loop, that there should be an integer i with the initial value 0, that it should continue to run so long as i is less than 3, that it should increment i by 1 every time it runs, and that every time the loop runs it should print the element at the ith index in the numbers array.

--

*'parameter' is probably not the correct terminology.

Comments

1

Array's values are taken out by the syntax

numbers[index];

Array index is started from 0 then 1 next 2.... So the in order to retrieve the 1st element you need

numbers[0];

Meanwhile inside the for loop you have created a block variable named i. Note that while iterating, the value of the i increases by 1 because of i++.

So in your for loop this happens.

numbers [0];
numbers[1];
numbers[2];

I think what you don't understand is how a for loop works. Please read,

As per that article,

for(initialization; condition ; increment/decrement){
   statement(s);
}

enter image description here

Example (This is not Java, it's JavaScript but the for loop works the same way; is not don't misunderstand. I just want to show you a working example on how i's value increments.) :

var i;
for (i = 0; i < 10; i++) {
  console.log("i = " + i);
}

Comments

0

"Arrays will always be laid out in memory using consecutive storage locations. The compiler knows the array to start at memory cell x. When it needs to get to a[123], it adds 123 to x and uses that number to address the memory to get to the element."

They are in consecutive and indexing starts with 0. and at each new element is next position to the current index. hence you can access any element from an array with his index.

If you are writing numbers[i] means ith element from array. and always highest index of array will always less than length of array (size of array).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.