OneBite.Dev - Coding blog in a bite size

get the last element of array in C

Code snippet on how to get the last element of array in C

  int lastElement = array[sizeOfArray - 1];

This code uses the array access operator (square brackets) to get the last element of an array by specifying the size of the array and subtracting one. This is because the indices of array elements start from 0, so the last element will be at the index equal to the size of the array minus one. For example, if the size of the array is 5, then the last element will be at the index 4. In this line of code, the expression “sizeOfArray - 1” is used to get the index of the last element, and then it is used to get the last element using the array access operator.

c