In this tutorial you will learn about the Java Program to Add Element to Array and its application with practical example.
Java Program to Add Element to Array
In this tutorial, we will learn to create a Java program that will add the elements to 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.
Algorithm:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Step 1 :- Initialize the program. Step 2 :- Declaring the variables for the program. Step 3 :- Taking the size of the array. Step 4 :- Taking the elements of the array. Step 5 :- Taking the extra element for the array. Step 6 :- Adding that element in the array. Step 7 :- Printing the array after insertion. Step 8 :- End the program. |
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 in the array using a for-loop. At last, we will print the added 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 28 29 30 31 32 |
import java.util.Scanner; class AddingElement { public static void main(String[] args) { //Declaring the required variable for the program int len, p,ele; Scanner sc = new Scanner(System.in); //Taking the size of the array from the user. System.out.print("Enter length of an array:"); len = sc.nextInt(); int arr[] = new int[len+1]; //Taking the elements of the array from the user. System.out.println("Enter "+len+" elements:"); for(int i = 0; i < len; i++) { arr[i] = sc.nextInt(); } //Taking the element to add in the array from the user. System.out.print("Enter the element which you want to insert:"); ele = sc.nextInt(); arr[len] = ele; //Printing the array after inserting the elements. System.out.print("After inserting : "); for(int i = 0; i <len; i++) { System.out.print(arr[i]+","); } System.out.print(arr[len]); } } |
Output:-
In the above program, we have first initialized the required variable.
- ele = it will hold the integer value.
- len = it will hold the integer value.
- i = it will hold the integer value.
Input size and the elements of the array from the user.
Program Logic Code for the adding of the element in the array.
Printing array after adding the element in the array.