Iterating Over an Array

In this lesson, we will look at:
  • iteration using for
  • iteration using foreach
  • iteration using while
  • iteration using do...while

Iterating over an array using for

The for loop is convenient when you need access by index or when the order of iteration matters.
Line 1, Char 1
Iterating over an array in reverse
Line 1, Char 1

Iterating over an array using foreach

Used when you simply need to get the values, not the index.
Line 1, Char 1

Iteration using while

Used when the number of steps is not known in advance or the loop depends on external conditions.
Line 1, Char 1

Iteration using do...while

This loop will execute the body at least once, even if the condition is false.
Line 1, Char 1

Summary

  • for — when you need control over the index
  • foreach — simplest and safe
  • while — unknown number of iterations
  • do...while — need to execute at least once

Exercises

  1. Print the elements of the fruits array using for.
Line 1, Char 1
  1. Print the elements of the fruits array using foreach.
Line 1, Char 1
  1. Print the elements of the fruits array using while.
Line 1, Char 1
  1. Print the elements of the fruits array using do…while.
Line 1, Char 1