Wednesday, May 11, 2022

How to calculate sum of all numbers in a given array in Java [Example]

Hello guys, if you are thinking about how to calculate the sum of all numbers in a given integer array then you have come to the right place. Earlier, I have shared 75 programming questions from the interview and in today's coding problem, you will learn how to write a program to calculate the sum of array elements in Java. As part of this coding problem, you need to write a method that will accept an integer array and it should return the total sum of all the elements. The array could contain both positive and negative numbers but only decimal numbers are allowed. 

The array can also be null or empty so make sure your solution handles those as well. In the case of a null or empty array, your program can throw IllegalArgumentException. The empty array means an array whose length is zero or there is no element inside it. 

Well, that's enough for the requirement of this simple coding problem. The solution is really simple, just loop through the array and keep adding elements into sum until you process all the elements.

There is no tricky thing in this program. It is particularly designed to make a new programmer familiar with working with array and loop like how to loop over an array, how to retrieve elements from an array using the index, and how to write a function to return an integer.

The solution to the problem is very simple, first, you need to write code to take the input from the user. Since you cannot take an array as input from the command line, you need to take each element in store in the array you are going to pass to the sum() method. 

This method takes an array and returns the sum of its elements. For the sake of simplicity, it is not throwing IllegalArgumentException but you can code it by yourself. Just do the check before calculating the sum in a for loop.

By the way, if you are new to Java and not familiar with basic concepts like an array, linked list, or how to get input from users then I highly recommend you to join a comprehensive Java course like The Complete Java Masterclass by Tim Buchalaka on Udemy. This 80+ hour course is the most comprehensive and up-to-date course to learn Java online. 




Java Program to calculate the sum of array elements in Java

Here is our complete Java program to calculate the sum of all elements of the given array. It uses Scanner to take user input from the command prompt and enhanced for loop of Java 5 to loop over the array. In each step we add the current element into the sum variable and once the iteration finishes we return this value to the caller. This the sum of all elements of the given array.

By the way, if you are preparing for coding interviews and want to refresh your data structure and algorithm knowledge in Java then I also suggest you join Data Structures for Coding Interviews in Java, an interactive course by Educative to master Data Structure in Java. 

How to calculate Sum of Numbers using Array in Java [Example]

The great thing about Educative is that it allows you to run code directly in your browser, which makes learning faster as you won't need to download any software or set up your own development environment. 

And, If you seriously want to develop your coding sense and understand data structure and algorithms, and love reading books then you can also solve advanced problems given in Algorithm Design Manual by Steven Skiena, after solving these basic problems. 

import java.util.Scanner;

/*
 * Java Program to calculate sum of array elements
 * input = [1, 2, 3, 4, 5, 6]
 * output = 21
 */

public class ArraySumProblem {

  public static void main(String[] args) {

  System.out.println("Welcome to Java program to calculate 
                          sum of elements in an array");
  System.out.println("Please enter the length of array?");

  Scanner scnr = new Scanner(System.in);
  int length = scnr.nextInt();
  int[] input = new int[length];

  System.out.println("Please enter elements of array");
  for (int i = 0; i < length; i++) {
  input[i] = scnr.nextInt();
  }

  int total = sumOfElements(input);
  System.out.println("Sum of all elements of array is " + total);
  scnr.close();
  }

  /**
  * A Java method to run sum of all elements of given array
  * 
  * @param array
  * @return sum of all elements of int array
  */
  public static int sumOfElements(int[] array) {
  int sum = 0;
  for (int i : array) {
  sum = sum + i;
  }
  return sum;
  }
}

Output
Welcome to Java program to calculate sum of elements in an array
Please enter the length of an array?
4
Please enter elements of array
1
2
2
3
Sum of all elements of array is 8

Welcome to Java program to calculate sum of elements in an array
Please enter the length of an array?
6
Please enter elements of array
202
34
56
6
5
46
Sum of all elements of array is 349

That's all about how to calculate the sum of array elements in Java. It's one of the simplest Java programming exercises but very good to build command over programming constructs. At the beginner level, these small program helps you to gain confidence and learn fast. 


Other Java Programming exercises for Beginners
  • How to remove duplicate elements from the array in Java? (solution)
  • How to reverse an array in place in Java? (solution)
  • How to check if a year is a leap year in Java? (solution)
  • How to print Fibonacci series in Java (solution)
  • How to find all permutations of a given String in Java? (solution)
  • How to reverse a String in place in Java? (solution)
  • How to find if the given Integer is Palindrome in Java? (solution)
  • How to check if a String contains duplicate characters in Java? (solution)
  • How to find the highest occurring word from a given file in Java? (solution)
  • How to count vowels and consonants in a given String in Java? (solution)
  • How to implement Linear Search in Java? (solution)
  • How to check if the given String is palindrome or not in Java? (solution)
  • How to remove duplicate characters from String in Java? (solution)
  • How to implement binary search in Java? (solution)
  • How to check if the given number is prime in Java (solution)
  • How to check if two given Strings are Anagram in Java? (solution)
  • How to reverse words in a given String in Java? (solution)
  • How to calculate the Area of Triangle in Java? (program)

Thanks for reading this article so far. If you find this Programming exercise handy then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note. 

P. S. - If you are new to the Java world and want to learn Java Programming forms scratch and you are also looking for a free online course to start with then you can also check out this Java Tutorial for Complete Beginners (FREE) course from Udemy. This course is completely free and more than 1.2 million people have joined this course to learn Java online. 

2 comments:

  1. i want to declare two single dimension array or size in 4 (both) eg. int []a={1,2,3.4}
    second is int []b={5,6,7,8}; and now i want the sum of array element in other array call ed int [] c= new int[4];in this array i want like {6,8,10,12}
    can u show me the way to do it ?

    ReplyDelete
  2. Can we java all toughest interview questions for praactice

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.