print the elements of the array without using the [] notation in c++
#include <iostream>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < size; i++) {
std::cout << *(arr + i) << " ";
}
return 0;
}
Explanation:
- First, we include the
<iostream>
library, which provides the input/output stream objects such asstd::cout
. - Inside the
main()
function, we declare an arrayarr
of typeint
and initialize it with some values{1, 2, 3, 4, 5}
. - We calculate the size of the array by dividing the total size of the array by the size of its first element. This is done using the
sizeof()
operator. - Next, we use a
for
loop to iterate over each element of the array. The loop variablei
starts from 0 and goes up tosize - 1
. - Inside the loop, we use pointer arithmetic to access each element of the array. The expression
*(arr + i)
gives us the value at thei
-th index of the array. - Finally, we use
std::cout
to print each element followed by a space.
Note: The *(arr + i)
is equivalent to arr[i]
and is used here to demonstrate an alternative way of accessing array elements without using the []
notation.