本文参考C Primer Plus进行学习
出口循环条件,即在循环的每次迭代之后检查测试条件,这保证了至少执行循环体中的内容一次。
- #include
- int main()
- {
- const int secret_code=13;
- int code_entered;
-
- do
- {
- printf("To enter the triskaidekaphobia therapy club,\n");
- printf("Please enter the secret number:");
- scanf("%d",&code_entered);
- }
- while(code_entered!=secret_code);
- printf("Congratulations!You are cured!\n");
- return 0;
- }

while循环也可以完成,不过代码稍微长一点。
- #include
- int main()
- {
- const int secret_code=13;
- int code_entered;
-
- printf("To enter the triskaidekaphobia therapy club,\n");
- printf("Please enter the secret number:");
- scanf("%d",&code_entered);
-
- while(code_entered!=secret_code)
- {
- printf("To enter the triskaidekaphobia therapy club,\n");
- printf("Please enter the secret number:");
- scanf("%d",&code_entered);
- printf("Congratulations!You are cured!\n");
- }
-
- return 0;
- }
下面是do while的通用形式
do
statement
while(expression);
statement可以是一条简单语句或复合语句。注意,do while 循环以分号结尾。
do while 循环在执行完循环体后才执行测试条件,所以至少执行循环体一次;而for循环和while循环先执行测试条件再执行循环体。
通常,入口条件循环用的比较多,其一,一般原则是在执行之前测试比较好。其二,测试放在循环的开头,可读性比较高。在许多应用中,要求一开始不符合条件就直接跳出循环。
一般而言,当循环涉及初始化和更新变量时,用for循环比较合适,其他情况下while循环比较好。
while(scanf("%ld",&sum)==1)
对于涉及索引基数的循环,用for循环更合适。
for(count=1;count<=100;count++)
- #include<stdio.h>
- #define ROWS 6
- #define CHARS 10
- int main(void)
- {
- int row;
- char ch;
-
- for(row=0;row<6;row++)
- {
- for(ch='A';ch<('A'+CHARS);ch++)
- printf("%c",ch);
- printf("\n");
- }
- return 0;
- }

- #include<stdio.h>
- int main(void)
- {
- const int ROWS=6;
- const int CHARS=6;
- int row;
- char ch;
-
- for(row=0;row<6;row++)
- {
- for(ch='A'+row;ch<('A'+CHARS);ch++)
- printf("%c",ch);
- printf("\n");
- }
- return 0;
- }

float debts[20];
声明debts是一个内含20个元素的数组,每个元素都可以储存float类型的值。数组的第一个元素是debts[0],最后一个是debts[19]。可以给每个元素赋float类型的值。
例如:debts[10]=32.54;
scanf("%f",&debts[10]); //把一个数值读入数组的第11个元素


- #include<stdio.h>
- #define SIZE 10
- #define PAR 72
- int main(void)
- {
- int index,score[SIZE];
- int sum=0;
- float average;
-
- printf("Enter %d golf scores:\n",SIZE);
- for(index=0;index<SIZE;index++)
- scanf("%d",&score[index]);
- printf("The scores read in are as follows:\n");
- for(index=0;index<SIZE;index++)
- printf("%5d",score[index]);
- printf("\n");
- for(index=0;index<SIZE;index++)
- sum+=score[index];
- average=(float) sum/SIZE;
- printf("Sum of scores =%d,average=%.2f\n",sum,average);
- printf("That is a handicap of %.0f.\n",average-PAR);
- return 0;
- }

明天继续吧!加油!