In: Computer Science
Create a class and name it MyArray. This class must have an internal array of integers and the consumer should specify the maximum capacity when instantiating. MyArray class must provide following functions:
1- insert: This method receives and integer and inserts into the array. For simplicity you can assume the array is large enough and never overflows.
2- display: This method displays all integers stored in the array in the same order as they are inserted (first in first out).
3- reverseDisplay: This method displays all integers stored in the array in the reverse order as they are inserted (first in last out).
4- getMax: This method returns the maximum value stored in the array.
Explanation:
Here is the class MyArray in Bold, which has the array a, elements to store the current number of elements in the array.
Then insert, display, reverseDisplay and getMax methods are defined.
In the Main function, an object of the class MyArray is created and all the functions are checked.
Code:
class MyArray
{
int a[];
int elements;
MyArray(int max_capacity)
{
a = new int[max_capacity];
elements = 0;
}
void insert(int n)
{
a[elements] = n;
elements++;
}
void display()
{
for(int i=0; i<elements; i++)
{
System.out.print(a[i]+" ");
}
System.out.println();
}
void reverseDisplay()
{
for(int i=elements-1; i>=0; i--)
{
System.out.print(a[i]+" ");
}
System.out.println();
}
int getMax()
{
int max = a[0];
for(int i=0; i<elements; i++)
{
if(a[i] > max)
max = a[i];
}
return max;
}
}
public class Main
{
public static void main(String[] args) {
MyArray m = new MyArray(10);
m.insert(3);
m.insert(5);
m.insert(7);
m.display();
m.reverseDisplay();
System.out.println("Max:
"+m.getMax());
}
}
Output:
PLEASE UPVOTE IF YOU FOUND THIS HELPFUL!
PLEASE COMMENT IF YOU NEED ANY HELP!