Get the last n items from an array in C++

In this tutorial, we will learn how to get the last n items from an array in C++ in an easy way. So let’s get started.

How to get the last n items from an array in C++?

This can be done by following some simple steps:

  1. Declaration and initialization:- First of all we will declare and initialize our array. This is very simple. Let’s see how to do it.

 

int arr[]={1,2,3,4,5,6,7};

2. Finding the number of elements in an array:- You may already know how to do it. But let me clarify this can be done by dividing the whole size of an array by the size of an element in an array.

int n=sizeof(arr)/sizeof(arr[0]);

3. Taking input:-  Now we will take the count of numbers that the user wants to print from last as input. This can be done by using a cin statement.

int k;
cout<<"Enter the number of elements:-"<<endl;
cin>>k;

4. Using loop:-The next step is to loop through array elements starting from n-1 which is the index of the last element of our array to the count till where we want to print our numbers from last and lastly we will decrement our iterator. Let’s see how to do it.

for(int i=n-1;i>(n-1)-k;i--)
{
  cout<<arr[i]<<" ";
}

5. Using conditionals:-  The Final step is to use conditionals. You might be wondering why I am using conditionals? Although I am getting my answer by using loops.

But let me tell you that we are wrapping our loop inside conditionals to ensure that there will be no garbage value. For example, let’s say there are 7 elements in an array. But the user enters that he/she wants to print 8 elements then it will return some garbage value.

So to avoid confusion we will use the if condition and inside that we will say that if the number of elements that the user wants exceeds the total number of elements (i.e.  k>n), then the loop will not be executed.

 

if(k>n)
{
  cout<<"Enter valid number of elements"<<endl;
}
else
{
  cout<<"last "<<k<<" Elements are:";
  for(int i=n-1;i>(n-1)-k;i--)
  {
    cout<<arr[i]<<" ";
  }
}

So here we reach our solution. Isn’t it easy right? Now let’s see the complete code.

 

#include <iostream>
using namespace std;
int main()
{
    int arr[]={1,2,3,4,5,6,7};
    int n=sizeof(arr)/sizeof(arr[0]);

    int k;
    cout<<"Enter the number of elements"<<endl;
    cin>>k;

    if(k>n)
    {
        cout<<"Enter valid number of elements"<<endl;
    }
    else
    {
        cout<<"last "<<k<<" Elements are:";
        for(int i=n-1;i>(n-1)-k;i--)
        {
        cout<<arr[i]<<" ";
        }
    }

    return 0;
}

That’s it for this tutorial I hoped you liked it.

Keep learning!

Leave a Reply

Your email address will not be published.