Click here to Skip to main content
14,876,938 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
-Create a new array of size n+1, where n is the size of the original array.
-Add the n elements of the original array in this array.
-Add the new element in the n+1 th position.
-Print the new array.

What I have tried:

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));
Updated 27-Mar-21 15:09pm
Richard MacCutchan 27-Mar-21 11:55am
That is Java not Javascript.

1 solution

We are more than willing to help those that are stuck: but that doesn't mean that we are here to do it all for you! We can't do all the work, you are either getting paid for this, or it's part of your grades and it wouldn't be at all fair for us to do it all for you.

So we need you to do the work, and we will help you when you get stuck. That doesn't mean we will give you a step by step solution you can hand in!
Start by explaining where you are at the moment, and what the next step in the process is. Then tell us what you have tried to get that next step working, and what happened when you did.

If you are having problems getting started at all, then this may help: How to Write Code to Solve a Problem, A Beginner's Guide[^]

To be honest, if you wrote the rest of that, you should have no problem with a simple JavaScript for Loop[^]
Beckam12332 27-Mar-21 14:23pm
sorry , and thnkyou fr yr advice

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900