双层循环的编写方法取决于所使用的编程语言和数据结构。以下是几种常见编程语言中双层循环的示例代码:
Python 示例
```python
双层for循环遍历列表
list1 = [1, 2, 3]
list2 = [4, 5, 6]
for i in list1:
for j in list2:
print(i, j)
```
Bash 示例
```bash
双层for循环打印矩形
length=5
weight=5
for ((i=0; i for ((j=0; j echo -n "*" done echo "" done ``` C++ 示例 ```cpp include int main() { int a = {0}; // 双层for循环给二维数组赋值 for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { a[i][j] = i + j; } } // 双层for循环输出二维数组 for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { std::cout << a[i][j] << " "; } std::cout << std::endl; } return 0; } ``` Java 示例 ```java public class DoubleLoop { public static void main(String[] args) { // 双层for循环遍历数组 int[][] array = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; 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.println(); } } } ``` JavaScript 示例 ```javascript // 双层for循环遍历数组 const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; for (let i = 0; i < array1.length; i++) { for (let j = 0; j < array2.length; j++) { console.log(array1[i] + " " + array2[j]); } } ``` 这些示例展示了如何在不同编程语言中编写双层循环。根据具体需求选择合适的编程语言和数据结构,可以实现各种复杂的操作和计算。