A lecture snippet with a mentor as part of the Codegym University course. Sign up for the full course.


"I want to tell you about one more loop. The for loop. It's just another way to express a while loop, just more compact and convenient (for programmers). Here are some examples:"

while
int i = 3;
while (i >= 0)
{
    System.out.println(i);
    i--;
}
for

for (int i = 3; i >= 0; i--) { System.out.println(i); }
while
int i = 0;
while (i < 3)
{
    System.out.println(i);
    i++;
}
for

for (int i = 0; i < 3; i++) { System.out.println(i); }
while
boolean isExit = false;
while (!isExit)
{
    String s = buffer.readLine();
    isExit = s.equals("exit");
}
for

for (boolean isExit = false; !isExit; ) { String s = buffer.readLine(); isExit = s.equals("exit"); }
while
while (true)
    System.out.println("C");
for
for (; true; )
    System.out.println("C");
while
while (true)
{
    String s = buffer.readLine();
    if (s.equals("exit"))
        break;    
}
for
for (; true; )
{
    String s = buffer.readLine();
    if (s.equals("exit"))
        break;    
}

"Eh?"

"These loops are equivalent. A while loop contains a single condition in the parentheses, but there are three elements in a for loop statement. But the compiler turns a for loop into an equivalent while loop."

"The first expression in a for loop (highlighted in green) is executed once before the loop begins."

"The second expression is evaluated every time before the loop body is executed. This is like the condition in a while loop."

"The third expression is evaluated after every execution of the loop body."

"Why do we need one more loop? Everything is perfectly clear with the while loop."

"It's for programmers' convenience. Loops are very common in programming. It's helpful to have a single line contain information on the loop counter's initial value, the termination condition, and the increment expression."