Quick Index
Purpose


This example uses the same problem as the previous iteration, except that the syntax is more concise. Only the collection elements are needed during iteration, not the index. The iteration is from first to last.

Writing Algorithm


Problem Statement
Problem Statement: Write an algorithm to print a collection of elements using the "println" method for each element.

Given: Variable 'elements' that holds a collection of objects.
Review: Solution by Index
Here is the algorithm using an iteration index for reference.
Pseudocode:
printAll(elements) {
	for (let i = 0; i < elements.length; i++) {
		let nextElem = elements[i];
		println(nextElement.toString())
	}
}
Writing Algorithm in Pseudocode
This pseudocode allows us to simply loop over the collection 'elements' and do a println for each element.

Next we will examine the pseudocode in detail
Pseudocode:
function printAll(elements) {
	for (let nextElement of elements) {
		println(nextElement.toString())
	}
}
//Try It
let collection = [10, 20, 30, 40];
printAll(collection);


Pseudocode Breakdown


for (let nextElement in elements)

  • for -- says to loop
  • let nextElement -- says to assign the next collection element to loop variable "nextElement"
  • in elements -- says that this is the source (collection) that is being iterated over

for (let nextElement in elements) {
	println(nextElement)
}
 

  • {} -- The braces define the loop block. The block of code within the braces executes for every loop (with a new loop var)
  • println(nextElement) -- calls println with the loop var "nextElement"

Notes:
  • A loop variable is the same as a local variable (the local context is the "loop block").
  • If the loop block contains only one statement, the braces "{}" are optional.


Walking Through Algorithm


We're now going to walk through the algorithm using example data.

Given Data
Let us say that the provided array is a collection of student (objects) as follows:

elements = [Riya, Asha, Chin]
   [Riya, Asha, Chin]
println(elements) {        [Riya, Asha, Chin]
    for (let nextElement in elements) {
        println(nextElement)
    }
}
Loop 1
The first loop.
Loop variable "eachElement" is assigned value "Riya" (first element in collection).
            Riya
for (let nextElement in elements) {
    println(nextElement)
             Riya
}
Loop 2
The next loop.
Loop variable "eachElement" is assigned the next collection element -- "Asha".
            Asha
for (let nextElement in elements) {
    println(nextElement.toString())
             Asha
}
Loop 3
The next loop.
Loop variable "eachElement" is assigned the next collection element -- "Chin".
            Chin
for (let nextElement in elements) {
    println(nextElement.toString())
             Chin
}
LOOP ENDS
We have run out of elements in the collection (i.e., there is no "nextElement")

The loop ends.
                  [Riya, Asha, Chin]
for (let nextElement in elements) {
    println(nextElement.toString())
}