E
E
EVGENY T.2019-08-20 09:55:19
Java
EVGENY T., 2019-08-20 09:55:19

Endless loop or unnecessary variable behind the loop?

From time to time I meet with tasks where it is necessary to twist a variable inside the loop and end the loop when it reaches a certain value. There are two options for implementing this algorithm:
1. An infinite loop with exit inside

do {
 int myVar = getVar();
 // логика работы с myVar
 if (myVar <= 0)
 break;
} while (true)

The variable sits in its scope, the calculation takes one line, but the infinite loop looks scary, the exit from it somewhere in the middle is not obvious.
2. Loop with condition:
int myVar = getVar();
while(myVar > 0) {
 // логика работы с myVar
 myVar = getVar();
}

The cycle does not look endless, the way out is obvious. But the myVar variable does not need to loom outside the loop, there are two lines of its calculation.
Which algorithm would you prefer? Why?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ronald McDonald, 2019-08-20
@Beshere

1. Endless loop with exit inside

This. To be afraid of wolves - do not go into the forest, do not be afraid to take responsibility.
If you are afraid of infinite loops, don't use them. And you don’t need to be afraid of them, if you wrote everything correctly, then nothing terrible will happen.

K
Karpion, 2019-08-28
@Karpion

In this case, it is necessary to use not a loop-with-precondition "while ...", but a loop-with-postcondition "repeat ... until" (sometimes it is written as "... while" or "do ... while" , but the condition is at the end of the loop).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question