FOR循環
——作為一個計數循環,在執行之前,就已經知道要循環多少次
要求
- 必須要有初始化計算器(例如 count=0之類的)
- 計算器必須與有限值進行比較(i<=j?)
- 每次循環完結,遞增or遞減計算器
For的格式
for把初始化,測試和更新組合到一起
例子:
#include<stdio.h> int main() { const int NUMBER = 22; int count; for(count = 1;count <=NUMBER;count++); printf("BE my Valentine!\n"); return 0; }
for 當中,(count=1)代表了初始化,只在循環開始前運行一次
(count<=NUMBER)代表了測試條件,即count小於等於NUMBER時,表達式為真,反之,則假
(count++) 代表了表達式執行更新,在每次循環結束后運行。
For具有強大的靈活性,滿足我們的各種需要
1.
用做計數器
#include<stdio.h> int main() { int secs; for(sec=0;sec<=5;sec++){ printf("% seconds\n",sec); printf("We have ignition\n"); return 0; }
輸出為 :
0 seconds
1 seconds
2 seconds
3 seconds
4 seconds
5 seconds
2.通過改變它的更新動作,來改變它的遞增or遞減
eg:(i +=2)//每次循環,i加2
3.可用字符代表數字計數:
#include<stdio.h> int main() { char ch; for (ch = 'a';ch<='z';ch++){ printf("The ASCII value for %c is %d.\n",ch,ch); } }
PS:因為字符以ASCII碼的形式保存在系統里,可當做整數計算