To get the last element in an array in C++, you can use array indexing similar to C.
In this example,
numbers
with some elements.numbers[count - 1]
and store it in the variable lastNumber
.lastNumber
.#include <iostream>
using namespace std;
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int count = sizeof(numbers) / sizeof(numbers[0]);
int lastNumber = numbers[count - 1];
cout << "Last number is: " << lastNumber << endl;
return 0;
}
Last number is: 5
In this example,
words
with some elements.words[count - 1]
and store it in the variable lastWord
.lastWord
.#include <iostream>
#include <string>
using namespace std;
int main() {
string words[] = {"apple", "banana", "cherry"};
int count = sizeof(words) / sizeof(words[0]);
string lastWord = words[count - 1];
cout << "Last word is: " << lastWord << endl;
return 0;
}
Last word is: cherry
In this tutorial, we learned How to get Last Element in Array in C++ language with well detailed examples.