setTrue
Objective(s): Practice traversing an array.
Given an array, myBool
, set all the values to true
.
What is the return type of this method? How does that inform you about the need for a return line in the body?
A loop structure is useful when needing to visit every position of an array. The loop itself allows you to generate all the necessary indexes. This was a repetitive problem from Unit 4 where you were generating numbers. It's finally useful for something!
The for-loop's control variable i is used to counting from 0 to (length - 1) which are all the valid indexes for the array called arrayName below.
for(int i = 0; i < arrayName.length; i++){
arrayName[i] = 3; //index is used to visit the position in the array and set it to 3!
}
The loop above is a typical loop for traversing arrays. An array traversal is when you "visit" the elements of an array such as for printing or for assigning. Below is another example to print every element of an array
for(int i = 0; i < array.length; i++){
System.out.println(array[i]); //print the element at index i
}