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:
- 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); } } |
sum-> 37
Time Complexity : O(n).
Auxiliary Space: O(1)
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); } } |
sum-> 37
Time Complexity: O(n)
Auxiliary Space: O(1)