Processing math: 100%

Lesson goal: The while-loop to average numbers

Previous: Type some words | Home | Next: Mouse clicks

As mentioned, while-loops can make a chunk of program code run over and over until the condition of the while-loop becomes false. Here's an example that asks you to type a number. As long as you type a positive number, it'll keep computing the average of your numbers. As soon as you type in a negative number, it'll stop and tell you the average.

The code won't quite work. What condition you put in the while ... do line that will keep it looping as long as n0?

Now you try. Put a condition in the while ... do line that will keep the while loop running as long as n0.

Type your code here:

12
 
1
n=0
2
sum=0
3
count=0
4
while ???? do
5
 print("type a number (< 0 to exit): ")
6
 n = tonumber(input())
7
 if n >=0 then
8
  sum=sum+n
9
  count=count+1
10
 end
11
end
12
print("The average is",sum/count)

See your results here: