Tutorials > Programming > Task 3–2: Writing While Loops
Writing a Basic While Function
Write a function sigma that sums all the numbers from 0 to n.
1. Define a function sigma that accepts a variable n and create a new program.
2. To add an empty while loop, on the Math tab, in the Operators and Symbols group, click Programming, and then click while.
3. Specify that the while loop should continue as long as n>0 and should decrement n by 1 inside the loop.
 Unlike for loops, you must increment or decrement the while iterator.
4. To add the current iterator value to the sum, type the following line as shown below, right after the while statement.
5. Return the value of sum.
 Update the iterator last; otherwise, you miss the first iteration addition.
6. Calculate the value of sigma for 5.
As expected, the program is equivalent to the following sum:
Add continue statements to keep the loop running but to skip a specific iteration.
Write a function that sums all the numbers from 0 to n, except for numbers that can be divided by 17.
1. Copy the above function and rename it to sigma_not17.
2. Inside the while loop, add a new line under the while statement.
3. Add an if statement and type the expression below.
4. To avoid endless looping, decrement n by 1.
5. To add a continue statement, on the Math tab, in the Operators and Symbols group, click Programming, and then click continue.
6. Calculate the value of sigma_not17 for 16 and 17.
Write a program that sums all numbers and exits the loop when the counter is greater than 20.
1. Define a variable sum and create a new program.
2. To add an empty while loop, on the Math tab, in the Operators and Symbols group, click Programming, and then click while.
3. Specify that the while loop should run forever.
 A while loop runs as long as the value of the expression inside the parenthesis is not 0.
4. Initialize sum and i.
5. Add the value of the iterator i to a variable sum and increment i by 1 inside the loop.
6. Return the value of sum.
 Currently this loop is infinite.
7. To break the loop, type if i > 20 and add the break statement. To add a break statement, on the Math tab, in the Operators and Symbols group, click Programming, and then click break.
8. Calculate sum.
9. To break the loop and exit the program, select the break statement and on the Math tab, in the Operators and Symbols group, click Programming, and then click return, to modify it to a return statement. Type sum in the placeholder as shown below.