Learn

The next type of control flow we will cover in this lesson is loops. Loops allow us to perform the same action multiple times within a script, whether outputting numerous messages to the user or processing data.

Loops define a body of code to be executed repeatedly until a stop condition is met. Each execution of code is called an iteration.

The first loop we will cover is the for loop. There are three steps to creating a for loop:

  • initializing a counter variable
  • setting a stop condition using the counter variable
  • changing the value of the counter variable

The body of a for loop contains the code that iterates over and over until the given condition is met:

for ($i = 0; $i -lt 3; $i++) { Write-Host "i is ($i)" }

The example above starts with the for keyword with the following inside the parentheses:

  • $i = 0 initializes the counter $i to 0.
  • $i -lt 3 sets the condition for the loop to continue. As long as $i is less than 3, the code inside the loop body will continue to execute
  • $i++ increments the counter, so the set condition will eventually evaluate to false.

The above loop will repeat three times before $i -lt 3 is no longer true, and the code will output:

$i is 0 $i is 1 $i is 2

Once $i equals 3, the code will no longer execute.

Instructions

1.

Inside FOR_Example.ps1 create a for loop that:

  • initializes a counter $i to equal 1
  • sets a run condition of $i is less than or equal to 10
  • increments $i by 1 for each loop

Leave the body of the loop empty.

2.

Inside the for loop body, define a variable $square and set it to:

$i * $i
3.

Inside the for loop body, use Write-Host to output $square. Feel free to use the following line of code:

Write-Host "The square of" $i "is" $square

Just be sure to output $square. Your loop should run 10 times and output squares from 1 to 10.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?