Sum program in java

Sum of Array in Java

Sum of Array in Java | Array Programs in Java – 5 | In the previous Java program, we have seen the different ways to print an array in Java. In this post, we will write a program to find the sum of an array in Java | Sum of Array Elements in Java | Array Addition in Java |

Program Description:- Write a Java program to find the sum of array elements in Java.

Examples of the sum of array elements. Assume we have a given array,

array [] =
Sum of array elements = 10+20+30 = 60

Similarly,
array [] =
Sum of array elements = 50+60-20+55-90 = 55

Читайте также:  Nginx php fpm php in html

Procedure to find the sum of array elements,
1) Take one array.
2) Declare one sum variable and initialize it with 0.
3) Using a loop, Iterate through the elements of the given array.
4) Add element to the sum variable and assign result value back to the sum variable. (i.e. sum = sum + arr [i] )
5) When all elements of the array are added to the sum variable then display the result.

Now, let us see the array addition in Java and display the result. First, we will develop a program by hardcoding the values, and again we develop another Java program to take array input from the end-user and then find the sum of array elements. To iterate through the array elements, you can use the length property of the array.

Java program to calculate the sum of array elements

public class ArraySum < public static void main(String[] args) < // declare array and // initialize it with values int array[] = ; // initialize sum variable with 0 int sum = 0; // add array elements for (int i=0; i // display the result System.out.println("Sum of array elements= " + sum); > >

Sum of array elements= 150

In the previous program we have hardcoded the values, now let us develop another Java program to solve the same problem but take input values from the end-user.

Java Program To Calculate The Sum Of Array Elements By Taking Input Values

import java.util.Scanner; public class ArraySum < public static void main(String[] args) < // create Scanner class object Scanner scan = new Scanner(System.in); // take size of array System.out.print("Enter number of elements: "); int number = scan.nextInt(); // declare array with given size int array[] = new int[number]; // take input for array elements System.out.println("Enter array elements: "); for (int i=0; i// initialize sum variable with 0 int sum = 0; // add array elements to sum for (int i=0; i // display the result System.out.println("Sum of array elements= " + sum); > >

Output for the different test-cases:-

Enter number of elements: 5
Enter array elements:
10 20 30 40 50
Sum of array elements= 150

Enter number of elements: 3
Enter array elements:
150 -100 120
Sum of array elements= 170

In the above program, instead of the array.length you can also use numbers variable because both hold the same value. For simplicity, we are using the Scanner class to take input you can also use BufferReader class. To iterate through the loop we can also use a for-each loop rather than a simple for loop.

// for-each loop for (int i : list) < // add array elements to sum sum += i; >

Limitation of the above program:- the number of array elements must be known at the program development time. If the number of array elements is dynamic and can’t be predicted before then we must take the help of collection classes because they can grow dynamically.

import java.util.List; import java.util.ArrayList; public class ArraySum < public static void main(String[] args) < // declare list Listlist = new ArrayList(); // add elements to the list // you can take input from the end-user list.add(10); list.add(20); list.add(30); list.add(40); list.add(50); // initialize sum variable with 0 int sum = 0; // add array elements to sum for (int i : list) < sum += i; >// display the result System.out.println("Sum = " + sum); > >

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

Sum program in java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

How to find sum of array elements in java

Sum of array elements means the sum of all the elements(or digits) in the array. Array elements can be integers( int ) or decimal numbers( float or double ).
There are different methods to calculate sum of elements in an array in java and this post discusses them all.

Method 1 : Using for loop
This is a traditional and most commonly used approach where the array is iterated using a for loop.
In each iteration, the current array element is added to a variable which holds the sum of array elements.
This variable is initialized to 0 before the start of loop. Example,

public class ArraySumCalculator { public static void main(String[] args) { int[] array = { 1, 34, 67, 23, -2, 18 }; // variable to hold sum of array elements int sum = 0; // iterate using a for loop for (int loopCounter = 0; loopCounter &lt; array.length; loopCounter++) { // get current array element int element = array[loopCounter]; // add element to sum sum += element; } System.out.println("Sum of array elements is: " + sum); } }

public class ArraySumCalculator < public static void main(String[] args) < int[] array = < 1, 34, 67, 23, -2, 18 >; // variable to hold sum of array elements int sum = 0; // iterate using a for loop for (int loopCounter = 0; loopCounter < array.length; loopCounter++) < // get current array element int element = array[loopCounter]; // add element to sum sum += element; >System.out.println(«Sum of array elements is: » + sum); > >

Sum of array elements is: 141

for loop in this program can also be replaced with a for-each loop as shown below.

Источник

How to Find the Sum of Two Numbers in Java

wikiHow is a “wiki,” similar to Wikipedia, which means that many of our articles are co-written by multiple authors. To create this article, volunteer authors worked to edit and improve it over time.

This article has been viewed 205,440 times.

Finding the sum of two numbers is simple, but it can get tedious if the numbers are big. Here is how you can create a Java program to find the sum of two numbers.

Image titled Find the Sum of Two Numbers in Java Step 1

Plan your program. Finding the sum of two numbers isn’t difficult, but it is always a good practice to plan your program before beginning to code. Understand that you’d need two inputs/ parameters from the user for this program: the two numbers.

Image titled Find the Sum of Two Numbers in Java Step 2

  • Create a separate variable to store the value of the sum. This can be of the type int.
  • The formula to find the sum is:

Image titled Find the Sum of Two Numbers in Java Step 3

Display the output. Once the program has calculated the sum, display it to the user. Use the System.out.print or System.out.println (to print on a new line) function, in Java, for this. [2] X Research source

Community Q&A

Can the volume of a cuboid, cylinder, and cone be calculated by a switch statement taking suitable variables and data types?

Yes. You may want to have the user specify what kind of shape before taking in any other input (such as dimensions).

Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow

Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow

Assume there are three integers (a, b, c): int a = 46; int b = 56; int c = a + b; System.out.println(c); Don’t forget the semicolons.

Thanks! We’re glad this was helpful.
Thank you for your feedback.
As a small thank you, we’d like to offer you a $30 gift card (valid at GoNift.com). Use it to try out great new products and services nationwide without paying full price—wine, food delivery, clothing and more. Enjoy! Claim Your Gift If wikiHow has helped you, please consider a small contribution to support us in helping more readers like you. We’re committed to providing the world with free how-to resources, and even $1 helps us in our mission. Support wikiHow

mScanner.nextInt(); sum = firstNumber + secondNumber; System.out.println("The sum of the two numbers you entered o">+ sum); > > 

You Might Also Like

Add Two Numbers in Visual Basic.NET

Add Two Numbers in Visual Basic

Add Binary Numbers

Sum the Integers from 1 to N

Set Java Home

How to Set JAVA_HOME for JDK & JRE: A Step-by-Step Guide

Check Your Java Version in the Windows Command Line

Use Easy Windows CMD Commands to Check Your Java Version

Do Division in Java

How to Do Division in Java (Integer and Floating Point)

Compile and Run Java Program by Notepad

How to Compile and Run Java Programs Using Notepad++

Источник

Get the Sum of an Array in Java

Get the Sum of an Array in Java

  1. Find the Sum of an Array by Using a for Loop in Java
  2. Find the Sum of an Array by Using the Stream Method in Java
  3. Find the Sum of an Array by Using the reduce Method in Java
  4. Find the Sum of an Array by Using the sum Method in Java
  5. Find the Sum of an Array by Using the IntStream Interface in Java
  6. Find the Sum of an Array by Using a Compact for Loop in Java

This tutorial introduces how to find the sum of an array in Java also lists some example codes to understand the topic.

An array is defined as a collection of similar types of elements in Java. In this article, we’ll find the sum of array elements by using some built-in methods and custom codes.

Performing this operation is very common during programming. Unfortunately, Java does not provide any specific method to get the sum of an array. So, we will use some tricks to solve this issue!

Find the Sum of an Array by Using a for Loop in Java

In this example, we used a loop to traverse each array element and get thir sum parallel. This method has a simple code that requires a single loop to get the sum. Here’s the example program:

public class SimpleTesting  public static void main(String[] args)   int arr[] = new int[] 12,34,45,21,33,4>;  int sum = 0;  for (int i = 0; i  arr.length; i++)   sum+=arr[i];  >  System.out.println("Array Sum = "+sum);   > > 

Find the Sum of an Array by Using the Stream Method in Java

In this example, we used the stream() method of the Arrays class and the parallel() method to get the sum of the array elements. We passed the lambda expression to the reduce() method that actually does the sum operation. See the example below:

import java.util.Arrays; public class SimpleTesting  public static void main(String[] args)   int arr[] = new int[] 12,34,45,21,33,4>;  int sum = Arrays.stream(arr).parallel().reduce(0,(a,b)-> a + b);  System.out.println("Array Sum = "+sum);   > > 

Find the Sum of an Array by Using the reduce Method in Java

In this example, we used the reduced() method directly with the stream of arrays and get the sum of the elements. Here’s how to do it:

import java.util.Arrays; public class SimpleTesting  public static void main(String[] args)   int arr[] = new int[] 12,34,45,21,33,4>;  int sum = Arrays.stream(arr).reduce(0,(a,b)-> a + b);  System.out.println("Array Sum = "+sum);   > > 

Find the Sum of an Array by Using the sum Method in Java

Java provides the sum() method in the Stream API to get a sum of stream sequences. Here, we passed an array to the stream and got its sum by using the sum() method. See the example below:

import java.util.Arrays; public class SimpleTesting  public static void main(String[] args)   int arr[] = new int[] 12,34,45,21,33,4>;  int sum = Arrays.stream(arr).sum();  System.out.println("Array Sum = "+sum);  > > 

Find the Sum of an Array by Using the IntStream Interface in Java

This method is another solution where you can use the Intsream interface to create a stream of array elements and utilize the sum() method to get the sum in a straightforward, single-line solution. Follow the sample code here:

import java.util.stream.IntStream; public class SimpleTesting  public static void main(String[] args)   int arr[] = new int[] 12,34,45,21,33,4>;  int sum = IntStream.of(arr).sum();  System.out.println("Array Sum = "+sum);  > > 

Find the Sum of an Array by Using a Compact for Loop in Java

In this example, we used a for loop to get the sum of array elements with an additional unique process. Here, rather than creating a loop body, we just bind up into the loop signature part. We can call it a compact loop solution. You can try it if you’re not afraid of a messy code block.

public class SimpleTesting  public static void main(String[] args)   int arr[] = new int[] 12,34,45,21,33,4>;  int sum,i;  for(sum= 0, i= arr.length - 1; 0  i; sum+= arr[i--]);  System.out.println("Array Sum = "+sum);  > > 

Related Article — Java Array

Источник

Оцените статью