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:
The sum is 5050
The average is 50.5
For Hints Visti Hints on Exercise SumAndAverage (Loop)
TRY:
- Modify the program to use a "while-do" loop instead of "for" loop.
- Modify the program to use a "do-while" loop.
- What is the difference between "for" and "while-do" loops? What is the difference between "while-do" and "do-while" loops?
- 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.
- 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.)
- Modify the program to sum those numbers from 1 to 100 that is divisible by 7, and compute the average.
- 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.
int number = lowerbound;
int sum = 0;
while (number <= upperbound) {
sum += number;
++number;
}
int number = lowerbound;
int sum = 0;
do {
sum += number;
++number;
} while (number <= upperbound);
int count = 0; // count the number within the range, init to 0 for (...; ...; ...) { ...... ++count; }
No Comment to " Exercise SumAndAverage (Loop) "