Select Page

For each is pretty simple. You provide a list to loop through and there’s a local variable named “item” given to you that holds the value of an item. Note that you can change the name “item” to anything you like. Remember “item” is a local variable, you cannot use it outside the scope. In for each block, the scope is inside the do section of for each block. Let’s calculate sum of numbers in a list. See the snapshot below- We have a list named numberList which contains three items – 20, 30, and 10. We wrote a procedure named CalculateSum that sums up the numbers in our list and then displays the sum. We declared a global variable named sum and initialized it to 0. Initializing means assigning a value the first time when you create a variable. Inside the procedure, we again set the value of sum to 0. You might think the initial value of sum was already 0 when we defined the sum variable outside CalculateSum procedure. Well, you may want to use the same procedure again and again. In that case, it’s safe to reinitialize a global variable unless the previous value of that global variable should be retained. We used for each block to loop through each item in our numberList and added to the value of sum. The execution of the above procedure would look like this-

```sum = 0

sum = sum + value at position 1 of numberList (0 + 20 = 20)
(Now the value of sum is 20)

sum = sum + value at position 2 of numberList (20 + 30 = 50)
(Now the value of sum is 50)

sum = sum + value at position 3 of numberList (50 + 10 = 60)
(Now the value of sum is 60)```

The final value of sum will be 60.

For more examples on list and control blocks, take a look at List Tutorial.

```
```