Using Loops with ArraysUsing Loops with Arrays

How to Iterate Through an Array Using Loops?

Arrays and loops are frequently used in tandem. When dealing with a large array containing 100 or even 1000 elements, manually working with and extracting each element would be impractical. Just imagine how time-consuming it would be to manually fill such an array...

To achieve such tasks, we'll employ loops. In the previous section, we observed that we initially assigned the variable i a value of 0 in the for loop, and array indexing also starts at 0. Do you notice the connection?

Let's say we have a task to display all the elements of an array of type char with a length of 10. Let's examine a code fragment that accomplishes this task:

java

Main.java

Let's take a closer look at how the loop iterates over an array:

java

Main.java

Task:

Let's practice working with loops and arrays on your own. Your task is to populate an array with numbers from 1 to 10 using a for loop and then display it on the console. Keep in mind that the numbers should be arranged in ascending order.

java

Main.java

  1. 1. The variable i should be incremented by one each time you want to store its value in the array so that you can use i+1 every time;
  2. 2. Don't forget to specify in your loop that "i" should increase until it reaches the array's length. It would look like i < result.length.

package com.example;

public class Main {
    public static void main(String[] args) {
        int[] result = new int[10];
        for (int i = 0; i < result.length; i++) {
            result[i] = i + 1; 
            System.out.println(result[i]);
         }
    }
}
      

Everything was clear?

Section 4. Chapter 2