Find sum of elements of Linked List using Iterator

By | September 10, 2017

Sum of elements of Linked List using Iterator :

In this program, we are inserting elements in a Linked List. And, then traversing the list using an iterator, the goal is to find sum of all the elements of the list.

 

package AddusingIterator;

import java.util.Iterator;
import java.util.LinkedList;

public class program1 {
    public static void main(String[] args) {

        LinkedList<Float> num = new LinkedList<>();
        num.add(4.3F);
        num.add(2.2F);
        num.add(3.5F);
        num.add(5.0F);

        System.out.println(num);
        num.remove(3);  // Removing the Element From Index 3
        System.out.println(num); // Printing

        float sum = 0;
        Iterator<Float> iterator = num.iterator();
        while (iterator.hasNext()) {
            float n = iterator.next();
            sum += n;

        }
        System.out.println("Sum Of Numbers:" + sum);
    }
}

Output

 [4.3, 2.2, 3.5, 5.0]
 [4.3, 2.2, 3.5]
 Sum Of Numbers:10.0