Computer Science, asked by aseemalatheef, 10 months ago

write a Java program to duplicate an element from a set of elements.Get the array size and elements .Get the position of the element to be replicated at the end of the array.If the position given is greater than the size of an array display the message as "Position is greater than the size of an array".If the size of the array is zero or lesser then display the message "Invalid array size".

Answers

Answered by poojan
23

Program:

import java.util.*;

import java.io.*;

public class Main  

{  

public static void main(String[] args)  

{  

int n;  

Scanner sc=new Scanner(System.in);

n=sc.nextInt();  //array size

if(n<=0){ //if array size is 0 or less

   System.out.println("Invalid array size");

   System.exit(0);

}

int[] array = new int[n];

for(int i=0; i<n; i++)  //taking elements into array

{  

array[i]=sc.nextInt();  

}

int ind=sc.nextInt();  //taking the index of element to be duplicated and it should be in the range of 0 to n-1

if(ind>=n){ //If index is greater than array size [0..n-1]

   System.out.println("Position is greater than the size of an array");

   System.exit(0);

}

System.out.println(Arrays.toString(array)); //initial array

array = Arrays.copyOf(array, array.length + 1);

//create new array from old array and allocate one more element

array[array.length - 1] = array[ind];

//adding duplicate of indexed element at the end of array; new array

System.out.println(Arrays.toString(array));

}  

}  

Test case 1:

5

1

2

3

4

5

2        //element at index 2 is 3. Add duplicate 3 at the end of array

[1, 2, 3, 4, 5]

[1, 2, 3, 4, 5, 3]

Test case 2:

-1    //Array size should be greater than zero. Invalid size given.

Invalid array size

Test case 3:

5

1

2

3

4

5

5    

//Index starts with 0, ends with n-1 i.e., 4. So, 5 is out of the bound index.

Position is greater than the size of an array

Learn more:

1. Write a program to check whether it is a Lead number or not in java

https://brainly.in/question/15644815

2. Write a java program to input name and mobile numbers of all employees of any office. Using "Linear Search", search array of mobile numbers for a given "mobile number" and print name of employee if found, otherwise print a suitable message.

https://brainly.in/question/18217872

Attachments:
Similar questions