Introduction to Counting and Looping
Introduction to Counting and Looping
Fundamentals of Counting in Looping
Introduction
When it comes to lists (including arrays), a loop is an operation that visits each member of the list and performs an operation on that member. PowerShell provides many operators to perform such an operation.
Performing an Operation While a Condition is True
One of the techniques to perform looping is to first perform an operation, then check a condition to repeat a statement. To do this, you can use an operator named while. The formula to follow is:
while(condition) statement
To make your code easier to read, you can put the sections on different lines as follows:
while(condition) { statement-1 statement-2 . . . statement-x }
Most of the time, the statement goes along with a way to move forward or backward. The section that has the statement is the body of the while condition.
With a while loop, PowerShell first examines the condition. If the condition is true, then it executes the statement. After executing the statement, the condition is checked again. As long as the condition is true, the statement will keep executing. When or once the condition becomes false, the loop stops.
Most of the time, before entering in a while loop, you should have an object or a variable that has been initialized or the variable provides a starting value. From there, you can ask PowerShell to check another condition and keep doing something as long as that condition is true. Here is an example:
# Consider a starting value as 0 $number = 1 # As long as the above value is lower than 5, ... while($number -le 5) { # ... display that number Write-Host 'Make sure you review your time sheet before submitting it.' # Increase the number (or counter) $number++ # Check the number (or counter) again. Is it still less than 5? }
This would produce:
S C:\TaxPreparation05> . 'C:\Exercise09\Exercise7.ps1' Make sure you review your time sheet before submitting it. Make sure you review your time sheet before submitting it. Make sure you review your time sheet before submitting it. Make sure you review your time sheet before submitting it. Make sure you review your time sheet before submitting it.
The while loop is used to first check a condition and then execute a statement. If the condition is false, the statement would never execute.
Introduction to Loops and Lists
As you may know already, a list is a group of items. Here is an example of a list of numbers with each number stored in a variable:
$number1 = 12.44 $number2 = 525.38 $number3 = 6.28 $number4 = 2448.32 $number5 = 632.04
The items are grouped from a starting to an ending points. The list can be created as an array. Here is an example:
$numbers = @(12.44, 525.38, 6.28, 2448.32, 632.04)
The list has a number of items. We saw that, to get the number of items of an array, you can apply .length or .count to the name of an array variable. Here is an example of accessing it:
$numbers = @(12.44, 525.38, 6.28, 2448.32, 632.04) Write-Host "Number of Items in the array: " $numbers.Length Write-Host "================================="
This would produce:
PS C:\TaxPreparation05> . 'C:\Exercise09\Exercise7.ps1' Number of Items in the array: 5 =================================
Each item can be located by its index from 0 to number-of-items - 1. Here is an example that accesses each of the items:
$numbers = @(12.44, 525.38, 6.28, 2448.32, 632.04) Write-Host "Number:" $numbers[0] Write-Host "Number:" $numbers[1] Write-Host "Number:" $numbers[2] Write-Host "Number:" $numbers[3] Write-Host "Number:" $numbers[4] Write-Host "============================"
This would produce:
PS C:\TaxPreparation05> . 'C:\Exercise09\Exercise7.ps1' Number: 12.44 Number: 525.38 Number: 6.28 Number: 2448.32 Number: 632.04 ============================
As opposed to accessing one item at a time, a loop allows you to access the items as a group. Each item can still be accessed by its index. You can first declare a variable that would hold the index for an item. Here is an example:
$counter = 0
$numbers = @(12.44, 525.38, 6.28, 2448.32, 632.04)
To access an item in a loop, use the name of the array but pass the index in the square brackets of the variable. Here is an example:
$counter = 0 $numbers = @(12.44, 525.38, 6.28, 2448.32, 632.04) while ($counter -le 4) { Write-Host "Number: " $numbers[$counter] $counter++ } Write-Host "================================="
This would produce:
PS C:\TaxPreparation05> . 'C:\Exercise09\Exercise7.ps1' Number: 12.44 Number: 525.38 Number: 6.28 Number: 2448.32 Number: 632.04 =================================
Omitting a Looping Variable
Remember that when you don't need a variable to hold a value, you can directly use the value where it is needed. This is also valid for a list of values you are using in a loop. This means that, when performing a while operation that involves an array, if you will use a list only once, you can create that list directly where it is needed. Everything else remains the same. Consider an earlier code section as follows:
$counter = 0 [float[]]$numbers = @(12.44, 525.38, 6.28, 2448.32, 632.04) while($counter -le 4) { Write-Host "Number:" $numbers[$counter] $counter++ } Write-Host "================================="
If you will use the array only once, you can create it directly where it is needed as follows:
$counter = 0
while($counter -le 4) {
Write-Host "Number:" @(12.44, 525.38, 6.28, 2448.32, 632.04)[$counter]
$counter++
}
Write-Host "================================="
If you want, to make your code a little easier to read, you can write some of its sections on different lines. Consider the following example:
$counter = 0
while($counter -le 4) {
Write-Host @(
12.44, 525.38, 6.28, 2448.32, 632.04
)[$counter]
$counter++;
}
Write-Host "================================="
This would produce:
PS C:\TaxPreparation05> . 'C:\Exercise09\Exercise7.ps1' 12.44 525.38 6.28 2448.32 632.04 =================================
You can also write the code as follows:
$counter = 0;
while($counter -le 4) {
Write-Host "Number: " @(
12.44
525.38
6.28
2448.32
632.04
)[$counter]
$counter++;
}
Write-Host "================================="
Doing Something While a Condition is True
Sometimes, before executing a repeating action, or before checking the condition for the first time, you may want to first execute a statement. In other words, you want to first execute a statement before checking its condition. To do that, you combine the while keyword with a keyword named do. The formula to follow is:
do { statement while (condition}
To make your code easy to read, especially if the condition is long, you can (and should) put the sections on different lines. The formula would become:
do { statement-1 statement-2 . . . statement-x } while (condition)
The do...while condition executes a statement first. After the first execution of the statement, the condition is examined. If the condition is true, the statement is executed again. The statement would be executed as many times the condition would be true. Once the condition becomes false, the looping (the execution of the statement) would stop. This can be illustrated as follows:
As seen with the if and the while statements, the condition being checked must be included between parentheses. Here is an example:
$number = 0 do { Write-Host "Make sure you review the time sheet before submitting it." $number++ } while ($number -le 4) Write-Host "=========================================================="
This would produce:
PS C:\TaxPreparation05> . 'C:\Exercise09\Exercise7.ps1' Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it. ==========================================================
Doing Something on a List
We saw that a while loop first checks a condition before performing an action. A do...while loop first performs an action before checking a condition. That's their main difference. Otherwise, you can perform a do...while operation where you would have used a while loop. This is also valid for lists such as arrays. Consider a while loop we used earlier as follows:
$counter = 0 [float[]]$numbers = @(12.44, 525.38, 6.28, 2448.32, 632.04) while($counter -le 4) { Write-Host "Number:" $numbers[$counter] $counter++ } Write-Host "================================="
Instead of first checking a condition before performing an action in a while loop, you may want to first perform the desired action before checking a condition. In that case, the above code can be changed as follows:
$counter = 0 [float[]]$numbers = @(12.44, 525.38, 6.28, 2448.32, 632.04) do { Write-Host "Number:" $numbers[$counter] $counter++ } while($counter -le 4) Write-Host "================================="
Remember that the array variable may be necessary only if you are planning to use that variable more than once. Otherwise, you can create the array directly where it is used. This can be done as follows:
$counter = 0
do {
Write-Host "Number: ", @(
12.44, 525.38, 6.28, 2448.32, 632.04
)[$counter]
$counter++
} while($counter -le 4)
Write-Host "================================="
Introduction
Some operations require that you visit each item in a range, usually a range of numbers. To let you do this, the C-based languages, including C#, provide the for keyword. The primary formula to follow is:
for(start; end; frequency) { statement}
Once again, to make your code easy to read, especially if the statement is long or if there are many statements, you should (must) write the sections on different lines. The formula to follow would become:
for(start; end; frequency) { statement-1 statement-2 . . . statement-x }
The for loop is typically used to visit each number of a range. For this reason, it is divided in three parts. The first section specifies the starting point of the range. This start expression can be a variable assigned to the starting value. An example would be $count = 0;.
The second section sets the counting limit. This end expression is created as a Boolean expression that can be true or false. An example would be count -lt 5;. This means that the counting would continue as long as the value of start is less than 5. When such a condition becomes false, the loop or counting would stop.
The last section determines how the counting should move from one value to another. If you want the loop to increment the value from start, you can apply the ++ operator to it. Here is an example:
for($number = 1; $number -le 5; $number++) { Write-Host "The time sheet was checked and this payroll has been approved." } Write-Host "==============================================================="
This would produce:
PS C:\TaxPreparation05> . 'C:\Exercise09\Exercise7.ps1' The time sheet was checked and this payroll has been approved. The time sheet was checked and this payroll has been approved. The time sheet was checked and this payroll has been approved. The time sheet was checked and this payroll has been approved. The time sheet was checked and this payroll has been approved. ===============================================================
For a List
The primary purpose of a loop is to act on a list, such as an array of items, a list of numbers, etc. As it happens, mathematics (or algebra) automatically provides a list of numbers. This makes it possible to automatically have available a list of numbers as soon as you create an array. On the other hand, if you want a particular list of numbers, you can explicitly create it, as we saw with the while loop. After creating such an array, you can use a for loop to access each item by its position. The formula you can use is:
# Create a list or array of objects for($counter; counter[-lt][-le][-gt][-ge] start-or-end-value; counter-frequency) { # Optional operations list-or-array-of-objects[counter]; # Optional operations }
Based on this, a for loop primary performs the same operations as a while or a do...while loop. The primary difference is that, for a while or a do...while loop, you can (must) first declare, outside the loop, a variable that holds the starting value of the loop. For a for loop, you can also first declare a variable for the starting value, which you can do outside the loop, but, by tradition, that variable is declared in the parentheses of the for loop. Other than in the body of any of those loops, you can access the elements of the array or list using square brackets. Consider a while loop we used earlier as follows:
$counter = 0 # Optional things here [double[]]$numbers = @(12.44, 525.38, 6.28, 2448.32, 632.04) while($counter -le 4) { Write-Host "Number:" $numbers[$counter] $counter++; } Write-Host "================================="
Using a for loop, the above code can be changed as follows:
[double[]]$numbers = @(12.44, 525.38, 6.28, 2448.32, 632.04) for($counter = 0; $counter -le 4; $counter++) { Write-Host "Number:" $numbers[$counter] } Write-Host "================================="
As stated already, an array variable is necessary only if you are planning to use the list many times. Otherwise, you can create the array directly where you need it. Here is an example:
for($counter = 0; $counter -le 4; $counter++) {
Write-Host "Number:" @(12.44, 525.38, 6.28, 2448.32, 632.04)[$counter]
}
Write-Host "================================="
Reversing the Counting Direction
Instead of proceeding from a lower to a higher value in a loop, you can visit the values from the end of a list to the beginning. To do this, for the first part of the loop, set the last value as the starting point. For the second part of the loop, specify the possible ending point as the first value. For its Boolean expression, you usually set a condition that would work backwards. This is usually done using the -gt or the -ge operator. The last section usually applies the -- operator to the variable of the loop. The formula to follow can be the following:
for(end; start; frequency) { statement-1 statement-2 . . . statement-x }
Here is an example:
[double[]]$numbers = @(12.44, 525.38, 6.28, 2448.32, 632.04) for($counter = $numbers.Count; $counter -ge 0; $counter--) { Write-Host "Number:" $numbers[$counter] } Write-Host "================================="
This would produce:
PS C:\TaxPreparation05> . 'C:\Exercise09\Exercise7.ps1' Number: Number: 632.04 Number: 2448.32 Number: 6.28 Number: 525.38 Number: 12.44 =================================
Instead of visiting the elements of a list by counting them, you may want to visit each item directly. To do this, you can use an operator named foreach. The formula to use it is:
foreach(variable in list) { statement}
To make your code easy to read, you can (and should) write the statement on its own line. This can be done as follows:
foreach(variable in list) { statement-1 statement-2 . . . statement-x }
The loop starts with the foreach keyword followed by parentheses. In the parentheses, enter the list that contains the elements you want. Precede that list with an operator named in. The foreach loop needs a variable that would represent an item from the list. Therefore, in the parentheses, start by declaring a variable before the in operator. Of course, the name of the variable must start with $. Outside the parentheses, create a statement of your choice. At a minimum, you can simply display the variable's value to the user. Here is an example:
$numbers = @(102, 44, 525, 38, 6, 28, 24481, 327, 632, 104) foreach($nbr in $numbers) { Write-Host "Number:" $nbr } Write-Host '==============================='
This would produce:
PS C:\TaxPreparation05> . 'C:\Exercise09\Exercise7.ps1' Number: 102 Number: 44 Number: 525 Number: 38 Number: 6 Number: 28 Number: 24481 Number: 327 Number: 632 Number: 104 ===============================
|
|||
Previous | Copyright © 2001-2025, FunctionX | Wednesday 19 February 2025, 11:41 | Next |
|