Leetcode learn array Code from Java to Go(Loop)

손진성·2022년 2월 8일
0

Leet Code

목록 보기
1/3

Writing Items into an Array with a Loop

Java

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;
}

Go

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

Reading Items from an Array with a Loop

Java

// 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

Go

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

Enhanced For Loop in Java

Java

// 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.

Go

// 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

profile
Gopyther

0개의 댓글