• <C Primer Plus>5 Looping while


     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.
    ", 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.
    ", 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++)

  • 相关阅读:
    Java学习笔记day01
    对有序数组进行二分查找(折半查找)
    对数组进行冒泡排序
    LeetCode #344. Reverse String
    LeetCode #292. Nim Game
    LeetCode #258. Add Digits
    Android DiskLruCache完全解析,硬盘缓存的最佳方案
    Android源码解析——LruCache
    Messenger与AIDL的异同
    Android应用层View绘制流程与源码分析
  • 原文地址:https://www.cnblogs.com/michael2016/p/6658651.html
Copyright © 2020-2023  润新知