Loop Array In C++
Code snippet for how to Loop Array In C++ with sample and detail explanation
Looping over arrays in C++ is an essential skill when dealing with data structures where the elements are grouped together. This guide will take you through a simple example and explanation on how to perform this task.
Code snippet for Looping Array in C++
#include<iostream>
using namespace std;
int main(){
int numbers[5] = {7, 5, 6, 12, 35};
cout << "The numbers are: ";
// Displaying array elements using for loop
for(int n : numbers) {
cout << n << " ";
}
return 0;
}
Code Explanation for Looping Array in C++
To begin with, we include the iostream library that allows us to perform standard input and output operations. The namespace ‘std’ eliminates the need to use ‘std::’ before the I/O functions.
Among the first lines of our main function, we create an integer array named ‘numbers’ and assign it five different integer values.
Next, we set up a for loop to iterate through each element in the array. In this loop, we use a range-based format (int n : numbers) which tells the loop to go through each element in the array named ‘numbers’ and treat the current element as ‘n’ during each iteration. In some other programming languages, this variety of loop is often termed a “for-each” loop.
Within the loop, we use ‘cout’ to print the value of ‘n’ followed by two spaces. Thus, for each element in the array, its value will be printed on the screen with a space in between.
Once the loop has iterated over all the elements in the array, the function ends with ‘return 0;’, indicating that the program has successfully completed.
This way of looping through arrays in C++ is easy to understand, reduces the chances of off-by-one errors, and generally leads to cleaner code. It’s particularly useful when we don’t need to know the index of the current element in the array, just the element itself.