for loop

Module 1. Java Syntax
Level 6 , Lesson 3
Available

1. Comparing loops: for vs while

A while loop can be used anywhere a statement or group of statements needs to be performed several times. But among all the possible scenarios, one is worth highlighting.

We're talking about the situation when the programmer (the program's creator) knows in advance how many times the loop should be executed. This is usually handled by declaring a special counter variable, and then increasing (or decreasing) the variable by 1 with each iteration of the loop.

Everything seems to work as it should, but it isn't very convenient. Before the loop, we set the counter variable's initial value. Then in the condition we check whether it has already reached the final value. But we usually change the value at the very end of the loop body.

And what if the body of the loop is large? Or if we have several nested loops? In general, in these cases it's desirable to collect all this information about counter variables in one place. And that's why we have the for loop in Java. It also doesn't look very complicated:

for (statement 1; condition; statement 2)
{
   block of statements
}

A while loop has just a condition in parentheses, but a for loop adds two statements, separated by semicolons.

The reality is simpler than it sounds: the compiler converts a for loop into an ordinary while loop like this:

statement 1;
while (condition)
{
   block of statements
   statement 2;
}

Or better yet, let's demonstrate this with an example. The two code snippets below are identical.

Option 1 Option 2
for (int i = 0; i < 20; i++)
{
   System.out.println(i);
}
int i = 0;
while (i < 20)
{
   System.out.println(i);
   i++;
}

We just gathered into one place all the code that pertains to the i counter variable.

In a for loop, statement 1 is executed just once, before the loop itself begins. This can be seen clearly in the second code snippet

statement 2 is executed the same number of times as the body of the loop, and each time it is executed after the entire body of the loop has been executed


2. Where the for loop is used

The for loop is probably the most used type of loop in Java. It is used everywhere, for programmers it is just clearer and more convenient than a while loop. Virtually any while loop can be converted into a for loop.

Examples:

while loop for loop
int i = 3;
while (i >= 0)
{
   System.out.println(i);
   i--;
}
for (int i = 3; i >= 0; i--)
{
   System.out.println(i);
}
int i = 0;
while (i < 3)
{
   System.out.println(i);
   i++;
}
for (int i = 0; i < 3; i++)
{
   System.out.println(i);
}
boolean isExit = false;
while (!isExit)
{
   String s = console.nextLine();
   isExit = s.equals("exit");
}
for (boolean isExit = false; !isExit; )
{
   String s = console.nextLine();
   isExit = s.equals("exit");
}
while (true)
   System.out.println("C");
for (; true; )
   System.out.println("C");
while (true)
{
   String s = console.nextLine();
   if (s.equals("exit"))
      break;
}
for (; true; )
{
   String s = console.nextLine();
   if (s.equals("exit"))
      break;
}

Pay attention to the last example. The statements for working with the loop counter are missing. There is no counter and no statement.

In a for loop, Java lets you omit the "statement to initialize the counter" and the "statement to update the counter". Even the expression that defines the loop condition can be omitted.


6
Task
New Java Syntax, level 6, lesson 3
Locked
String array in reverse order
1. Create an array of 10 strings. 2. Enter 8 strings from the keyboard and save them in the array. 3. Display the contents of the entire array (10 elements) on the screen in reverse order. Each element on a new line.

3. Nuances of using the for loop

An important point about using for loops and break and continue statements.

A break statement in a for loop works the same as in a while loop — it terminates the loop immediately. A continue statement skips the loop body, but not statement 2 (which changes the loop counter).

Let's take another look at how for and while loops are related.

for (statement 1; condition; statement 2)
{
   block of statements
}
statement 1;
while (condition)
{
   block of statements
   statement 2;
}

If a continue statement is executed in a for loop, then the rest of the block of statements is skipped, but statement 2 (the one that works with the for loop's counter variable) is still executed.

Let's return to our example with skipping numbers that are divisible by 7.

This code will loop forever This code will work fine
int i = 1;
while (i <= 20)
{
   if ( (i % 7) == 0) continue;
   System.out.println(i);
   i++;
}
for (int i = 1; i <= 20; i++)
{
   if ( (i % 7) == 0) continue;
   System.out.println(i);
}

The code that uses the while loop will not work — i will never be greater than 7. But the code with the for loop will work fine.


6
Task
New Java Syntax, level 6, lesson 3
Locked
Array of numbers in reverse order
1. Create an array of 10 numbers. 2. Enter 10 numbers from the keyboard and write them to the array. 3. Display the elements of the array in reverse order. Display each value on a new line.

4. Comparing for loops: Java vs Pascal

By the way, Pascal also has a For loop. In general, essentially every programming language has one. But in Pascal is it super clear. Examples:

Pascal Java
For i := 1 to 10 do
Begin
   Writeln(i);
End;
for (int i = 1; i <= 10; i++)
{
   System.out.println(i);
}
For i := 1 to 10 do step 2
Begin
   Writeln(i);
End;
for (int i = 1; i <= 10; i = i + 2)
{
   System.out.println(i);
}
For i := 10 downto 0 do step 2
Begin
   Writeln(i);
End;
for (int i = 10; i >= 0; i = i - 2)
{
   System.out.println(i);
}

Comments (18)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Ahsan, Usman Level 5, Norco, USA
11 December 2023
Actually so Light.
Zhanysh Level 41, Warsaw - the best!
1 November 2023
Easy :)
18 April 2023
Why did we have to use the continue statement in that last one?
Abhishek Tripathi Level 72, Rewa, India Expert
4 July 2023
So that our program will not print the statement (i) when the value of the i = 7 and for other values of i we'll print the statement (i itself ).
muchemi Level 5, United States of America, United States
10 April 2023
Dear support, kindly read the comments and rewrite the question to reflect the feedback on clearer instructions.
John Squirrels Level 41, San Francisco, Poland
10 April 2023
Could you please specify what question should be rewritten?
Anonymous #11225109 Level 5, United States of America, United States
4 February 2023
public class Solution { public static void main(String[] args) { for (int i = 1; i <15; i++) { if ( !(i % 2) == 0) continue; System.out.println(i); } } }
Josip Batinić Level 17, Croatia
26 January 2023
This is a hard one. Maybe this explanation of the task will help: The task is to write a program that reads 3 integers from the keyboard: start, end, and multiple. The program should use a for loop to display the sum of multiples of multiple variable in the range from start (inclusive) to end (not inclusive). To move to the next iteration of the loop, use a continue statement. Sum of multiples of multiple variable means the sum of all numbers in the range from start (inclusive) to end (not inclusive) that are evenly divisible by the multiple variable. For example, if the inputs are start = 2, end = 10, and multiple = 3, then the program would calculate the sum of all numbers in the range from 2 (inclusive) to 10 (not inclusive) that are evenly divisible by 3, which would be 3 + 6 + 9 = 18.
Java coffee Level 5, Ireland
15 November 2024
Thank you so much for your explanation, I finally understood what the task was about and I was able to correctly solve it.
Shuvam Chattopadhyay Level 5, Kolkata, India
14 October 2022
bruh tf was that last task
Alex Level 5, Romania
25 August 2022
"sum of multiples of multiple variable" tried to understand what to do, gave up. Read Ryan explanation, got it. Thanks Ryan!
ABHISHEK PANDEY Level 14, Mumbai , India
5 September 2022
sum only those numbers which are multiple of a given value here a given value is value of variable named multiple
28 September 2022
Never give up bro
silentPlanet Level 8, Hartford, United States
14 June 2022
What on earth are those instructions in the "Sum of Even Numbers" task? I know english is not your first language, and that's fine, but those instructions are outrageous lmao.
Ryan Level 13, United States
14 June 2022
I'm glad I'm not the only one. I've read it 5 times and I'm still unsure what is required of me. *Edit for anyone else who needs it: I believe it is the title that is misleading. It's not the sum of even numbers, it is the sum of numbers that are considered a multiple of the variable "multiple" Ex: if the multiple is 3 and the start and end are 1 & 30, respectively, multiples would include (3, 6, 9, 12, 15, 18, 21, 24, 27) Which means the sum would be all of those just added together. Edit: 30 would not included because the end of the range is not to be included. -Thanks Hipokratestl
hipokratestl Level 24, Poland
15 June 2022
Except 30, end number is not inclusive
Ryan Level 13, United States
17 June 2022
Whoops, you are correct -> I'll edit that out.
GioGTelian Level 10
21 October 2022
thank u ryan