首页 > 其他 > 详细

<C Primer Plus>5 Looping while

时间:2017-04-02 12:35:56      阅读:205      评论:0      收藏:0      [点我收藏+]
 1 #include <stdio.h>
 2 int main(void){
 3     long num;
 4     long sum = 0L;
 5     int status;
 6 
 7     printf("Please input an integer to be summed.");
 8     printf("(q to quit): ");
 9     status = scanf("%ld", &num);
10     while (status == 1){
11         sum = sum + num;
12         printf("Pleast enter next integer (q to quit):");
13         status = scanf("%ld", &num);
14     }
15     printf("Those integers sum to %ld.\n", sum);
16 
17     return 0;
18 }
The pseudocode:

  initialize sum to 0
  prompt user
  read input
  while the input is an integer
      add the input to sum
      promt user
      then read the next input

  after input completes ,print sum

 

 1 #include <stdio.h>
 2 int main(void){
 3     long num;
 4     long sum = 0L;
 5 
 6     printf("Please input an integer to be summed.");
 7     printf("(q to quit): ");
 8     while (1 == scanf("%ld", &num) ){
 9         sum += num;
10         printf("Pleast enter next integer (q to quit):");
11     }
12     printf("Those integers sum to %ld.\n", sum);
13 
14     return 0;
15 }

The pseudocode :
while getting and testing the value succeeds
  process the value

 REMEBER:

A for loop is appropriate when the loop involves initializing and updating a variable, and a while loop is better when the conditions are othervise.

for example:

while (scanf("%ld",&num) == 1)

for(count = 1;count <= 100; count++)

<C Primer Plus>5 Looping while

原文:http://www.cnblogs.com/michael2016/p/6658651.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!