To get the last element in an array in C, you can use array indexing similar to other languages.
In this example,
numbers
with some elements.numbers[count - 1]
and store it in the variable lastNumber
.lastNumber
.#include <stdio.h>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int count = sizeof(numbers) / sizeof(numbers[0]);
int lastNumber = numbers[count - 1];
printf("Last number is: %d\n", lastNumber);
return 0;
}
Last number is: 5
In this example,
chars
with some elements.chars[count - 1]
and store it in the variable lastChar
.lastChar
.#include <stdio.h>
int main() {
char chars[] = {'a', 'b', 'c'};
int count = sizeof(chars) / sizeof(chars[0]);
char lastChar = chars[count - 1];
printf("Last char is: %c\n", lastChar);
return 0;
}
Last char is: c
In this tutorial, we learned How to get Last Element in Array in C language with well detailed examples.