[RUBY] "Infinite loop" that the middle two boys once said

What is an infinite loop?

When each method or while statement is used for repeated processing, there is no end and the processing is repeated forever. Of course, it puts a load on the personal computer.

Concrete example

number = 0
while number >= 0
 puts number
 number += 1
end

Continue to add 1 to number and output.

while statement

while conditional expression
 #Processing to repeat when the conditional expression is true
end

If the conditional expression is not true like the if statement, the process will not be executed. If you put true in the conditional expression, it will surely be repeated.

How to stop an infinite loop

Use break. For example

number = 0
while number >= 0
 if number == 100
  break
 end
 puts number
 number += 1
end

Use the if statement to end the process when the number reaches 100. That is, the final output is 99.

point

-[x] The while statement processes only when the conditional expression is true. -[x] Infinite routes can be stopped with break.

Finally

I don't think there are many situations where an infinite loop occurs.

Recommended Posts

"Infinite loop" that the middle two boys once said