문법:
for(dataType item : array) {
...
}
- array - an array or a collection
- item - each item of array/collection is assigned to this variable
- dataType - the data type of the array/collection
Ex.1>
// print array elements
class Main {
public static void main(String[] args) {
// create an array
int[] numbers = {3, 9, 5, -5};
// for each loop
for (int number: numbers) {
System.out.println(number);
}
}
}
output>
3
9
5
-5
Ex.2>
// Calculate the sum of all elements of an array
class Main {
public static void main(String[] args) {
// an array of numbers
int[] numbers = {3, 4, 5, -5, 0, 12};
int sum = 0;
// iterating through each element of the array
for (int number: numbers) {
sum += number;
}
System.out.println("Sum = " + sum);
}
}
output>
Sum = 19
출처: Programiz
'WIL(What I Learned)' 카테고리의 다른 글
Row, Column 구분. (0) | 2021.12.04 |
---|---|
21.12.4 토 (0) | 2021.12.04 |
Push 전 Commit 메시지 변경하기 (0) | 2021.11.30 |
21.11.29 月 (0) | 2021.11.30 |
21.11.26 金 (0) | 2021.11.26 |