Activity 4.20.1.
Fix the following code so that it prints every other value in the array
arr1
starting with the value at index 0.
Solution.
Change line 5 to add the
[]
on the declaration of arr1
to show that it is an array of integer values. Change line 6 to index < arr1.length
so that you donβt go out of bounds (the last valid index is the length minus one). Change line 8 to print arr1[index]
.
public class Test1
{
public static void main(String[] args)
{
int[] arr1 = {1, 3, 7, 9, 15, 17};
for (int index = 0; index < arr1.length; index += 2)
{
System.out.print(arr1[index] + ", ");
}
}
}