Array Algorithms Sum Over All Elements – Intro to Java Programming

In this section, we’ll be talking about some common algorithms. I’ll explain to you the problem that we want to solve. I’ll explain to you the general algorithm and then I’ll leave it to you to implement it in Java and then we’ll talk together about the implementation. Let’s start with the algorithm to compute the sum of values in an ArrayList. Suppose we have a bunch of pictures that we want to arrange horizontally, the total width of all of them depends on the sum of the widths of all of the individual ones. To compute the sum, we’ll of course need a variable to hold it. And I’ll just write it in a pseudo-code here. Now for each element in the array, add to the sum to measure of that element. And I’m writing it in this generic form so that you can reuse the algorithm for other situations. In our case, the element is a picture in the ArrayList of pictures. And the measure is the width, and here we’re summing up the various widths. But in other situations you may be, if wanting to compute some other things, maybe the prices of some articles. So that’s the general algorithm, now your job will be to complete code for the specific case of summing the width of pictures. So here I’ve have set up the ArrayList of pictures for you. Here is a statement to print the result and your job will be to put in the Java code for the algorithm that I’ve just described. Have a go at it and then we’ll compare notes.

Leave a Reply

Your email address will not be published. Required fields are marked *