JavaRush /Java Blog /Random EN /For Loop in Java

For Loop in Java

Published in the Random EN group
They say that the best programmer is a lazy programmer. Instead of performing the same type of actions several times, he will come up with an algorithm that will do this job for him. And he will do it well so that it does not need to be redone. How to use a for loop in Java - 1Something like this, in order not to write the same code many times, they came up with cycles. Imagine that we need to print numbers from 0 to 99 to the console. Code without a loop:
System.out.println(0);
System.out.println(1);
System.out.println(2);
System.out.println(3);
System.out.println(4);
System.out.println(5);
// And so on
This code will take 100 lines! So many. Here's what it would look like with a loop:
for(int i = 0; i < 100; i++) {
   System.out.println(i);
}
Only 3 lines!

What are for loops?

The for loop is a program code control structure that violates the linearity of the algorithm execution and allows the specified code to be executed many times. For example, you need to take 30 drops of medicine. The algorithm will be something like this:
  1. Prepare a glass.
  2. Open cover.
  3. Get 1 drop.
  4. Get 2 drops.
  5. Get 30 drops.
  6. Close medicine.
  7. Take your portion.
This algorithm can be explained much faster:
  1. Prepare a glass.
  2. Open the drip cap.
  3. Get 30 drops.
  4. Close medicine.
  5. Take your portion.
We use a for loop almost every day when talking to other people: “...20 steps further down the street...”, “...do 10 reps and 5 more at 2 times slower…”, “...do 5 purchases in various categories and get a prize ... ”you can go on for a long time, but the meaning is clear. In Java, the for loop is necessary to keep the code short and concise.

How the for loop works

The for loop is used like this:
for(<начальная точка>; <condition выхода>; <операторы счетчика>) {
	// Loop body
}
Пример перебора цифр от 0 до 5 и вывод каждой в консоль:
for(int i = 0; i < 5; i++) {
   System.out.println(i);
}
Conclusion:

0
1
2
3
4
If you translate this entry into human language, you get the following: “ Create a variable i with an initial value of 0 until it reaches 5, add 1 to it, and write the value of i to the console at each step .” The for loop in Java is based on three stages, which can be represented by the following diagram: How to use the for loop in Java - 2The exit condition of the loop is a Boolean expression. If it is false, the loop will terminate. In the example above, the variable iis incremented by 1. If its value is less than 5, the loop continues. But as soon as iit becomes greater than or equal to 5, the loop will stop. The counter operator is an expression that performs a conversion on the counter variable. In the example above, the variableiincreased by 1. That is, the loop will be executed exactly 5 times. If the counter operator adds 2 to the variable i, the result will be different:
for(int i = 0; i < 5; i = i + 2) {
   System.out.println(i);
}
Conclusion:

0
2
4
You can also multiply a variable, divide, raise to a power, in general, do whatever you want. The main thing is that the result of the conversion is a number. The loop body is any code that can be executed. In the example above, in the body of the loop, the value of the variable i was output to the console, but the contents of this body are limited by the task and imagination. Summarizing the whole scheme, the principle of this loop - for - is as follows: the code that is in the body of the loop will be executed as many times as the counter operator performs transformations before the loop exit condition is reached. If you set the loop exit condition as true:
for(int i = 0; true; i++) {
   if(i % 1000000 == 0) System.out.println(i);
}
System.out.println("Loop ended");
Then the code after the loop will be marked with an error unreachable statementbecause it will never be executed. Tricky challenge: Will the code below print “ Loop ended” to the console, or will the loop run indefinitely?
for(int i = 0; i > -1; i++) {
   if(i % 1000000 == 0) System.out.println(i);
}
System.out.println("Loop ended");
Answer: will. The variable i will sooner or later reach its maximum value, and a further increase will turn it into a maximum negative value, as a result of which the exit condition will be satisfied (i <= -1).

forEach loop

When working with loops, sometimes you have to iterate over arrays or collections. You can usually iterate over an array with a for loop:
public void printAllElements(String[] stringArray) {
   for(int i = 0; i < stringArray.length; i++) {
       System.out.println(stringArray[i]);
   }
}
And it is right. However, to iterate through all the elements of the array in turn, they came up with the forEach construct. Its signature is as follows:
for(<Тип element> <Name переменной, куда будет записан очередной элемент> : <Название массива>) {
	// Loop body
}
You can iterate through an array of strings and output each one to the console in the following way:
public void printAllElements(String[] stringArray) {
   for(String s : stringArray) {
       System.out.println(s);
   }
}
Also short and concise. Most importantly, there is no need to think about the counter and the exit condition, everything is already done for us.

How for loops are used

Now let's look at a few examples of using the for loop in Java to solve various problems.

Reverse cycle (from largest to smallest)

for(int i = 5; i > 0; i--) {
   System.out.println(i);
}
Conclusion:

5
4
3
2
1

Multiple Variables and Incrementing a Counter in a Loop Body

Several variables can be used in a for loop, for example, they can be converted in a counter statement:
int a = 0;
for(int i = 5; i > 0; i--, a++) {
   System.out.print("Step: " + a + " Meaning: ");
   System.out.println(i);
}
Conclusion:

Шаг: 0 Значение: 5
Шаг: 1 Значение: 4
Шаг: 2 Значение: 3
Шаг: 3 Значение: 2
Шаг: 4 Значение: 1
Or declare two variables and loop until they are equal to each other:
for(int i = 5, j = 11; i != j; i++, j--) {
   System.out.println("i: " + i + " j: " + j);
}
Conclusion:

i: 5 j: 11
i: 6 j: 10
i: 7 j: 9
It is unlikely that this action has any value, but it is useful to know about such a possibility. You can also create inner loops in a for loop. In this case, the number of loop steps will be multiplied:
for(int i = 0; i < 5; i++) {
   System.out.print(i + " | ");
   for(int j = 0; j < 5; j++) {
       System.out.print(j + " ");
   }
   System.out.print('\n');
}
Conclusion:

0 | 0 1 2 3 4 
1 | 0 1 2 3 4 
2 | 0 1 2 3 4 
3 | 0 1 2 3 4 
4 | 0 1 2 3 4
In a loop with a counter, jit is possible to access the counter of the outer loop. This makes nested loops an ideal way to iterate over 2D, 3D, and other arrays:
int[][] array = { {0, 1, 2, 3, 4 },
                       {1, 2, 3, 4, 5},
                       {2, 3, 4, 5, 6},
                       {3, 4, 5, 6, 7}};

for(int i = 0; i < array.length; i++) {
   for(int j = 0; j < array[i].length; j++) {
       System.out.print(array[i][j] + " ");
   }
   System.out.print('\n');
}
Conclusion:

0 1 2 3 4 
1 2 3 4 5 
2 3 4 5 6 
3 4 5 6 7 

Early termination of the cycle

If you need to interrupt the loop while processing it, use the statement break, which stops the current loop body. All subsequent iterations are also skipped:
public void getFirstPosition(String[] stringArray, String element) {
   for (int i = 0; i < stringArray.length; i++) {
       if(stringArray[i].equals(element)) {
           System.out.println(i);
           break;
       }
   }
}
The method will print the position of the first searched element in the array:
String[] array = {"one", "two", "three", "Jeronimo"};
getFirstPosition(array, "two");
Conclusion:

1

Endless cycle

Another way to create an infinite for loop is to leave the counter declaration area, exit condition, and counter statement empty:
for (;;) {
}
But keep in mind that in most cases, an infinite loop is evidence of a logical error. Such a loop must have an exit condition. How to use the for loop in Java - 3
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION