C 語言中 for 迴圈與 while 迴圈
For 迴圈
for 迴圈是一個重複控制結構。它執行特定的次數語句。首先,它從開始迭代的地方獲取初始值。其次,它獲取一個條件,該條件被檢查為真或假。最後,它遞增/遞減並更新迴圈變數。
以下是在 C 語言中 for 迴圈的語法:
for ( init; condition; increment ) {
statement(s);
}以下是在 C 語言中 for 迴圈的示例:
示例
#include <stdio.h>
int main () {
int a = 5;
for(int i=0;i<=5;i++) {
printf("Value of a: %d
", a);
a++;
}
return 0;
}輸出
Value of a: 5 Value of a: 6 Value of a: 7 Value of a: 8 Value of a: 9 Value of a: 10
While 迴圈
While 迴圈用於執行 while 迴圈塊內的語句,直到條件為真。它只接收一個條件來執行塊內的語句。當條件變為假時,它停止並執行 while 迴圈下的語句。
以下是 C 語言中 while 迴圈的語法:
while(condition) {
statement(s);
}以下是在 C 語言中 while 迴圈的示例:
示例
#include <stdio.h>
int main () {
int a = 5;
while( a < 10 ) {
printf("Value of a: %d
", a);
a++;
}
return 0;
}輸出
Value of a: 5 Value of a: 6 Value of a: 7 Value of a: 8 Value of a: 9
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP