Exercise SumAndAverage (Loop)

Compiled By Unknown - No Comments
Write a program called SumAndAverage to produce the sum of 1, 2, 3, ..., to an upperbound (e.g., 100). Also compute and display the average. The output shall look like:
The sum is 5050
The average is 50.5
For Hints Visti Hints on Exercise SumAndAverage (Loop)


TRY:
  1. Modify the program to use a "while-do" loop instead of "for" loop.
  2. int number = lowerbound;
    int sum = 0;
    while (number <= upperbound) {
       sum += number;
       ++number;
    }
    
  3. Modify the program to use a "do-while" loop.
  4. int number = lowerbound;
    int sum = 0;
    do {
       sum += number;
       ++number;
    } while (number <= upperbound);
    
  5. What is the difference between "for" and "while-do" loops? What is the difference between "while-do" and "do-while" loops?
  6. Modify the program to sum from 111 to 8899, and compute the average. Introduce an int variable called count to count the numbers in the specified range.
  7. int count = 0;   // count the number within the range, init to 0
    for (...; ...; ...) {
       ......
       ++count;
    }
    
  8. Modify the program to sum only the odd numbers from 1 to 100, and compute the average. (Hint: n is an odd number if n % 2 is not 0.)
  9. Modify the program to sum those numbers from 1 to 100 that is divisible by 7, and compute the average.
  10. Modify the program to find the "sum of the squares" of all the numbers from 1 to 100, i.e. 1*1 + 2*2 + 3*3 + ... + 100*100.

Tags:

No Comment to " Exercise SumAndAverage (Loop) "