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 = 6Input :List = [5, 1, 2, 3]Output:Sum = 11

**Approach 1:**

- Create the sum variable of an integer data type.
- Initialize sum with 0.
- Start iterating the List using for-loop.
- During iteration add each element with the sum variable.
- 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); ` ` ` `} ` `}` |

*chevron_right*

*filter_none*

**Output**

sum-> 37

**Time Complexity:** O(n)

**Approach 2:**

- Create the sum variable of an integer data type.
- Initialize sum with 0.
- Start iterating the List using enhanced for-loop.
- During iteration add each element with the sum variable.
- 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); ` ` ` `} ` `}` |

*chevron_right*

*filter_none*

**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.