- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
An array is a group of elements. Each element has its own index value. We can access any element using these indexes. But in the case of the last element, we don't know the index until we know the number of elements present in the array. In this case, we have to use logic. Let's discuss these details in a nutshell.
Accessing the first element
Since we know the index of the first element we can get the value of that element very easily. Let the array be arr. then the value of the first element is arr.
In the following example, there are arrays called array1 and array2 and both the arrays consist of '4' elements. Since the index of the first element is '0', the value of the first element is array1 and array2.
Tutorix Elon musk
Accessing the last element
If we know the number of elements in the array, using index we can find the last element. For instance, if an array named arr consists of 5 elements then the last element is arr. But in case if we are not aware of a number of elements then we have to proceed logically. The Last element is nothing but the element at the index position that is the length of the array minus-1. If the length is 4 then the last element is arr.
In the following example, the last element of arrays named array1 and array2 have been found out and the results were displayed in the output. In accessing the last element of the former array, a normal index is used whereas for the latter array, the length of the array is used.
- Delete first and last element from a LinkedList in Java
- Find First and Last Position of Element in Sorted Array in Python
- Maximum difference between first and last indexes of an element in array in C
- Java Program to Add Element at First and Last Position of a Linked list