迴圈語句可以在迴圈內使用任意型別的命令,包括其他迴圈命令。這種迴圈叫做巢狀迴圈(nested loop)在使用巢狀迴圈時,你是在迭代中使用迭代,與命令執行的次數是乘積關係。
[chendajie@chendajie nest_loop]$ cat test1
#!/bin/bash
# nesting for loops
for(( a =
1; a <=
3; a++
))do
echo
"starting loop $a:"
for(( b =
1; b <=
3; b++
)) do
echo
" inside loop: $b"
done
done
[chendajie@chendajie nest_loop]$ ./test1
starting loop 1:
inside loop: 1
inside loop: 2
inside loop: 3
starting loop 2:
inside loop: 1
inside loop: 2
inside loop: 3
starting loop 3:
inside loop: 1
inside loop: 2
inside loop: 3
這個被巢狀的迴圈(也成為內部迴圈,inner loop)會在外部迴圈的每次迭代中遍歷一次它所有的值。注意,兩個迴圈的do和done命令沒有任何差別,bash shell知道當第乙個done命令執行時是指內部迴圈而非外部迴圈。
在混用迴圈命令時也一樣,比如在while迴圈內部放置乙個for迴圈:
[chendajie@chendajie nest_loop]$ cat -n test2
1 #!/bin/bash
2 # placing a for loop inside a while loop
34 var1=5
56 while
[$var1 -ge 0 ]
7 do
8 echo
"outer loop: $var1"
9 for
(( var2 =
1; var2 <
3; var2++
)) 10 do
11 var3=$[
$var1 * $var2
] 12 echo
" inner loop: $var1 * $var2 = $var3 "
13 done
14 var1=$[
$var1 -1 ]
15 done
[chendajie@chendajie nest_loop]$ ./test2
outer loop: 5
inner loop: 5 * 1 = 5
inner loop: 5 * 2 = 10
outer loop: 4
inner loop: 4 * 1 = 4
inner loop: 4 * 2 = 8
outer loop: 3
inner loop: 3 * 1 = 3
inner loop: 3 * 2 = 6
outer loop: 2
inner loop: 2 * 1 = 2
inner loop: 2 * 2 = 4
outer loop: 1
inner loop: 1 * 1 = 1
inner loop: 1 * 2 = 2
outer loop: 0
inner loop: 0 * 1 = 0
inner loop: 0 * 2 = 0
同樣,shell能夠區分開內部for迴圈和外部while迴圈各自的do和done命令
下面這個時混用until和while迴圈。
[chendajie@chendajie nest_loop]$ cat -n test3
1 #!/bin/bash
2 # using until and while loops
34 var1=3
56 until
[$var1 -eq 0 ]
7 do
8 echo
"outer loop: $var1"
9 var2=1
10 while
[$var2 -lt 5 ]
11 do
12 var3=
$(echo
"scale=4; $var1 / $var2"|bc
) 13 echo
" inner loop: $var1 / $var2 = $var3"
14 var2=$[
$var2 + 1 ]
15 done
16 var1=$[
$var1 -1 ]
17 done
[chendajie@chendajie nest_loop]$ ./test3
outer loop: 3
inner loop: 3 / 1 = 3.0000
inner loop: 3 / 2 = 1.5000
inner loop: 3 / 3 = 1.0000
inner loop: 3 / 4 = .7500
outer loop: 2
inner loop: 2 / 1 = 2.0000
inner loop: 2 / 2 = 1.0000
inner loop: 2 / 3 = .6666
inner loop: 2 / 4 = .5000
outer loop: 1
inner loop: 1 / 1 = 1.0000
inner loop: 1 / 2 = .5000
inner loop: 1 / 3 = .3333
inner loop: 1 / 4 = .2500
外部的until迴圈以值3開始,並繼續執行到值等於0.內部while迴圈以值1開始並一直執行,只要值小於5,每個迴圈都必須改變在測試條件中用到的值,否則迴圈就會無止盡進行下去。 巢狀for迴圈
根據外層的條件,判斷裡層能否執行,如果能執行,就把裡層 都迴圈完畢後,再繼續執行外層,繼續判斷。for 開始條件 判斷條件 更改條件 1.入門案例 public class test for system.out.println 總結2 外迴圈控制行,內迴圈控制列 for int i 1 i 2 i...
for迴圈 巢狀
package com.d for迴圈 巢狀 date 2022.2.24 正直角三角形 倒直角三角形 等腰三角形 九九乘法口訣表 public class fornest 正直角三角形 public static void zl system.out.println 外層用println換行 倒直...
PHP 條件巢狀 迴圈巢狀 條件迴圈相巢狀
1.條件巢狀 demo 假設在發3月工資的時候,不僅判定性別,還要判定男性是否有房,沒有房,可以發放住房補貼,對於女性,判定是否懷孕,懷孕還有懷孕補貼 totalmoney 0 總工資 basicmoney 8000 基本工資 男 nohouse true 沒有房?housemoney 150 住房...