COMPSCI4039 Programming
Arrays Part 2
Loops with arrays
Copyright By PowCoder代写 加微信 powcoder
• Can be tedious to manually reference offsets when manipulating data.
• Loops are often used to alleviate this. • Setting values.
• Changing values.
• Getting values.
• Among other reasons…
• For is one of the most common loops used with arrays.
• Remember our for conditional needs some check to know how long to run.
• Makes sense to run until we have checked the entire array.
• We can take an array and use its length attribute to see how many
values it contains.
• Length is an attribute of the array object that we can access. • It is public in that sense.
Using for to populate an array…
• This code here will set each value to be double the index value. • We first specify a starting value for the index.
• Then we specify the condition to stop looping.
• Then we specify what we do in the event we are not done.
Remember that the index value is itself a primitive that we can use.
It can point to one of the values in the array, or be used in some mathematical operation.
public class IntArray {
public static void main(String[] args) {
int[] myIntArray = new int[10];
for(int i=0;i