For loop java method

For loop in Java with example

For loop is used to execute a set of statements repeatedly until a particular condition returns false. In Java we have three types of basic loops: for, while and do-while. In this tutorial you will learn about for loop in Java. You will also learn nested for loop, enhanced for loop and infinite for loop with examples.

Syntax of for loop:

for(initialization; condition ; increment/decrement)

Initialization: In the initialization part, variables like loop counter (you will generally see i and j in loops, these are the loop counters) are initialized. This is an optional part of the loop as the variables can be initialized before the loop. This executes only once when the loop starts.

Condition: This is one of the important part of the loop. This condition determines till when the loop should keep repeating. The loop keeps repeating until the condition becomes false.

Increment/Decrement: In this part of the loop declaration, you can specify the increment or decrement of loop counter. This is to modify the loop counter value so that at one point condition becomes false and the loop ends.

Statement: The statements inside the loop body keeps executing for each iteration of the loop until the loop stops.

Flow of Execution of the for Loop

for loop Java

As a program executes, the interpreter always keeps track of which statement is about to be executed. We call this the control flow, or the flow of execution of the program.

First step: In for loop, initialization happens first and only one time, which means that the initialization part of for loop only executes once.

Second step: Condition in for loop is evaluated on each iteration, if the condition is true then the statements inside for loop body gets executed. Once the condition returns false, the statements in for loop does not execute and the control gets transferred to the next statement in the program after for loop.

Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes that updates the loop counter.

Fourth step: After third step, the control jumps to second step and condition is re-evaluated.

Example: Simple for loop

This is a simple example of for loop. Here we are displaying the value of variable i inside the loop body. We are using decrement operator in the loop so the value of i decreases by one after each iteration of the loop and at some point the condition i>1 returns false, this is when the loop stops.

Читайте также:  Хакер программирования на java

The output of this program is:

The value of i is: 10 The value of i is: 9 The value of i is: 8 The value of i is: 7 The value of i is: 6 The value of i is: 5 The value of i is: 4 The value of i is: 3 The value of i is: 2

In the above program:
int i=1 is initialization expression
i>1 is condition(Boolean expression)
i– Decrement operation

Java Nested for loop

A for loop inside another for loop is called nested for loop. Let’s take an example to understand the concept of nested for loop. In this example, we are printing a pattern using nested for loop.

public class JavaExample < public static void main(String[] args) < //outer loop for(int i=1;i<=6;i++)< //inner loop for(int j=1;j<=i;j++)< System.out.print("* "); >// this is to move the cursor to new line // to print the next row of the pattern System.out.println(); > > >

Java for loop example

Output:

Infinite for loop

A loop that never stops executing is called infinite loop. This happens when the condition expression defined in loop never returns false. The following example will help you understand the importance of Boolean expression and increment/decrement operation co-ordination:

class ForLoopExample2 < public static void main(String args[])< for(int i=1; i>=1; i++) < System.out.println("The value of i is: "+i); >> >

This is an infinite loop as the condition would never return false. The initialization step is setting up the value of variable i to 1, since we are incrementing the value of i, it would always be greater than 1 (the Boolean expression: i>1) so it would never return false. This would eventually lead to the infinite loop condition. Thus it is important to see the co-ordination between Boolean expression and increment/decrement operation to determine whether the loop would terminate at some point of time or not.

Here is another example of infinite for loop:

Example: Iterate an array using for loop

Let’s see another example of for loop. Here we are iterating and displaying array elements using the for loop.

class ForLoopExample3 < public static void main(String args[])< int arr[]=; //i starts with 0 as array index starts with 0 too for(int i=0; i > >

Enhanced For loop

Enhanced for loop is another way of defining a loop. This is especially useful when you want to iterate array, ArrayList and other collections classes. Tt is easy to read and write.

Let’s take the same example that we have seen above. We are rewriting it using enhanced for loop.

class ForLoopExample3 < public static void main(String args[])< int arr[]=; for (int num : arr) < System.out.println(num); >> >

Note: In the above example, I have declared the num as int in the enhanced for loop. This will change depending on the data type of array. For example, the enhanced for loop for string type would look like this:

String arr[]=; for (String str : arr)

Check out these java programming examples related to for loop:

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Comments

I really appreciate and recommend this website to all the beginners and experienced as well. As i find it very ease in learning java, i’ve been in touch with the same for past 1yr but never been so comfortable with it. But after reading the few tutorials on this website i realized that, my concepts weren’t that much clear which i feel have been cleared after hitting these tutorials.
Thanks –

Читайте также:  Php code to get php version

Very Helpful for beginners…As I am from a Non-IT background in my graduation, this site has helped me a lot…Add more sample & simple programs so that we can know more.
Great going guys…keep it up 🙂

I think this array declaration is wrong.it can’t be like this.
int arr[4]=;
It should be like this
int arr[]=;

Both ways are correct. He declared and FIXED the size of array to 4 and if I come to your point, you can declare any number of members in your array!. Your concept is good for Multidimensional Array but for Single array.. Always declare the size of array!.

This is one of the best sites for learning java. Concepts are made very clear and explained in such a simple way. Wonderful way of teaching. Thank you so much!

Источник

Цикл For в Java

Java-университет

Как используют цикл for в Java - 1

Говорят, что лучший программист — ленивый программист. Вместо того, чтобы совершать однотипные действия по нескольку раз, он придумает алгоритм, который сделает эту работу за него. А еще он сделает его хорошо, чтобы не нужно было переделывать. Примерно так, чтобы много раз не писать один и тот же код, придумали циклы. Представим, что нам нужно вывести в консоль числа от 0 до 99. Код без цикла:

 System.out.println(0); System.out.println(1); System.out.println(2); System.out.println(3); System.out.println(4); System.out.println(5); // И так далее 

Что такое циклы for?

  1. Приготовить стакан.
  2. Открыть крышку.
  3. Получить 1 каплю.
  4. Получить 2 каплю. …
  5. Получить 30 каплю.
  6. Закрыть лекарство.
  7. Принять полученную порцию.
  1. Приготовить стакан.
  2. Открыть крышку капель.
  3. Получить 30 капель.
  4. Закрыть лекарство.
  5. Принять полученную порцию.

Принцип работы цикла for

 for(; ; ) < // Тело цикла >Пример перебора цифр от 0 до 5 и вывод каждой в консоль: for(int i = 0; i

Как используют цикл for в Java - 2

Если перевести данную запись на человеческий язык, получится следующее: “Создай переменную i с начальным значением 0, пока она не достигнет 5, прибавляй к ней по 1 и на каждом шаге записывай значение i в консоль.” В основе работы цикла for в Java лежат три стадии, их можно изобразить следующей схемой: Условие выхода из цикла — это булево выражение. Если оно ложно, цикл будет завершен. В примере выше переменная i увеличивается на 1. Если ее значение менее 5, цикл продолжается. Но как только i станет больше или равно 5, цикл прекратится. Оператор счетчика — выражение, которое выполняет преобразование переменной счетчика. В примере выше переменная i увеличивалась на 1. То есть цикл будет выполнен ровно 5 раз. Если оператор счетчика будет прибавлять по 2 к переменной i , результат будет иным:

Также можно умножать переменную, делить, возводить в степень, в общем, делать все, что угодно. Главное, чтобы в результате преобразования получилось число. Тело цикла — любой код, который может быть выполнен. В примере выше в теле цикла был вывод значения переменной i в консоль, однако содержимое данного тела ограничено задачей и фантазией. Обобщая всю схему, принцип данного цикла — for — следующий: код, который находится в теле цикла, будет выполнен столько раз, сколько преобразований выполнит оператор счетчика до того, как будет достигнуто условие выхода из цикла. Если задать условие выхода из цикла как true :

 for(int i = 0; true; i++) < if(i % 1000000 == 0) System.out.println(i); >System.out.println("Loop ended"); 

То код после цикла будет помечен ошибкой unreachable statement , так как никогда не будет исполнен. Задача на смекалку: в результате запуска кода ниже будет ли выведено в консоль “ Loop ended ” или цикл будет выполняться бесконечно?

 for(int i = 0; i > -1; i++) < if(i % 1000000 == 0) System.out.println(i); >System.out.println("Loop ended"); 

Ответ: будет. Переменная i рано или поздно достигнет максимального значения, а дальнейшее увеличение превратит ее в максимальное отрицательное, в результате чего условие выхода будет выполнено (i < = -1).

Читайте также:  Php curl curlopt cookiejar

Цикл forEach

При работе с циклами иногда приходится перебирать массивы или коллекции. Обычно массив можно перебрать с помощью цикла for:

 public void printAllElements(String[] stringArray) < for(int i = 0; i < stringArray.length; i++) < System.out.println(stringArray[i]); >> 

И это правильно. Однако, для перебора всех элементов массива по очереди придумали конструкцию forEach. Ее сигнатура следующая:

 public void printAllElements(String[] stringArray) < for(String s : stringArray) < System.out.println(s); >> 

Тоже кратко и лаконично. Самое главное, нет нужды думать о счетчике и об условии выхода, все уже сделано за нас.

Как используются циклы for

А теперь рассмотрим несколько примеров использование цикла for в Java для решения разнообразных задач.

Обратный цикл (от большего к меньшему)

Несколько переменных и увеличение счетчика в теле цикла

В цикле for можно использовать несколько переменных, например их можно преобразовывать в операторе счетчика:

 int a = 0; for(int i = 5; i > 0; i--, a++)
 Шаг: 0 Значение: 5 Шаг: 1 Значение: 4 Шаг: 2 Значение: 3 Шаг: 3 Значение: 2 Шаг: 4 Значение: 1 
 for(int i = 5, j = 11; i != j; i++, j--)
 i: 5 j: 11 i: 6 j: 10 i: 7 j: 9 

Вряд ли это действие имеет какую-либо ценность, но знать о такой возможности полезно. В цикле for также можно создавать внутренние циклы. В этом случае количество шагов цикла будет умножаться:

 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'); > 
 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 

В цикле со счетчиком j есть возможность обращаться к счетчику внешнего цикла. Благодаря этому вложенные циклы — идеальный способ обхода двумерного, трехмерного и прочих массивов:

 int[][] array = < , , , >; 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'); > 
 0 1 2 3 4 1 2 3 4 5 2 3 4 5 6 3 4 5 6 7 

Досрочное завершение цикла

Если при обработке цикла нужно его прервать, используйте оператор break , который останавливает работу текущего тела цикла. Все последующие итерации также пропускаются:

 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; >> > 
 String[] array = ; getFirstPosition(array, "two"); 

Бесконечный цикл

Еще один способ создать бесконечный цикл for — оставить пустой область объявления счетчика, условие выхода и оператор счетчика:

Как используют цикл for в Java - 3

Но учти, что в большинстве случаев бесконечный цикл — свидетельство логической ошибки. У такого цикла обязательно должно быть условие выхода.

Источник

Оцените статью