It can be done by using an indexed loop such that the counter runs from 0 to the array size minus one. In this manner, you can reference all the elements in sequence by using the loop counter as the array subscript.
To reference all the elements in a one-dimensional array, you typically loop through each element of the array using an index variable or a foreach loop, depending on the programming language you’re using. Here’s how you can do it in various programming languages:
C/C++:
cpp
#include<iostream>
intmain(){ int arr[] = {1, 2, 3, 4, 5}; int size = sizeof(arr) / sizeof(arr[0]); // Calculate array size
for (int i = 0; i < size; ++i) {
std::cout << arr[i] << " ";
} return0;
}
for (int num : arr) {
System.out.print(num + " ");
}
}
}
Python:
python
arr = [1, 2, 3, 4, 5]
for num in arr: print(num, end=" ")
JavaScript:
javascript
let arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) { console.log(arr[i]);
}
Ruby:
ruby
arr = [1, 2, 3, 4, 5]
arr.each do |num|
puts num end
In all these examples, each element of the array is accessed and printed out. You can perform any operation on the elements of the array inside the loop according to your requirement.