1. Implement an array of 10 integers with following features:
a. Add an element at start
b. Add an element at end
c. Add an element at i-th index
d. Remove an element from start
e. Remove an element from end
f. Remove an element from i-th index
1
Expert's answer
2018-01-28T09:08:44-0500
public class Main { public static void main(String[] args) { IntArray a = new IntArray();
System.out.println("Add value 7 at start: "); a.addAtStart(7); System.out.println(a);
System.out.println("Add value 5 at a[3]: "); a.addByIndex(5, 3); System.out.println(a);
System.out.println("Add value 2 at a[8]: "); a.addByIndex(2, 8); System.out.println(a);
System.out.println("Add value 1 at start:"); a.addAtStart(1); System.out.println(a);
System.out.println("Add value 4 at end:"); a.addAtEnd(4); System.out.println(a);
System.out.println("Remove value at a[1]:"); a.removeByIndex(1); System.out.println(a);
System.out.println("Remove value from start:"); a.removeFromStart(); System.out.println(a);
System.out.println("Add value 9 at end:"); a.addAtEnd(9); System.out.println(a);
System.out.println("Remove value from end:"); a.removeFromEnd(); System.out.println(a); } }
=================================
public class IntArray { private int[] arr;
public IntArray() { arr = new int[10]; } void addByIndex (int value, int index) { if(index >= 0 && index <= 9) { int[] buffer = new int[this.arr.length]; for(int i = 0; i < this.arr.length; i++) { buffer[i] = this.arr[i]; }
this.arr = new int[this.arr.length];
for(int i = 0; i < index; i++) { this.arr[i] = buffer[i]; }
this.arr[index] = value;
for(int i = index + 1; i < this.arr.length; i++) { this.arr[i] = buffer[i - 1]; } } else { System.out.println("Incorrect index value!"); } }
Comments
Leave a comment