In: Computer Science
for java
Welcome to a classic homework problem! Create a public class called Last8. You should exposed two public methods: add: adds a value, does not return a value last: returns an array containing the last 8 values that were added, in any order. You do not need a constructor, but you can add an empty one if you need. Until 8 values have been added you should return 0s in their place. For example, here's how an instance of Last8 should work:
Program :
import java.util.Scanner;
public class Main
{
public static void add(int[] a,int x,int i)
{
a[i]=x;
}
public static int[] last(int[] a)
{
int NewArray[] = new int[8];
int c=0,k=0;
int j=0;
while(a[k]!='\0')
{
c++;
k=k+1;
}
if(c>=8){
int l=c-8;
for(int i=c-1;i>=l;i--)
{
NewArray[j]=a[i];
j=j+1;
}
}
else{
for(int i=7;i>=0;i--)
{
NewArray[j]=a[i];
j=j+1;
}
}
return NewArray;
}
public static void main(String[] args) {
int Array[] = new int[100];
add(Array,1,0);
add(Array,2,1);
add(Array,3,2);
add(Array,4,3);
int[] res=last(Array);
for(int i=0;i<8;i++)
{
System.out.print(res[i] +" ");
}
}
}
Output :
Thank You Have a Great Day !!! Please do like.