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 the job for him. And he will do it well so that there is no need to redo it. How to use for loop in Java - 1In order to avoid writing the same code over and over again, loops were invented. Let's imagine that we need to display 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. And here's what it would look like with a loop:

for(int i = 0; i < 100; i++) {
   System.out.println(i);
}
Just 3 lines!

What are for loops?

A for loop is a control structure of program code that breaks the linearity of the execution of the algorithm and allows you to execute the specified code 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 the lid.
  3. Get 1 drop.
  4. Get 2 drops.
  5. ...
  6. Get 30 drop.
  7. Close the medicine.
  8. Take the received portion.
This algorithm can be explained much more quickly:
  1. Prepare a glass.
  2. Open the drip cap.
  3. Get 30 drops.
  4. Close the medicine.
  5. Take the received portion.
We use the for loop almost every day in conversation with other people: “...20 steps down the street...”, “...do 10 repetitions and another 5 at 2 times slower...”, “...do 5 purchases in various categories and get a prize…” I could 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

A 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 we translate this entry into human language, we get the following: “ Create a variable i with an initial value of 0, until it reaches 5, add 1 to it and at each step write the value of i to the console .” The for loop in Java is based on three stages, which can be represented by the following diagram: How to use a for loop in Java - 2The condition for exiting the loop is a Boolean expression. If it is false, the loop will end. 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 cycle will stop. The counter operator is an expression that performs a conversion on a counter variable. In the example above, the variable iwas increased 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 transformation results in a number. The body of the loop is any code that can be executed. In the example above, the body of the loop was outputting the value of variable i to the console, but the contents of this body are limited by the task and imagination. Summarizing the entire scheme, the principle of this for loop is as follows: the code that is in the body of the loop will be executed as many times as the number of conversions the counter operator will perform before the condition for exiting the loop 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 statement, since it will never be executed. A challenge for ingenuity: as a result of running the code below, will “ Loop ended” be output to the console or will the loop run endlessly?

for(int i = 0; i > -1; i++) {
   if(i % 1000000 == 0) System.out.println(i);
}
System.out.println("Loop ended");
Answer: there will be. The variable i will sooner or later reach its maximum value, and 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, you sometimes have to iterate over arrays or collections. Typically you can iterate through an array using 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 one by one, they came up with the forEach construction. Its signature is as follows:

for(<Тип element> <Name переменной, куда будет записан очередной элемент> : <Название массива>) {
	// Loop body
}
You can iterate through an array of strings and print 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 larger to smaller)


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

5
4
3
2
1

Several variables and incrementing the counter in the loop body

You can use multiple variables 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 this possibility. You can also create inner loops within 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 counter loop, jit is possible to access the counter of the outer loop. This makes nested loops an ideal way to traverse two-dimensional, three-dimensional, 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 completion of the cycle

If you need to interrupt a loop while processing a loop, use the operator break, which stops the current body of the loop. 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 a for loop in Java - 3
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION