forked from ashvish183/Hactoberfest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
5e9b016
commit bfea4ac
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
// Java Program to add an element in an Array | ||
|
||
import java.io.*; | ||
import java.lang.*; | ||
import java.util.*; | ||
|
||
class GFG { | ||
|
||
// Function to add x in arr | ||
public static int[] addX(int n, int arr[], int x) | ||
{ | ||
int i; | ||
|
||
// create a new array of size n+1 | ||
int newarr[] = new int[n + 1]; | ||
|
||
// insert the elements from | ||
// the old array into the new array | ||
// insert all elements till n | ||
// then insert x at n+1 | ||
for (i = 0; i < n; i++) | ||
newarr[i] = arr[i]; | ||
|
||
newarr[n] = x; | ||
|
||
return newarr; | ||
} | ||
|
||
// Driver code | ||
public static void main(String[] args) | ||
{ | ||
|
||
int n = 10; | ||
int i; | ||
|
||
// initial array of size 10 | ||
int arr[] | ||
= { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; | ||
|
||
// print the original array | ||
System.out.println("Initial Array:\n" | ||
+ Arrays.toString(arr)); | ||
|
||
// element to be added | ||
int x = 50; | ||
|
||
// call the method to add x in arr | ||
arr = addX(n, arr, x); | ||
|
||
// print the updated array | ||
System.out.println("\nArray with " + x | ||
+ " added:\n" | ||
+ Arrays.toString(arr)); | ||
} | ||
} |