I have an array:

int[] array = new int[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; 

I need to bring all the elements of the array to the console, I understand that for this we need a cycle:

 for (int i = 0; i < 10; i++) { System.out.println(array[i]); } 

And what if we add several elements, let's say:

 int[] array = new int[] {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 101, 102, 103}; 

How to sort through all these elements, constantly change the condition i <... That's actually the question, how to sort through the array of elements without knowing how many elements are there? :)

  • Sashko, thank you, I used your question in Java. And with a slight remake of it, on SI plus plus. You helped me a lot. - timob256

2 answers 2

@ Sashko , Good time of day!

  int[] array = new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 101, 102, 103, 104 }; for (int i = 0; i < array.length; i++) { System.out.println(array[i]); } 
  • Oooh, it works :) Thank you, @Kovalsky! - Sashko

To iterate over all the elements of an array in Java, there are at least three approaches:

Conditional loop

This is the usual "sishny" way. Just go through all the indices of the array, before each iteration, checking to see if it has reached the end.

 for (int i = 0; i < array.length; i++) { System.out.printf("%d\t%d\n", i, array[i]); } 

Collection cycle

We first write a variable that will take the values ​​of the elements of the array, and then after the colon - the name of our array. If you need an index, it will have to be considered separately.

 int i = 0; for (int element : array) { System.out.printf("%d\t%d\n", i, element); i++; } 

Applying threads

Starting with Java 8, a special interface Stream is available It is convenient to use, along with lyabda-functions.

 IntStream.of(array).forEach(element -> System.out.println("см. ==> " + element)); // если функции передаётся просто один аргумент, можно обойтись без стрелки IntStream.of(array).forEach(System.out::println); 

Bonus: the last two methods will work not only with arrays, but with arbitrary-type collections.