Skip to content
Related Articles

Related Articles

Improve Article

Java Program to Compute the Sum of Numbers in a List Using For-Loop

  • Last Updated : 22 Dec, 2020
Geek Week

Given a list of numbers, write a Java program to find the sum of all the elements in the List using for loop. For performing the given task, complete List traversal is necessary which makes the Time Complexity of the complete program to O(n), where n is the length of the List.

Example:

Input : List = [1, 2, 3]
Output: Sum = 6

Input : List = [5, 1, 2, 3]
Output: Sum = 11

Approach 1:

  1. Create the sum variable of an integer data type.
  2. Initialize sum with 0.
  3. Start iterating the List using for-loop.
  4. During iteration add each element with the sum variable.
  5. After execution of the loop, print the sum.

Below is the implementation of the above approach:

Java




// Java Program to Compute the Sum of
// Numbers in a List Using For-Loop
import java.util.*;
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        List<Integer> list = new ArrayList<>();
        list.add(5);
        list.add(6);
        list.add(7);
        list.add(10);
        list.add(9);
        int sum = 0;
        for (int i = 0; i < list.size(); i++)
            sum += list.get(i);
  
        System.out.println("sum-> " + sum);
    }
}
Output



sum-> 37

Time Complexity: O(n)

Approach 2:

  1. Create the sum variable of an integer data type.
  2. Initialize sum with 0.
  3. Start iterating the List using enhanced for-loop.
  4. During iteration add each element with the sum variable.
  5. After execution of the loop, print the sum.

Below is the implementation of the above approach:

Java




// Java Program to Compute the Sum of
// Numbers in a List Using Enhanced For-Loop
import java.util.*;
import java.io.*;
  
class GFG {
    public static void main(String[] args)
    {
        List<Integer> list = new ArrayList<>();
        list.add(5);
        list.add(6);
        list.add(7);
        list.add(10);
        list.add(9);
        int sum = 0;
        for (Integer i : list)
            sum += i;
  
        System.out.println("sum-> " + sum);
    }
}
Output
sum-> 37

Time Complexity: O(n)

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. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up