循环结构,常用的有for循环和while循环。
for循环求1到100的和:
# include <stdio.h> int main(void) { int i; int sum = 0; for (i=1;i<=100;++i) //for循环控制sum = sum + i;语句,执行顺序:1. i=1; 2. i<=100; 3. sum = sum + i; 4. ++i;(++i标志着一次循环结 //束) 5. i<=100 sum = sum + i; printf("sum = %d\n", sum); return 0; }
运行结果:
求1到100的偶数和,步长为2,即i+=2
# include <stdio.h> int main(void) { int i; int sum = 0; for (i=1;i<100;i+=2) //步长为2 sum = sum + i; printf("sum = %d\n", sum); return 0; }
示例3:
# include <stdio.h> int main(void) { int i; int j = 0; int sum = 0; float ave; for (i=1;i<=100;i+=2) { sum = sum + i; j++; } ave = float(sum/j); printf("1到100的所有奇数和为:%d\n", sum); printf("奇数个数为:%d\n", j); printf("奇数的平均值为:%f\n", ave); sum = 0; //sum和j需要重新被赋值。 j = 0; for (i=2;i<=100;i+=2) { sum = sum + i; j++; } ave = float(sum/j); printf("1到100的所有偶数和为:%d\n", sum); printf("偶数个数为:%d\n", j); printf("偶数的平均值为:%f\n", ave); return 0; }
示例4:
/* 2012年12月16日22:21:08 目的:考察对流程顺序的理解。 */ # include <stdio.h> int main(void) { int i,j; for (i=0;i<3;++i) { printf("111!\n"); for (j=2;j<5;++j) { printf("222!\n"); printf("333!\n"); } printf("444!\n"); } return 0; } /* 输出结果是: 111! 222! 333! 222! 333! 222! 333! 444! 111! 222! 333! 222! 333! 222! 333! 444! 111! 222! 333! 222! 333! 222! 333! 444! Press any key to continue */
for与while
# include <stdio.h> int main(void) { int i; int sum = 0; /* for (i=1;i<=100;i++) sum = sum + i; printf("sum = %d\n", sum); */ i = 1; while (i <= 100) { sum = sum + i; i++; } printf("sum = %d\n", sum); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/lfhappypain/article/details/47170489