1. Write a piece of code that, given an array ar of integers, computes the sum of all positive elements of this array.
Solution:
int sum = 0;
for (int i = 0; i < ar.length; i++)
{if (ar[i] > 0) sum += ar[i];}
2. To check the correctness of the code you wrote in Problem 1,
write a piece of code that defines a new array ar
consisting of 2 elements of type integer and assigns, to elements of this
array, values 5 and -3. Trace step-by-step
how the piece of code you wrote
in Problem 1 will compute the sum of all positive elements of this array (the
answer should be 5).
Solution:
int[] ar = {5, -3};
Tracing:
The fact that we have defined an array ar with 2 elements means, in
effect, that we have defined two variables ar[0] and ar[1]:
----
| \|
---\
ar \
\|
- -------
| 5 | ar[0]
-------
| -3 | ar[1]
-------
Then, we define a new variable sum and assigning to it a value 0:
-------
| 0 |
-------
sum
Next, we get to the for-loop. First, we define a new integer variable
i and assign to it the value 0:
------- -------
| 0 | | 0 |
------- -------
sum i
We check the condition: the length of our array ar is 2, so i is smaller
than this length. Thus, the condition i < ar.length is satisfied, and
we implement the operation in the body of the loop. Since i = 0,
we check the condition ar[0] > 0, i.e., 5 > 0. This
condition is satisfied, so we replace the previous value of sum
with a new value 5:
------- -------
| 5 | | 0 |
------- -------
sum i
Then, we go to the update statement i++; this statement adds 1 to i, so
we get:
------- -------
| 5 | | 1 |
------- -------
sum i
The condition i < ar.length is still satisfied, so we continue looping.
Inside the loop, the condition ar[i] > 0, i.e., -3 > 0, is false, so
we do not do anything. Then, we go to the update statement i++; this
statement adds 1 to i, so we get:
------- -------
| 5 | | 2 |
------- -------
sum i
The condition i < ar.length is no longer satisfied, so we stop.