## Learning Objectives

After completing this lesson, learners should be able to:
• Use for loops to repeat operations multiple times

• Running a script for multiple files

## Motivation

In an imaging processing workflow you often apply the same operation to several images, several labels, etc. In order to avoid repeating the same code many times we can use control flow statements such as a `for` loop. Loops together with `if` clauses represent extremely useful tools when programming.

## Concept map

graph TD A["Previous code"] --> Loop{"Check condition"} Loop --> |Condition is valid| RepeatChunk("Code chunk to be repeated") RepeatChunk --> Loop Loop --> |Condition is not valid| NextChunk("Next code to run")

## Activities

• Open a script editor.
• Open and run a script that contains several repeated operations and explain that you would like to write this part of code in a more simple way.
• Explain the different elements of a numeric `for` loop:
• The loop header, the loop counter/variable, and body
• The initial and end condition
• How the counter is iterated (e.g. `i++`).
• Using a print command show how the iterator changes
• Take the starting script and modify it using a `for` loop

Show activity for:

## Exercises

### Multiple erosion

• Open the binary image xy_8bit_binary__nuclei.tif
• Create a macro (or use a pre-defined one) to erode and find boundary of the binary objects
• Modify the macro so that you can perform an arbitrary number of erosions and find their boundary
Show exercise/solution for:

## ImageJ Macro, Multiple erosion

Download the script script_for_loop_erodeband_noloop.ijm. The goal is to perform a series of binary-erosions and compute the outline of these objects.

1. Create a variables `maxErode` that sets the number of erode operations
2. Create a `for` loop to perform `maxErode` operations, change the name of the image accordingly
3. (Advanced) Create a second `for` loop that uses `maxErode` as counter. Vary `maxErode` from 1 to 50

A solution can be found in script_for_loop_erodeband_withloop.ijm

## Explanations

#### For loop

A `for` loop occurs by iterating over a loop variable defined in a loop header. You use `for` loops when you know the number of iterations to execute.

#### While loop

While loop does not have a fixed number of iterations. Typically the header contains a condition that is computed within the body of the loop. TODO.

## Follow-up material

Recommended follow-up modules: