epikoeni

Traversing Arrays and ArrayLists in Java with a For Loop and with a While Loop

From: https://www.codecademy.com/courses/learn-java/lessons/learn-java-loops/exercises/iterating-over-arrays-and-arraylists

For Loops

Arrays:

for (int i = 0; i < newArray.length; i++) {
  // Do something with the item in the Array at position i
  newArray[i] += 1; // Increment it for example
}

ArrayLists:

for (int i = 0; i < newArrayList.size(); i++) {
  // Do something with the item in the ArrayList at position i
  int num = newArrayList.get(i);
  newArrayList.set(i, num + 1); // Increment it for example
}


While Loops

Arrays:

int i = 0; // initialize counter

while (i < newArray.length) {
  // Do something with the item in the Array at position i
  newArray[i] += 1;  // Like incrementing it for example
  i++; // increment the while loop
}

ArrayLists:

int i = 0; // initialize counter

while (i < newArrayList.size()) {
  // Do something with the item in the ArrayList at position i
  int num = newArrayList.get(i);
  newArrayList.set(i, num + i); // Like incrementing it for example
  i++; // increment the while loop
}
#java#programing#beginners
 
Share this