Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

insert an array in function and delete it also

+2 votes
asked Feb 20, 2019 by mahesh tpt (140 points)

1 Answer

0 votes
answered Apr 9 by Bhavanithra Mani (180 points)
import java.util.Scanner;

public class ArrayExample {

    // Function to insert an element at a given position
    public static int[] insert(int[] arr, int element, int position) {
        if (position < 0 || position > arr.length) {
            System.out.println("Invalid position!");
            return arr;
        }
        int[] newArr = new int[arr.length + 1];
        for (int i = 0, j = 0; i < newArr.length; i++) {
            if (i == position) {
                newArr[i] = element;
            } else {
                newArr[i] = arr[j++];
            }
        }
        return newArr;
    }

    // Function to delete an element at a given position
    public static int[] delete(int[] arr, int position) {
        if (position < 0 || position >= arr.length) {
            System.out.println("Invalid position!");
            return arr;
        }
        int[] newArr = new int[arr.length - 1];
        for (int i = 0, j = 0; i < arr.length; i++) {
            if (i != position) {
                newArr[j++] = arr[i];
            }
        }
        return newArr;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int[] arr = {1, 2, 3, 4, 5};
        System.out.print("Original Array: ");
        for (int num : arr) System.out.print(num + " ");
        System.out.println();

        // Insert
        arr = insert(arr, 99, 2); // Insert 99 at index 2
        System.out.print("After Insertion: ");
        for (int num : arr) System.out.print(num + " ");
        System.out.println();

        // Delete
        arr = delete(arr, 4); // Delete element at index 4
        System.out.print("After Deletion: ");
        for (int num : arr) System.out.print(num + " ");
        System.out.println();
    }
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...