How to compute the sum of numbers in a list using While-Loop in Java

The task is to use a while loop to calculate the sum of the numbers in the list. The List interface provides a way to store ordered collections. It is an ordered collection of objects in which repeated values ??can be stored. Since List retains the order of insertion, it allows positional access and insertion of elements.

Approach

  • Make a list.
  • Create two int variables one to store the number of arrays and the second to help us run the while loop.
  • Add multiple items to the list.
  • Run a while loop when the count variable is less than the list size.
  • Use the get() method to remove items from the list one by one and add items with a variable number.
  • Increase the variable number.

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 list = new ArrayList();
		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);
	}
}

Output

The sum of list is: 15

 

Submit Your Programming Assignment Details