Search code examples
lua

Lua - Take Multiple inputs


I want to write a program that calculate the Average of all input numbers.

First it will asks "How many number you want to input" If users type 5 then the program will take 5 inputs Then it calculates the Average of it.

I wrote a function that takes passed numbers & returns average of of it But How do we ask the user to input multiple inputs and save it in array


Solution

  • local num = nil;
    
    local sum = 0;
    
    local n = 0;
    
    while num != 0 do
        num = io.read()
        sum = sum + tonumber(num)
        n = n + 1;
    end
    
    print(sum / (n-1))
    

    this code will calculate all inputs and will stop asking for input until the user types 0, when he types 0, he will print the average of the values entered