Thursday, October 23, 2025
HomeLanguagesJavaJava Program to Compute the Sum of Numbers in a List Using...

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

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

Auxiliary Space: O(1)
 

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)

Auxiliary Space: O(1)

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS