The expression i += 2 in a for loop is used to increment the variable i by 2 in each iteration of the loop. This is particularly useful when you want to skip every other value or when you need to process elements at specific intervals.
Example Usage
Here’s an example of a for loop using i += 2:
#include <stdio.h>
int main() {
// Print even numbers from 0 to 10
for (int i = 0; i <= 10; i += 2) {
printf("%d\n", i);
}
return 0;
}
Explanation
- Initialization:
int i = 0initializesito 0. - Condition:
i <= 10checks ifiis less than or equal to 10. - Increment:
i += 2increases the value ofiby 2 after each iteration.
Output
The output of the above code will be:
0
2
4
6
8
10
Purpose
Using i += 2 allows you to:
- Iterate through a sequence of numbers with a specific step size (in this case, every second number).
- Efficiently process elements in an array or list where you only need to access every other element.
This technique is commonly used in scenarios where you want to reduce the number of iterations or when working with data structures that require skipping elements.
