Topics on Counting and Looping
Topics on Counting and Looping
Controlling a Loop
Loops and Conditional Statement Nesting
You can create a conditional statement in the body of a loop. This is referred to as nesting. Here is an example:
$number = 0
while($number -lt 5) {
Write-Host "Make sure you review the time sheet before submitting it."
if($number -eq 2) {
Write-Host "This is the third warning about your time sheet."
}
$number++
}
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. This is the third warning about your time sheet. Make sure you review the time sheet before submitting it. Make sure you review the time sheet before submitting it. ===============================================================
On the other hand, you can nest a loop in a conditional statement.
As mentioned in our introductions, a loop is supposed to navigate from a starting point to an ending value. Sometimes, for any reason, you want to stop that navigation before the end of the loop. To do this, you can use a keywork named break. This keyword is a whole statement by itself; therefore, it can (and should always) stay on its own line (this makes the program easy to read).
The break statement applies to the most previous conditional statement to it; provided that previous statement is applicable. The break statement can be used in a while condition, in a do...while, or a for loops to stop an ongoing operation. Here is an example that is used to count the levels of a house from 1 to 12 but it is asked to stop at 3:
for($number = 0; $number -le 5; $number++) {
Write-Host "The time sheet was checked and this payroll has been approved."
if($number -eq 2) {
break
}
}
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. ===============================================================
Continuing a Conditional Statement
Instead of stopping the flow of a loop, you may want to skip one of the values. To do this, you can use a keywork named continue keyword. You can use the continue statement inside of a while, a do...while, or a for conditional statements to ignore the subsequent statement or to jump from a false Boolean value to the subsequent valid value, unlike the break statement that would exit the loop. Like the break statement, the continue keyword applies to the most previous conditional statement and should stay on its own line. Here is an example that is supposed to count the levels of a house from 1 to 6:
[string]$strNumbers = ""
for($number = 0; $number -le 5; $number++) {
if($number -eq 3) {
continue
}
$strNumbers += $number + " "
Write-Host "The list of numbers is " $strNumbers
}
Write-Host "==========================================="
This would produce:
PS C:\TaxPreparation05> . 'C:\Exercise09\Exercise7.ps1' The list of numbers is 0 The list of numbers is 01 The list of numbers is 012 The list of numbers is 0124 The list of numbers is 01245 ===========================================
Notice that, when the compiler gets to 3, it ignores it.
Changing a Value in the Loop
Inside a loop, you may want to put a flag that would monitor the evolution of a piece of code so that, if a certain value is encountered, instead of skipping the looping by 1, you can make it jump to a valued range of your choice. To do this, in the loop, check the current value and if it gets to one you are looking for, change it. Here is an example where a loop is asked to count from 0 to 15:
[string]$strNumbers = "" for($number = 0; $number -lt 15; $number++) { if($number -eq 6) { $number = 10 } $strNumbers = $strNumbers + " " + $number } Write-Host "The list of numbers is" $strNumbers Write-Host '=================================================='
This would produce:
PS C:\TaxPreparation05> . 'C:\Exercise09\Exercise7.ps1' The list of numbers is 0 1 2 3 4 5 10 11 12 13 14 ==================================================
Notice that, when the loop reaches 6, it is asked to jump to number 10 instead.
Selecting a Value From a List
Introduction
If you have a list, such as an array, made of too many values, at one time you may want to isolate only the first n members of the list, or the last m members of the list, or a range of members from an index i to an index j. Another operation you may be interested to perform is to find out if a certain value exists in the list. One more interesting operation would be to find out what members or how many members of the list respond to a certain criterion.
for Looping
Consider the following array:
$numbers = @(102, 44, 525, 38, 6, 28, 24481, 327, 632, 104)
Imagine you want to access only the first n members of the array. To do this, you can use an if conditional statement nested in a for loop. Here is an example that produces the first 4 values of the array:
$numbers = @(102, 44, 525, 38, 6, 28, 24481, 327, 632, 104) for($i = 0; $i -lt 10; $i++) { if($i -lt 4) { Write-Host "Number: " $numbers[$i] } } Write-Host '==============================='
This would produce:
PS C:\TaxPreparation05> . 'C:\Exercise09\Exercise7.ps1' Number: 102 Number: 44 Number: 525 Number: 38 ======================
You can use the same technique to get the last m members of a list. You can also use a similar technique to get one or a few values inside of the list, based on a condition of your choice. Here is an example that gets the values that are multiple of 5 from the array:
$numbers = @(102, 44, 525, 38, 6, 28, 24485, 327, 635, 104) for($i = 0; $i -lt 10; $i++) { if($numbers[$i] % 5 -eq 0) { Write-Host "Number: " $numbers[$i] } } Write-Host "================="
This would produce:
PS C:\TaxPreparation05> . 'C:\Exercise09\Exercise7.ps1' Number: 525 Number: 24485 Number: 635 =================
while($true)
For the different situations in which we used a while condition so far, we included a means of checking the condition. As an option, you can include just the true Boolean constant in the parentheses of true. This would be done as follows:
while($true) { statement}
You can write the statement on its own line. In fact, if you have to process many statements, you should expand the body of the loop on many lines. The formula would become:
while($true) { statement-1 statement-2 . . . statement-x }
For the different situations in which we used a while condition so far, we included a means of checking the condition. As an option, you can include just the true Boolean constant in the parentheses of true. Here is an example:
while($true) {
Write-Output 'Application development is fun!!!'
}
This type of statement would work fine, but it has no way to stop because it is telling the compiler "As long as 'this' is true, ...". The question is, what is "this"? As a result, the program would run forever. Therefore, if you create a while($true) condition, in the body of the statement, you should (must) provide a way to stop, that is, a way for the condition to be (or to become) false. This can be done by including an if conditional statement. Here is an example:
$i = 0
while($true) {
if($i -gt 8) {
break
}
Write-Host $i 'Application development is fun!!!'
$i++
}
Write-Host '==============================='
This would produce:
PS C:\TaxPreparation05> . 'C:\Exercise09\Exercise7.ps1' 0 Application development is fun!!! 1 Application development is fun!!! 2 Application development is fun!!! 3 Application development is fun!!! 4 Application development is fun!!! 5 Application development is fun!!! 6 Application development is fun!!! 7 Application development is fun!!! 8 Application development is fun!!! ===============================
Options for a Loop
A Variable for a Counter
To make the code of a for loop easy to read, you can put each part of the for expression on its own line. Here is an example:
for($number = 0 $number -le 4 $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. ===============================================================
In the above example, we declared the variable in the for expression. You can use a variable from any source or declare a variable before the loop. Here is an example:
# A variable for a loop $number # Using a "for" loop for($number = 0; $number -le 5; $number++) { Write-Host 'The time sheet was checked and this payroll has been approved.' } Write-Host '==============================================================='
Omitting the Starting Point
In the above code, we first declared a variable, and then initialized it in the loop. If you have a variable that has been initialized and want to use it in the loop, in the section of the loop where the variable is supposed to be initialized, leave that section empty but include its semicolon. Here is an example:
$number = 0 for(; $number -le 5; $number++) { Write-Host 'The time sheet was checked and this payroll has been approved.' } Write-Host '==============================================================='
for a while Loop
Here is an example of code we used earlier for a while loop:
$counter = 0 while($counter -le 4) { Write-Host 'Make sure you review your time sheet before submitting it.' $counter++ }
We have already seen that you can declare and initialize a variable for a for loop, in which case you would omit the starting point of the loop. You can also omit the third part of the loop. In this case, in the body of the for loop, write a statement that specifies the next step of the loop. Here is an example:
$counter = 0 for(; $counter -le 4;) { Write-Host 'Make sure you review your time sheet before submitting it.' $counter++ }
Omitting the Parts for a Loop
The three sections of a for loop are required, but their contents are not. We have already seen how to omit the first and the third part of that loop. Well, you can also omit the second part. This means that you can define a for loop with all three empty parts:
for(; ; ) { Write-Host 'Make sure you review your time sheet before submitting it.' }
This code doesn't have any error and would work just fine, except that it would run forever, until the computer crashes, is shut down, or runs out of memory. Therefore, the requirements of a for loop remain: you must specify how to start counting, how to get to the next step, and under what condition to stop the loop. Since the for loop can be created with all three empty sections, this means that you can (should/must) create those sections outside the loop. We have already seen how to create the first and the third sections outside of for(;...;). In the same way, you can create the second section outside of for(;...;). The classic or simpler way is to create a conditional statement in the body of the loop and, in that statement, add a break line. This can be done as follows:
$counter = 0 for(;;) { Write-Host 'Make sure you review your time sheet before submitting it.' $counter++ if($counter -gt 4) { break } }
|
|||
Previous | Copyright © 2001-2025, FunctionX | Wednesday 19 February 2025, 11:35 | Next |
|