For循環
For 循環把所有三種動作(初始化,測試,更新)都放在一起
//6-11.c--- 一個使用for的計數循環
#include <stdio.h>
int main (void)
{
const int NUMBER = 22;
int count;
for (count = 1;count <= NUMBER;count++)
printf ("Be my Valentine!\n");
return 0 ;
}
關鍵字for之後的圓括號中包含了由兩個分號分開的三個表達式。第一個表達式進行初始化,他在for循環開始的時候執行一次。第二個表達式是判斷條件,在每次執行之前都要對它進行求值。當表達式爲假時循環結束,第三個表達式進行改變或稱爲更新,它在每次循環結束時進行計算。三個控制表達式中每一個都是完整的表達式
For 循環結構
////6-12.c--- 使用一個for循環產生一個產方表
#include <stdio.h>
int main (void)
{
int num ;
int c;
int a ;
printf (" n n cubed \n");
a = scanf ("%d",&c);
for(;a == 1;a = scanf ("%d",&c))
for (num =1;num <= c; num++)
printf ("%5d %5d\n",num ,num * num * num);
return 0 ;
}
利用for 的靈活性
9種可能性
1. 你可以使用減量運算符來減小計數器而不是增加它
如:
#include <stdio.h>
Int main (void)
{
Int secs;
For (secs = 5;secs > 0;secs--)
Printf (“%d seconds!\n”,secs);
Prinft (“we have ignition!\n”);
Return 0 ;
}
下面是它的輸出:
5seconds!
.
.
1seconds!
We have ignition!
2. 如果需要 你可以讓計數器加2,加10等等
For (n = 2;n < 60;n = n + 13)
3.你也可以用字符代替數字進行計數
For (ch = ‘a’;ch <= ‘z’;ch++)
4.你可以判斷迭代次數之外的條件。
5.你也可以讓數量幾何增加而不是算術增加
For (a = 100.0; a < 150.0; b = b * 1.1)
6.在第三個表達式中你可以使用所需的任何合法表達式
For (x = 1 ; y <= 75; y = (++x * 5)+50)
7.可以讓一個或多個表達式爲空(但是不能漏分號)
For (n = 3; ans <= 25;)
For (;;) 這個表達式中間的控制表達式爲空會被認爲是真
8.第一個表達式不必初始化一個值
9.循環中的動作可以改變循環表達式的參數
For (n = 1; n <100; n = n + delta)
更多的賦值運算符:+=,-=,*=,/=,%=
a +=等於a = a + 1;其它幾個一樣的結合,這些運算符同賦值符一樣低的優先級。
逗號運算符
逗號運算符擴展了for循環的靈活性因爲它使for循環中使用多個初始化或更新表達式
//6-13.c 使用逗號運算符計算郵資費率
#include <stdio.h>
int main (void)
{
const int FIRST_OZ = 37;
const int NEXT_OZ = 23;
int ounces ,cost;
printf ("ounces cost \n");
for (ounces = 1,cost = FIRST_OZ;ounces <= 16;ounces++,cost += NEXT_OZ)
printf ("%5d,$%4.2f\n",ounces,cost /100.0);
return 0 ;
}
第一個逗號表達式中對兩個變量進行了初始化,第二次出現使兩個變量都增加。
逗號運算符的兩個屬性:首先它保證被它分開的表達式按從左到右的次序進行計算,(也就是說逗號是個順序點,逗號左邊產生的所有副作用都在程序運行到逗號右邊之前生效)。其次整個逗號表達式的值是右邊成員的值。逗號也可以用作分隔符如printf()函數中的逗號.