Arrays with Loops
Learn to use arrays with the help of loops in Java.
We'll cover the following...
The for loop with arrays
The individual values in an array are accessed through an index number. The for loop variable can be used as an index number. However, the array values can also be used directly in a for loop.
The following program demonstrates the various ways of accessing array elements:
class Test{public static void main(String[] args){String[] vals = {"-5", "Java", "3.8"};System.out.println("One way of printing an array: ");for (int i = 0; i < vals.length; i++){System.out.println(vals[i]);}System.out.println("Another way of printing an array: ");for (String s: vals){System.out.println(s);}}}
In the code above:
- The new item is the
vals.lengthfunction, which is used to get the length of the array. - The first
forloop accesses the array values with the help of the loop variablei. - The second
forloop directly accesses the array values.
The while loop with arrays
We usually use the while loop to deal with arrays when the number of iterations is not fixed. For example, let’s say we want to generate n terms of a Fibonacci sequence and store it in an array, where n is the user input. A Fibonacci sequence is a sequence in which each number is the sum of the two preceding ones, except the first two terms.
Let’s start by noting a few terms of this sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ….
Here’s how to solve this problem:
- Start with an empty array of