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
```

Hints:

`public class `**SumAndAverage** { // saved as "SumAndAverage.java"
public static void main (String[] args) {
int sum = 0; // store the accumulated sum, init to 0
double average; // average in double
int lowerbound = 1; // the lower bound to sum
int upperbound = 100; // the upper bound to sum
for (int number = lowerbound; number <= upperbound; ++number) { // for loop
sum += number; // same as "sum = sum + number"
}
// Compute average in double. Beware that int/int produces int.
......
// Print sum and average.
......
}
}

TRY:

- Modify the program to use a "while-do" loop instead of "for" loop.
`int number = lowerbound; int sum = 0; while (number <= upperbound) { sum += number; ++number; }`

- Modify the program to use a "do-while" loop.
`int number = lowerbound; int sum = 0; do { sum += number; ++number; } while (number <= upperbound);`

- 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.`int count = 0; // count the number within the range, init to 0 for (...; ...; ...) { ...... ++count; }`

- 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.

Comment your answers :)

## 0 comments:

## Post a Comment