Page 1 of 1
repeat while with 2 conditions
Posted: Wed Jun 17, 2020 10:39 pm
by fhs14647
Dear Experts
How can I implement a repeat loop with 2 conditions:
1. Condition: number1 mod number2 should be 0
2. Condition: number 1 must be greater than number 0
2 Numbers should be generated by random and number 1 should be divided to zahl2. Only if modulo is 0 and number1 is larger than number2 is will be divided:
My Code Snippet
Code: Select all
else if text of field "labelKind" is "/" then
repeat while number1 mod number2 is not 0 and number1 < number2
creating //create 2 random numbers
end repeat
filling
put (number1 / number2) into sum
Thanks for your help
fhs14647
Re: repeat while with 2 conditions
Posted: Wed Jun 17, 2020 11:02 pm
by dunbarx
Hi.
Not sure what you need. It looks like you mostly have it.
Code: Select all
on mouseUp
repeat
put random(9) into var1
put random(9) into var2
if var1 mod var2 = 0 and var1 > var2 then
answer var1 & return & var2
exit repeat
end if
end repeat
end mouseUp
Craig
Re: repeat while with 2 conditions
Posted: Wed Jun 17, 2020 11:13 pm
by SparkOut
Where you have a "repeat while ..." loop with these multiple conditional tests, you need to be careful with the "double negative" effect.
You want
Code: Select all
repeat while number1 mod number2 is not zero
AND you want
which is to say that you want the repeat to continue looping while EITHER conditional test 1
OR conditional test 2 is true. Test 1 is true when not having 0 as a result of the mod operation, so regardless of the size comparison in test 2, it should loop. OR if the mod operation does result in zero, then if the size comparison result is that number1 is less than number2 then also loop. (Your test as written will accept number1 being equal to number2 by the way)
It helps to put the conditional tests in parentheses so you can see what resolves to true or fslse in each part of the structure.
Your repeat while loop should therefore be
Code: Select all
repeat while (number1 mod number2 is not zero) OR (number1 < number2)
You can simplify things if you follow Craig's info and test for positive conditions and break out of the repeat as he shows.
You could also reconstruct with a "repeat until ..." test1 AND test2 are both satisfied. But that's another exercise.
Re: repeat while with 2 conditions
Posted: Thu Jun 18, 2020 12:55 pm
by fhs14647
Thanks to dunbarx and SparkOut for the solution and their superb explaining!!
It works perfect now

Re: repeat while with 2 conditions
Posted: Thu Jun 18, 2020 1:46 pm
by dunbarx
Good.
Just a note. When using the basic "repeat" structure, that is, without any conditions or counters, make SURE you have a way to exit the loop:
Otherwise LC will happily repeat forever.
Craig
Re: repeat while with 2 conditions
Posted: Thu Jun 18, 2020 1:59 pm
by fhs14647
Thanks again!!