C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
While loopIn a PowerShell, the While loop is also known as a While statement. It is an entry-controlled loop. This loop executes the statements in a code of block when a specific condition evaluates to True. This loop is easier to construct than for statement because the syntax of this loop is less complicated. Syntax of While loopwhile(test_expression) { Statement-1 Statement-2 Statement-N } When we execute a while loop, PowerShell evaluates the condition first. Then, it executes the statements in a code of the block. The condition returns the Boolean value True or False. Until the Condition is 'True', the PowerShell execute the statements repeatedly. When the Condition returns False, the loop will terminate, and the control goes to the statement after the loop. Flowchart of While loopExamplesExample1: The following example prints the values from 1 to 5 using while loop: PS C:\> while($count -le 5) >> { >> echo $count >> $count +=1 >> } Output: 1 2 3 4 5 In this example, the condition ($count is less than equal to 5) is true while $count = 1, 2, 3, 4, 5. Each time through the loop, the value of a variable $count is incremented by 1 using the (+=) arithmetic assignment operator. When $count equals to 6, the condition statement evaluates to false, and the loop exits. Example2: The following example finds the sum of first n natural numbers: PS C:\> $n=10 PS C:\> $i=1 PS C:\> $sum=0 PS C:\> while($i -le $n) >> { >> $sum=$sum+$i >> $i=$i+1 >> } echo $sum Output: 55 In this example, the while loop is executed n number of times. And each time, the value of the variable $i is added to the $sum variable and values of $i is incremented by 1. Example3: The following example prints the factorial of a number using while loop: PS C:\> $fact =5 PS C:\> $f =1 PS C:\> while($fact -gt 0) >> { >> $f = $f *$fact >> $fact -=1 >> } echo $f Output: 120
Next TopicContinue and Break Statement
|