Object-Oriented Programming with Java, part I – Exercise 63

This program uses the method sum to add together all the numbers in the array.

My Code

import java.util.ArrayList;

public class SumOfNumbers {
    public static int sum(ArrayList<Integer> list) {
        // Write your code here
        int tot = 0;
        for (int num : list) {
            tot = tot + num;
    }
        return tot;
    }

    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(3);
        list.add(2);
        list.add(7);
        list.add(2);
        
        System.out.println("The sum: " + sum(list));

        list.add(10);
        
        System.out.println("The sum: " + sum(list));
    }

}

Model Code

import java.util.ArrayList;

 

public class SumOfNumbers {

    public static int sum(ArrayList<Integer> list) {

        // Write your code here

        int sum = 0;

        for (int number : list) {

            sum = sum + number;

        }

        return sum;

    }

 

    public static void main(String[] args) {

        ArrayList<Integer> list = new ArrayList<Integer>();

        list.add(3);

        list.add(2);

        list.add(7);

        list.add(2);

        

        System.out.println("The sum: " + sum(list));

 

        list.add(10);

        

        System.out.println("The sum: " + sum(list));

    }

 

}

Comments

Not perfect but not bad. Basically the same thing as the model code with worse variable naming.

Leave a comment