Exercises 5.3
1. -2 squared = 4
-1 squared = 1
0 squared = 0
1 squared = 1
2 squared = 4
3 squared = 9
2. 1
1
2
2
1
3
3
2
1
4
4
3
2
1
5
5
4
3
2
1
3. 3
0
1
2
3
4
4. 111
121
122
131
132
133
211
221
222
231
232
233
311
321
322
331
332
333
5.
111
121
122
131
132
133
222
232
233
333
6. 000
112
228
18
7. 000
112
228
18
8. 5123###
31###
1***
9, 10, 11
(a) limit = 10
Pretest
loop Posttest
loop Test-in-the-middle
loop
|
|
number |
sum |
|
number |
sum |
|
number |
sum |
|
|
0 |
0 |
|
0 |
0 |
|
0 |
0 |
|
|
1 |
1 |
|
1 |
1 |
|
1 |
1 |
|
|
2 |
3 |
|
2 |
3 |
|
2 |
3 |
|
|
3 |
6 |
|
3 |
6 |
|
3 |
6 |
|
|
4 |
10 |
|
4 |
10 |
|
4 |
10 |
|
|
5 |
15 |
|
5 |
15 |
|
5 |
15 |
|
|
|
|
|
|
|
|
6 |
15 |
(b) limit = 1
Pretest
loop Posttest
loop Test-in-the-middle
loop
|
|
number |
sum |
|
number |
sum |
|
number |
sum |
|
|
0 |
0 |
|
0 |
0 |
|
0 |
0 |
|
|
1 |
1 |
|
1 |
1 |
|
1 |
1 |
|
|
2 |
3 |
|
2 |
3 |
|
2 |
3 |
|
|
|
|
|
|
|
|
3 |
3 |
(c) limit = 0
Pretest
loop Posttest
loop Test-in-the-middle
loop
|
|
number |
sum |
|
number |
sum |
|
number |
sum |
|
|
0 |
0 |
|
0 |
0 |
|
0 |
0 |
|
|
1 |
1 |
|
1 |
1 |
|
1 |
1 |
|
|
|
|
|
|
|
|
2 |
1 |
12.
/* sumToN(n) computes the
sum 1 + 2 + … + n.
*
* Receive: n, an integer value
* Return: the
value of the sum 1 + 2 + … + n
*/
public static int sumToN(int
n)
{
int sum = 0;
for (int i = 1; i <= n; i++)
sum += i;
return sum;
}
13.
/* sumMToN(m, n) computes
the sum of the integers from m to n.
*
* Receive: m and n, two integers
* Return: the
value of the sum of m to n
*/
public static int sumMToN (int m, int n)
{
if (m > n) return 0; // no integers between m and n
int sum = 0; //
compute sum = m + (m + 1) + ... + n
for (int i = m; i <= n; i++)
sum += i;
return sum;
}
14.
for (int n = 1; n <= 100; n++)
theScreen.println((n * n));
15.
for (int n = 50; n > 0; n--)
theScreen.println((n * n * n));
16.
for (int i = 1; i <= 49; i += 2)
theScreen.println(Math.sqrt((double)(i)));
17.
for (double x = -2.0; x <= 2.0; x += 0.1)
theScreen.println("(" + x + ","
+ (x * x * x - 3 * x + 1) + ")");
18.
for (;;)
{
theScreen.println(x);
x -= 0.5;
if (x <= 0)
break;
}
19.
for (;;)
{
a =
theKeyboard.readInt();
b =
theKeyboard.readInt();
c =
theKeyboard.readInt();
theScreen.println((a + b + c));
if ( (a < 0)
|| (b < 0) || (c < 0) ) break;
}
20.
i = 1;
for (;;)
{
theScreen.println((i * i));
if ( i * i -
(i-1)*(i-1) > 50) break;
i++;
}