Codementor Events

Java Algorithm Code Challenge: The Sum of N Integers

Published May 31, 2017
Java Algorithm Code Challenge: The Sum of N Integers

In the past, I solved the following input/output algorithm problem below. Can you solve it like I did or do even better ? Give it a shot. And if you'd like me to create algorithms for you to solve using different java structures or angularJs derivatives (which are commonly used in the workplace), feel free to reach out to me. This is just a basic challenge to warm you up. Enjoy!

Given

...an array of integers of size N, you need to print the addition of all elements in the array

and the following code:


import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        
        //enter your code here and end with a system.out in order to print to the console
    }
}
 

Expected Result

...should show a single value equal to the sum of the elements in the array.

Sample Input

5
1000000001 1000000002 1000000003 1000000004 1000000005

Sample Output

5000000015

So assuming you pass in the 2 lines of sample input (one line at a time), you should receive the sample output if you've done things properly.

Good luck !

The Answer is below

Here is my version of the answer:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
     
        
        Scanner in = new Scanner(System.in);
        int t;
        long a= 0;
        t =  in.nextInt();
        for (int i = 0;i < t;i++){
            
            a +=  in.nextInt();    
            
        }
        System.out.println(a);
    }
}
Discover and read more posts from Ugo A
get started
post commentsBe the first to share your opinion
Show more replies