Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

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)



Last Updated : 08 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads