C++ Program to Loop Over an Array
The below example demonstrates how we can loop over an array in C++.
// C++ program to demonstrate how we can loop over an array
#include <iostream>
using namespace std;
int main()
{
// Create and initialize an array
int arr[] = { 1, 2, 3, 4, 5 };
// calculate the size of an array
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Elements in an Array: ";
// Loop over an array and print each element
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
return 0;
}
Output
Elements in an Array: 1 2 3 4 5
Time Complexity: O(n), here n is a size of an array.
Auxiliary Space: O(1)
Note: Besides using traditional loops, we can also use the range-based
for
loops and std::for_each algorithm to loop over an array and access each element.
How to Loop Over an Array in C++?
In C++, an array is a data structure that stores elements of similar type in contiguous memory locations. We can access the elements of an array using array indexing. In this article, we will learn how to loop over an array in C++.
Example:
Input: int arr[] = [1, 2, 3, 4, 5] Output: Array Elements: 1 2 3 4 5