Sobes.tech
Junior — Middle

What methods can be used to traverse array elements?

sobes.tech AI

Answer from AI

In C/C++, iterating over array elements can be implemented in several ways:

  1. For loop with index:
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
for (int i = 0; i < size; i++) {
    // process arr[i]
}
  1. While loop with pointer:
int* ptr = arr;
int* end = arr + size;
while (ptr < end) {
    // process *ptr
    ptr++;
}
  1. Range-based for (C++11 and above):
for (int value : arr) {
    // process value
}
  1. Using standard algorithms (C++):
#include <algorithm>
#include <iostream>

std::for_each(std::begin(arr), std::end(arr), [](int value) {
    // process value
});

Each method is suitable for different tasks and programming styles.