Get last n items from an array in Java

In this article, we will see a program to Get the last n items from an array in Java. I hope, you already have some idea about array if you are familiar with Java.

An array is a data structure that is used to store data of the same datatype. Users can explicitly take the value of size or have to define it in the program before using it.

Below is the syntax of an array:

datatype[] arrayname;
or
datatype arrayname[];

Now, below is our Java code that will able to get the last n items from our array:

import java.util.*;

public class lastElements
{
public static void main(String args[])
{
    int index=0,i;

   int[] arrayEx1 = new int[size1];
     
   int fromLast;

    arrayEx1=[4,1,2,5,3,6,7];
    fromLast=5;

for(i=0; i<arrayEx1.length; i++) {
         if(arrayEx1[i]==fromLast)
    {
      index=i;
      break;
    }
}
System.out.print("Last n items from an array is: ");
for (i=index; i<arrayEx1.length;i++)
System.out.print(" "+arrayEx1[i] );
}
}

The output of the above program is given below:

Last n items from an array is: 5 3 6 7

Explanation of our program:

Here we have taken the size of an array from the user. As per the size of an array, the user will enter elements and the values will be stored in the array. After initializing we will take elements from the user from where the user wants to print the elements. the elements will be printed from that position till the end of the array. We will print the elements from that index by storing the index of that value in the integer name index. So from index till the last position, we will print it.

Complexity:

O(n) where n is the size of the array.

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *