2.5 Loops
Table of Contents
for loops
Loops let you repeat a block of code many times without writing it over and over. In C++ the most common loop in ROOT-style analysis code is the for loop. It is especially useful when you know exactly how many times you want to repeat an operation, for example when you process all bins of a histogram or all elements of an array.
The general form of a for loop in C++ is:
for (initialization; condition; update) {
// code to repeat
}The three parts inside the parentheses control the loop:
- The initialization runs once before the loop starts, typically to declare and set a counter variable.
- The condition is checked before every iteration. If it is
true, the loop body runs. If it isfalse, the loop stops. - The update runs after each iteration, usually to change the counter variable.
A very common pattern is counting from zero up to, but not including, some upper limit N:
int N = 10;
for (int i = 0; i < N; ++i) {
cout << "i = " << i << endl;
}
Here i starts at 0, the loop continues while i < N, and ++i increases i by 1 after each iteration. This prints the values 0 through 9.
Important rule: In C++ arrays and many ROOT collections are indexed starting at 0. A loop that visits all elements usually goes from index 0 to N - 1 with a condition like i < N, not i <= N.
Inside a for loop you can use any valid C++ statements, including if conditions, arithmetic operations, function calls, and ROOT commands. For example, you can use a for loop directly in the ROOT interactive shell:
root [0] for (int i = 0; i < 5; ++i) {
root [1] cout << "Hello " << i << endl;
root [2] }
You can also use break and continue to control the loop more precisely. break stops the loop immediately, and continue skips the rest of the current iteration and goes on to the next one.
for (int i = 0; i < 10; ++i) {
if (i == 3) continue; // skip printing 3
if (i == 7) break; // stop completely when i is 7
cout << i << endl;
}
In ROOT analysis code, for loops are heavily used to iterate over known ranges such as bins of a histogram, indices in a C++ array, or elements of a std::vector when you want explicit control over the index.
while loops
A while loop repeats code as long as a condition remains true. It is most useful when you do not know in advance how many iterations you will need. Instead, the loop depends on some condition that can change in complex ways inside the loop body.
The general form is:
while (condition) {
// code to repeat
}
The condition is checked before each iteration. If it is true, the body runs. If it is false, the loop stops and execution continues after the loop.
For example, consider a simple counter:
int i = 0;
while (i < 5) {
cout << "i = " << i << endl;
++i;
}
This produces the same output as the previous for example. The important difference is that the initialization (int i = 0) is outside the loop header, and the update (++i) appears inside the loop body. With a while loop it is your responsibility to make sure that the condition eventually becomes false, otherwise the loop will run forever.
Important rule: Always ensure that something inside a while loop changes the variables used in the condition in a way that makes the condition false at some point, otherwise you create an infinite loop.
A while loop is especially natural when you are reading data until there is nothing left. For example, when reading lines from a text file, you often do not know the number of lines in advance, so a while loop that checks for end of file is a good choice.
C++ also has a do { ... } while (condition); loop, where the body is executed at least once before the condition is checked, but that form is used less often in typical ROOT analysis code. Most of the time you will work with for and while loops.
Just like in for loops, you can use break to exit early and continue to skip to the next iteration. while loops appear in many ROOT macros to repeat operations until a certain analysis condition is met, such as reading all events, processing input from a file, or waiting until a counter reaches a threshold.
Looping over data
In ROOT analysis you repeatedly perform the same calculation for many data items, such as events in a TTree, bins in a histogram, or elements in a C++ container. Loops are the tool that lets you express these repetitive operations clearly and compactly.
A typical pattern in beginner macros is to loop over a simple C++ array. Suppose you have an array of ten values and you want to print them:
double values[10] = {1.2, 3.4, 2.2, 5.0, 4.1, 6.3, 7.7, 8.8, 9.0, 0.5};
for (int i = 0; i < 10; ++i) {
cout << "values[" << i << "] = " << values[i] << endl;
}
Here the loop index i selects each element. This is exactly the same pattern you will use later with histogram bin indices or with vector indices.
When you work with standard C++ containers such as std::vector, you often have a variable that stores the number of elements, and you use that size in the loop condition:
std::vector<double> energy;
energy.push_back(10.5);
energy.push_back(12.3);
energy.push_back(9.8);
for (int i = 0; i < energy.size(); ++i) {
cout << "energy[" << i << "] = " << energy[i] << endl;
}In ROOT, many operations on data combine loops with simple arithmetic or conditions. For example, you might compute the sum of an array of measurements:
double sum = 0.0;
for (int i = 0; i < 10; ++i) {
sum += values[i];
}
cout << "Sum = " << sum << endl;Or you might count how many values pass a simple cut:
int count = 0;
for (int i = 0; i < 10; ++i) {
if (values[i] > 5.0) {
++count;
}
}
cout << "Number of values > 5 = " << count << endl;These simple examples mirror real analysis tasks, where you will loop over events, apply selection criteria, and update counters or histograms. You can already see the structure that you will reuse when you fill histograms, select events, or process TTrees in later chapters.
Important pattern: Loop over all data items, apply selection conditions with if, and update accumulated quantities such as sums, counters, or histogram fills inside the loop.
By becoming comfortable with for and while loops on basic C++ data, you prepare yourself to understand the larger event loops and data processing structures that are central to ROOT analysis.
Views: 11
KAHIBARO