60 690
Assignments Done
97,9%
Successfully Done
In April 2018

Answer to Question #72892 in Java | JSP | JSF for Atif Haroon

Question #72892
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
Expert's answer

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!");
}
}

void addAtStart(int value)
{
this.addByIndex(value, 0);
}

void addAtEnd(int value)
{
this.addByIndex(value, this.arr.length - 1);
}

void removeByIndex (int index)
{
int[] buffer = new int[this.arr.length];
for(int i = 0; i < arr.length; i++)
{
buffer[i] = arr[i];
}

this.arr = new int[this.arr.length];

for(int i = 0; i < index; i++)
{
this.arr[i] = buffer[i];
}
for(int i = index + 1; i < arr.length; i++)
{
this.arr[i - 1] = buffer[i];
}

}

void removeFromStart()
{
this.removeByIndex(0);
}

void removeFromEnd()
{
this.removeByIndex(this.arr.length - 1);
}

@Override
public String toString() {
String s = "";
for(int i = 0; i < arr.length; i++)
{
s += arr[i] + " ";
}
return s;
}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions