Java Program to Compute the Sum of Numbers in a List Using While-Loop
The task is to compute the sum of numbers in a list using while loop. The List interface provides a way to store the ordered collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements.
Approach
- Create a list.
- Create two int variable one for storing the sum of the array and the second is to help us to execute the while loop.
- Add some elements in the list.
- Execute the while loop until the count variable in less than the size of the list.
- Get elements of list one by one using get() method and add the element with sum variable.
- Increment the count variable.
Code
Java
import java.util.*;
public class GFG {
public static void main(String args[])
{
List<Integer> list = new ArrayList<Integer>();
int sum = 0 ;
int count = 0 ;
list.add( 1 );
list.add( 2 );
list.add( 3 );
list.add( 4 );
list.add( 5 );
while (list.size() > count) {
sum += list.get(count);
count++;
}
System.out.println( " The sum of list is: " + sum);
}
}
|
Output
The sum of list is: 15
Time complexity: O(n) where n is size of list
Auxiliary space:O(n) since using a List to store numbers
Last Updated :
07 Oct, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...