In: Computer Science
- Write a method sum that expects a List<Integer> as a parameter. The method returns an int representing the sum of the integers in the list.
- Write an index-based loop that prints the contents of a list.
Java Program:
import java.util.*;
//Class that holds list of integers
public class ListIntegers
{
//Main method
public static void main(String[] args)
{
//List of integers
List<Integer> integers = new
ArrayList<Integer>();
//Adding element in the list
integers.add(23);
integers.add(6);
integers.add(18);
integers.add(4);
integers.add(14);
System.out.println("\n\n Elements
present in the list: \n");
//Printing elements in the
list
print(integers);
//Calculating sum of elements in
the list
int sumOfIntegers =
sum(integers);
//Printing sum
System.out.println("\n\n Sum of
elements in the list: " + sumOfIntegers + " \n");
}
//Method that prints the elements in the list using
index-based loop
public static void print(List<Integer>
integers)
{
//Iterating over list
for(int i=0; i<integers.size();
i++)
{
//Printing
element
System.out.print( " \t " + integers.get(i) );
}
}
//Method that finds the sum of elements in the
list
public static int sum(List<Integer>
integers)
{
int sum = 0;
//Iterating over list
for(int i=0; i<integers.size();
i++)
{
//Accumulating
sum
sum +=
integers.get(i);
}
//Return the sum of elements in the
list
return sum;
}
}
------------------------------------------------------------------------------------------------------------------------------------------------------------------
Sample Output: