使用巢狀迴圈列印 1 至 9 四次冪的 C 程式
巢狀迴圈由一個放置在另一個迴圈內的迴圈組成。
巢狀 for 迴圈的示例如下 −
for (initialization; condition; operation){
for (initialization; condition; operation){
statement;
}
statement;
}在此示例中,內迴圈對外部迴圈的每次單次迭代執行其全部迭代範圍。
示例
以下 C 程式可透過使用巢狀 for 迴圈列印數字 1 至 9 的前四次冪的表格 −
#include <stdio.h>
void main(){
int i, j, k, temp,I=1;
printf("I\tI^2\tI^3\tI^4
");
printf("--------------------------------
");
for ( i = 1; i < 10; i ++) /* Outer loop */{
for (j = 1; j < 5; j ++) /* 1st level of nesting */{
temp = 1;
for(k = 0; k < j; k ++)
temp = temp * I;
printf ("%d\t", temp);
}
printf ("
");
I++;
}
}輸出
執行上述程式時,它產生以下結果 −
I I^2 I^3 I^4 ----------------------- 1 1 1 1 2 4 8 16 3 9 27 81 4 16 64 256 5 25 125 625 6 36 216 1296 7 49 343 2401 8 64 512 4096 9 81 729 6561
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP