int[] squareNumbers = new int[10];
// Go through each of the Array indexes, from 0 to 9.
for (int i = 0; i < 10; i++) {
// We need to be careful with the 0-indexing. The next square number
// is given by (i + 1) * (i + 1).
// Calculate it and insert it into the Array at index i.
int square = (i + 1) * (i + 1);
squareNumbers[i] = square;
}
squareNumbers := [10]int{}
// Go through each of the Array indexes, from 0 to 9.
for i := 0; i < 10; i++ {
// We need to be careful with the 0-indexing. The next square number
// is given by (i + 1) * (i + 1).
// Calculate it and insert it into the Array at index i.
square := (i + 1) * (i + 1)
squareNumbers[i] = square
// Go through each of the Array indexes, from 0 to 9.
for (int i = 0; i < 10; i++) {
// Access and print what's at the i'th index.
System.out.println(squareNumbers[i]);
}
// Will print:
// 1
// 4
// 9
// 16
// 25
// 36
// 49
// 64
// 81
// 100
for i := 0; i < 10; i++ {
// Access and print what's at the i'th index.
fmt.Println(squareNumbers[i])
}
// Will print:
// 1
// 4
// 9
// 16
// 25
// 36
// 49
// 64
// 81
// 100
// For each VALUE in the Array.
for (int square : squareNumbers) {
// Print the current value of square.
System.out.println(square);
}
// Prints exactly the same as the previous example.
// For each VALUE in the Array.
for _, square := range squareNumbers {
// Print the current value of square.
fmt.Println(square)
}
// Prints exactly the same as the previous example.
It can be seen as an improved For statement from the perspective of an array from the existing For Loop statement.
It can only be used in an array, and has the disadvantage of not being able to change the value of the array.
go.dev/play/p/PO-onZO8FM0