In this tutorial you will learn about the Java Program to Add the elements of an Array and its application with practical example.
Java Program to Add the elements of an Array
In this tutorial, we will learn to create a Java program that will add the elements of an Array using Java programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following Java programming topics:
- Operators in Java Programming.
- Basic Input and Output function in Java Programming.
- Basic Java programming.
- For loop in Java programming.
- Arithmetic operations in Java Programming.
What is An array?
The array is a collection of similar data types. An array can store multiple values with different indexes in memory by using a single variable. The array can be both single and multidimensional.
Program description to find add the Elements of an Array.
In this program, we will first take the input array size and the elements from the user. Then we will add all the elements of the array using a for-loop. At last, we will print all the elements of the array to the user.
With the help of this program, we can add the Elements of an Array.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.Arrays;//Importing the package for array import java.util.Scanner;//Importing the package for taking input public class AddElmOfArray { //Body of the main function of the program public static void main(String args[]){ //Taking the size of the array From the user System.out.println("Enter the required size of the array :: "); Scanner s = new Scanner(System.in); int size = s.nextInt(); int arry[] = new int [size]; int sum = 0; int i; //Taking the elements of the arry from the user. System.out.println("Enter the elements of the array one by one "); //Using the for loop to take the input elements for( i=0; i<size; i++){ arry[i] = s.nextInt(); sum = sum + arry[i]; } //Printing the elements of the array System.out.println("Elements of the array are: "+Arrays.toString(arry)); //Printing the sun of the elements of the array. System.out.println("Sum of the elements of the array ::"+sum); } } |
Output:-
In the above program, we have first initialized the required variable.
- arry[] = it will hold the integer value of the input elements.
- i = it will hold the integer value.
- Size = it will hold the integer value of the input.
Input size of the array from the user.
Taking the elements of the array from the user.
Program Logic Code for the adding of the elements of the array.
Printing output array after adding the element to the array.