Infinite for loop in Lua - loops

Why doesn't this work in lua?
for i = 1, 100, -1 do
print('Infinite')
end
The above loop prints nothing. From what I know from conventional languages like C/C++, the above should be an infinite loop.
C++ equivalent
for (int i = 1; i <= 100; i--)
cout << "Infinite";
I want to know how exactly a for loop in lua works. Isn't it the same as the C++ one given above?
Edit: I don't want to know How to make an infinite loop in lua. I am more concerned here with how a for loop in lua works?

As stated before, the for loop has three functions just like C/C++.
for i = <start>, <finish>, <increment> do
But lua will detect that the increment will not allow the function to end and will completely ignore this loop.
To create an infinite loop, you simple use:
while true do
In lua, putting a variable as an argument with no operator will check if the value exists/is true. If it is false/nil then it will not run. In this case, true is always true because it is constant so the loop goes forever.
while true do
print('Infinite Loop')
end

for is explicitly defined in Lua to check if current value is lower than limit if step is negative. Since step -1 is negative and current value 1 is lower than limit 100 right from the start, this for performs no loops.

A for loop in lua has the syntax below:
for init,max/min value, increment
do
statement(s)
end
so the code below will print from 1 to 10:
for i=10,1,-1
do
print(i)
end
To generate infinite loops in lua you might have to use while loops:
while( true )
do
print("This loop will run forever.")
end
for more visit http://www.tutorialspoint.com/lua/lua_loops.htm

Related

Can a recursive function containing a for loop that contains a call of the mentioned function be implemented using only for loops?

Similar questions have been asked and the general consensus is that anything can be converted from recursion to for loops and vice versa. However, I can't find a way to convert a function of the following pseudocode type to a for loop:
def recursive(n):
if n == 0:
return
for i in range(some_number):
do_sth...
recursive(n-1)
In this case, there is n nested loops and n varies depending on the given argument. When using only for loops, the number of nested loops seems to be always predetermined in the code, it doesn't vary depending on "input". Is there a way to make something like this using only for loops?
Is there a way to make something like this using only for loops?
Well, if you admit a while loop as a case of a pseudocode for loop, at least your example can be made:
def nonrecursive(n):
a = []
z = 0
while n:
while n:
i = z
if i == some_number: break
print((n, i))
a += [[n, i]]
n -= 1
z = 0
if not a: break
n, i = a.pop()
i += 1
z = i
We need to be careful here.
The general true statement is that loops can replace recursion and vice versa. This can be shown lots of ways; see the structured programming theorem for ideas.
Whether for loops can replace recursion depends upon your definitions. Can your for loops run forever, or for an indefinite amount of time not known in advance? If so, they are functionally equivalent to while loops, and they can replace recursion. If your for loops cannot be made to run forever or for an unknown (initially) number of iterations, recursion cannot always be replaced.
Really, it's while loops (plus a stack data structure) that can replace recursion without much trouble.

are all while loops convertible to for loops?

earlier, I thought that we can't use for loops when working with linked lists... but then
for(current = head; current != NULL; current = current->next)
this line made me think. is all while loops are convertible to for loops especially when there is more than one condition?
Yes anything which can be written in a while loop can be represented with a for loop. Both of them are entry controlled loops which means first they check the condition and then the body is executed.
For a loop to run properly, we need at least one thing, i.e. condition and at most 3 things:
Initialization of the looping variable (If necessary)
Condition (Necessary)
Modification to the looping variable (If looping variable is initialized)
Now I will present a simple code block with both while and for loops:
-> To print all naturals numbers from 1 to 100.
Using While loop
int i=1; //Initialization of looping variable
while(i<=100) //Condition check
{
cout<<i;
i++; //Increment (Modification of looping variable)
}
Using For loop
Method 1:
for(int i=1;i<=100;i++)
//Here the first part to the for is initialization of looping variable.
// Second part is the Condition
// Third part is the increment
{
cout<<i;
}
Method 2:
int i=1;//Initializing the loop variable
for(;i<=100;)//Condition
{
cout<<i;
i++;//Increment
}
I gave this 2 methods to write the For loop, to show that both while and for loop can run only with the condition. If we are capable enough to rewrite the code in the format we need, both will run exactly in the same way.
You can use for loops in this instance because you are iterating a specific number of times (once per item in the list). It's not super intuitive but most purely programming related you could manage to change from a purely true/false run condition to a bounded countable run condition.
This line of thinking breaks down very quickly if you involve any amount of hardware. Let's say you have a program that turns on an LED so long as you hold down a button.
while(button is down)
{
LED = ON;
}
Something like this you wouldn't want to do with a for loop because there is no way of counting something to know when you stop, the amount of time is decided by the person holding down the button and can't be known by the computer until it actually happens.
TL;DR: You can use for loops for a lot of things that aren't intuitive. But you can't use them to replace EVERY possible while loop.
Some code example from my code, using while in a way that I wouldn't replace it with a for.
public function generateUniqueTokenForEntity(){
while (true) {
$token = substr(md5(uniqid()), 0, 10);
$entry = $databaseTable->findEntryByToken($token);
if ($entry === null) {
return $token;
}
}
}

Syntax/concept of a non-iterated loop?

I'm trying to iterate through a loop (any programming language, really, but for this exercise I happen to be using c#) and I was just wondering... what happens when you try to use a loop that doesn't iterate at all (i.e. ...."null"?)
For example:
int x = choose(0,1,2);
for(int i=0;i<x;i++) {
//some stuff
}
Like, what would happen if x gets chosen to be 0? Does it just become a useless for loop on that case? Will my program crash? Is that bad programming practice? etc. etc.
I'm mainly asking because I'm trying to format a concatenated string but only if some array has enough elements. thanks
Well simply put, nothing will happen. A for loop is like an if statement where it checks the condition and repeats while that condition is true.
for(int i=0;i<x;i++)
This is saying:
Initialize i to 0
Check if i is less than the value of x
Increment i at the end of the loop
If x is 0, then the loop will simply not run; it becomes useless.

End condition of an IF loop that depends on a 3D array

I'm writing a program which will move a particle about a cube, either left,right,up,down, back or forward depending on the value randomly generator by the program. The particle is able to move with cube of dimensions LxLxL. I wish the program to stop when the particle has been to all possible sites and the number of jumps taken output.
Currently I am doing this using an array[i][j][k] and when the particle has been to a position, changing the value of the array at that corresponding point to 0. However, in my IF loop I have to type out every possible combination of i,j and k in order to say if they are all equal to 0 the program should end. Would there be a better way to do this?
Thanks,
Beth
Yes. I'm assuming the if in question is the one contained within the triple nested loop who's body sets finish=1;. The better way of doing this is to set a your flag before the loop, beginning with a true value then setting it to false and breaking if you encounter a value other then zero. Your if statement becomes much simpler, like this;
int finish =1; // start with a true value
//loops are untouched so still got the for i and for j above this
for(k = 0; k < 15; k++)
{
if (list[i][j][k] != 0)
{
finish = 0;
break;
}
}
// outside all the loops
return finish;
I think this is what you're asking for but if not please edit your question to clarify. I'm not sure if there is some technical name for this concept but the idea is to choose your initial truth value based on what's most efficient. Given you have a 15x15x15 array and a single non-zero value means false, it's much better to begin with true and break as soon as you encounter a value that makes your statement false. Trying to go in the other direction is far more complicated and far less efficient.
Maybe you can add your list[i][j][k] to a collection every time list[i][j][k]=0. Then at the end of your program, check for the collection's length. If it's of the right length, then terminate..

find the number of comparisons in the execution of the loop for any n>0 in the given code

Consider the following C code
int j,n; //declaration
j=1; //initialization
while(j<=n) //while loop
j=j*2; //code ends here
What is the number of comparisons made in the execution of the loop in the above code?
I have tried the following: let increment of j is pow(2,0), pow(2,1), pow(2,2), etc. For some value of i so according to the question
pow(2,i)<=n
i<=(log n/log2)
What after this? The answer is floor(log n/log 2)+1 but how?
That code is undefined, there is no answer since you don't specify the value of n and as the code is written there's no chance for n to have a well-defined value when the loop runs.
n is never initialised, so technically the behaviour is undefined as you're using an uninitialised variable in while (j<=n).
If you want to set n to the largest possible integer value, use
n = INT_MAX
Which is defined in the standard include file <limits.h>
But, that will result in integer overflow due to j=j*2 happening after the j<=n check. One way round this would be to define n = INT_MAX / 2. Better still use a do / while loop rather than while and perform the check at the end.
Assuming that you initialized the variable n with a proper value, as you know you are going to pow(2,i)<=n which means i<=log{2}n (just inverting the function).
log{base 2}n = log n/log2 for the well known logarithmic property.
Now the calculation is exact when i is real but in this case i is an integer you won't get exactly that number so the correct index will be in the approximation of [floor(logn/log2);floor(logn/log2)+1] which will be the loop required for for pow(2,i)<=n<pow(2,i+1)
Let's do a simple example:
n=11; ln(n)/ln(2)=2.39/0.69=3.46
floor(3.46) = 3
floor(3.46)+1 = 4
i=1 i<=n: true: i*=2
i=2 i<=n: true: i*=2
i=4 i<=n: true: i*=2
i=8 i<=n: true: i*=2
i=16 i<=n: false=> don't loop
which is exactly four
Let us assume some n values
For n=1 loop executes 1 time.
For n=2 loop executes 2 times.
For n=3 loop executes 2 times.
For n=(4 to 7) loop executes 3 times.
For n=8 loop executes 4 times.
So for n values like 1,2,4,8,16... loop executes 1,2,3,4,5...
Therefore if you compare these values mathematically -
For n=2^k loop executes (k+1) times from n=2^k, k=log2n (logn with base 2)
So loop executes log2n(floor value)+1 times.
yes code will end you are not initializing n. First initialize it then calculte

Resources