Skip to content
Related Articles

Related Articles

Java Program to Compute the Sum of Numbers in a List Using While-Loop
  • Last Updated : 28 Dec, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to Compute the Sum of Numbers in a List
// Using While-Loop
  
import java.util.*;
  
public class GFG {
    public static void main(String args[])
    {
  
        // create a list
        List<Integer> list = new ArrayList<Integer>();
        int sum = 0;
        int count = 0;
  
        // add some elements in list
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
  
        // execute while loop until the count less then the
        // list size.
        while (list.size() > count) {
  
            // add list values with sum variable one-by-one.
            sum += list.get(count);
  
            // increment in count variable
            count++;
        }
  
        // print sum variable
        System.out.println(" The sum of list is: " + sum);
    }
}

chevron_right


Output

 The sum of list is: 15

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :