Home

Simple Array Sum

For our next challenge, we’ll be finding the sum of a list of numbers.

We’re given two lines of inputs, the first line tells us how many numbers there are, and the next line has that many numbers. Our goal is to sum the numbers in the second line.

Sample input:

4
3 2 6 4

Sample output:

15 // 3 + 2 + 6 + 4 = 15

First, let’s set up our code to read from the standard input.

import java.util.*; //so we can use our Scanner

public class Solution {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        //more code
    }
}

In the //more code section, we can read the first integer, which gives us the number of items to sum up.

int n = in.nextInt();

Let’s also have another variable called sum to keep track of our total sum as we read in the next n integers.

int sum = 0;

To add the numbers together, let’s use a for loop. For an explanation on what a for loop is, check the above video at around the 1:57 mark.

The final code looks something like this:

import java.util.*;

public class Solution {
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int sum = 0; 

        for(int i = 0; i < n; i++){
            sum += in.nextInt();
        }

        System.out.println(sum);
    }
}

sum += in.nextInt() means to store the result of the addition sum + in.nextInt() back into sum.



Questions? Have a neat solution? Comment below!