Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте For-Loop | Цикли
Основи Java
course content

Зміст курсу

Основи Java

Основи Java

1. Початок Роботи
2. Основні Типи та Операції
3. Цикли
4. Масиви
5. String

book
For-Loop

A major drawback of the while loop is that we can't specify an exact number of iterations and fully control the loop's execution. That's why the for loop exists, which provides us with all the tools for proper loop control and is also used when working with arrays and collections. It's a cool thing.

Основним недоліком циклу while є те, що ми не можемо вказати точну кількість ітерацій і повністю контролювати виконання циклу. Саме для цього існує цикл for, який надає нам всі інструменти для правильного управління циклом, а також використовується при роботі з масивами і колекціями. Це крута штука.

For цикл

Цикл for - це оператор потоку керування, який дозволяє повторно виконати блок коду задану кількість разів. Він зазвичай використовується, коли вам відома точна кількість ітерацій або коли ти виконуєш ітерації над колекцією чи масивом.

java

Main

copy
123
for (initialization; condition; update) { // code to be executed }

If we go step by step, initially, we initialize a variable in a special section for it (we did the same for the while loop, only we did it outside the loop). Then we set the condition for when the loop should run (for example, as long as the variable is less than 10). After that, in the third section, we use an increment or decrement. Below is a flowchart and an explanation of the operation of each of the loop blocks:

Here's the breakdown of each part of the for loop:

  • Initialization: This is the initial setup executed only once at the beginning of the loop. Typically, you declare and initialize a loop control variable here. For example, int i = 0;
  • Condition: This is the condition checked before each iteration. If the condition is true, the loop body is executed. If the condition is false, the loop terminates. For example, i < 10;
  • Increment/Decrement Expression: This is the code executed after each iteration. Typically, you update the loop control variable here. For example, i++ (which is equivalent to i = i + 1);
  • Code Inside Loop: This is the block of code executed for each iteration of the loop. You can put any valid Java code inside the loop body.

Ось розбивка кожної частини циклу for:

  • initialization: Це початкове налаштування, яке виконується лише один раз на початку циклу. Зазвичай тут оголошується та ініціалізується керуюча змінна циклу. Наприклад, int i = 0;
  • condition: Це умова, яка перевіряється перед кожною ітерацією. Якщо умова true, виконується тіло циклу. Якщо умова false, то цикл завершується. Наприклад, i < 10;
  • increment/decrement: Це код, який виконується після кожної ітерації. Зазвичай тут ви оновлюєте керуючу змінну циклу. Наприклад, i++ (що еквівалентно i = i + 1);
  • Код всередині циклу: Це блок коду, який виконується для кожної ітерації циклу. Ви можете помістити будь-який коректний код на мові Java в тіло циклу.
java

Main

copy
123456789
package com.example; public class Main { public static void main(String[] args) { for (int i = 0; i < 10; i++) { System.out.println("Iteration: " + i); } } }

In this example, the loop will execute 10 times. It starts with i initialized to 0, checks if i is less than 10, executes the loop body, and then updates i by incrementing it by 1. This process repeats until the condition becomes false.

It's worth noting that in this loop, we can use the variable we created. In our case, we output the variable i to display the iteration number on the screen.

This is very useful, especially when we need our variable i to be involved in the code.

Let's look at another example where we need to display only even numbers in the range from 1 to 30:

java

main

copy
1234567891011
package com.example; public class Main { public static void main(String[] args) { for (int i = 0; i < 30; i++) { if (i % 2 == 0) { // check if `i` is even System.out.println(i); } } } }

Great, in the code above, we used the variable i when checking the condition. In other words, i represents the numbers we are considering. Next, we check if the number i is even using the modulo operation (%). If the remainder of division by 2 is zero, then the number is even, meaning it is divisible by 2 without a remainder.

Also, pay attention to how we set the condition for i. The algorithm of our actions remains the same as it was, but in the loop condition, we limited i to a value of 30, as specified in the task.

1. How many iterations will be there?

2. How many times i will be displayed

How many iterations will be there?

How many iterations will be there?

Виберіть правильну відповідь

How many times `i` will be displayed

How many times i will be displayed

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 3. Розділ 5
We're sorry to hear that something went wrong. What happened?
some-alt