Ranged for Loop
We already know how to iterate through arrays using for loops right? But in C++, there's another type of for
loop called the ranged for
loop through which we can access the array elements very easily.
Suppose today's your birthday and you want to distribute toffees to 5 students standing in a line. Now there are two ways to refer to them:
- Distribute toffees to students from position 1 to 5
- Distribute toffees to all students in the line
Here, both options are right but ain't the second option simpler? You want to meet each student in the line to distribute the toffees. You start with the first student, move to the next, and continue until you’ve given toffees to each student in the line. You don’t need to know how many students there are or their specific positions; you just want to see each one.
This is the difference between a simple for loop (first statement) and a ranged for loop (second statement). Here the student line refers to an array of size 5. Now let's understand ranged for loop with the help of a program.
Example
#include <iostream>
using namespace std;
int main() {
// initialize array
int arr[5] = {4, 0, 67, 9, 22};
// ranged for loop to print array elements
for (int var: numbers) {
cout << var << endl;
}
return 0;
}
Output
4
0
67
9
22
In the program,
for
- syntax of the looparr
- name of the arrayint var
- temporary variable just like the iterator i used for loops to access array elements (it should be of the same data type as the array)
Loop will run 5 times because the size of array is 5. In each iteration, the element of the array is assigned to the var
variable. Hence, when we printvar
, we are just printing the array elements itself. This is the reason for making the data type of var
same as that of the array.
Problem: Sum of Array Elements
Problem Statement:
Write a C++ program to create an array of size 4 with elements 9, 3, 12 & 7 and print its sum. Write separate programs, one using a for loop and one using a ranged for loop.
Output
Sum = 31
Solution using for loop
#include <iostream>
using namespace std;
int main() {
// Create an array of size 4 with elements 9, 3, 12, and 7
int arr[4] = {9, 3, 12, 7};
// Calculate the sum of the array elements
int sum = 0;
for (int i=0; i<4; i++) {
sum += arr[i];
}
// Print the sum of the array
cout << "Sum of the array: " << sum << endl;
return 0;
}
Solution using ranged for loop
#include <iostream>
using namespace std;
int main() {
// Create an array of size 4 with elements 9, 3, 12, and 7
int arr[4] = {9, 3, 12, 7};
// Calculate the sum of the array elements
int sum = 0;
for (int element : arr) {
sum += element;
}
// Print the sum of the array
cout << "Sum of the array: " << sum << endl;
return 0;
}