Using a For Loop to Count Iterations
To use a for loop for counting iterations and keep track of the iterations with a counter variable in Java, you can declare a counter variable before the loop and increment it inside the loop.
Here is an example of how you can use a for loop to count the number of iterations and keep track of the iterations with a counter variable:
int counter = 0;
for (int i = 0; i < 10; i++) {
// Code to be executed in the loop
counter++;
}
System.out.println("Number of iterations: " + counter);
Output:
Number of iterations: 10
In this example, the counter
variable is initialized to 0 before the loop. The loop iterates 10 times, and the counter
variable is incremented by 1 each time the loop executes. After the loop has completed, the counter
variable will hold the value 10, which represents the number of iterations that were performed.
You can also use a counter variable to keep track of other types of data, such as the sum of all the elements in an array or the number of times a particular value appears in a list. For example:
int[] array = {1, 2, 3, 4, 5}
int sum = 0;
for (int i = 0; i < array.length; i++) {
sum += array[i];
}
System.out.println("Sum of array elements: " + sum);
Output:
Sum of array elements: 15
This code uses a for loop to iterate over the elements of an array and keep track of the sum of all the elements using the sum
variable. After the loop has completed, the sum
variable will hold the total sum of all the elements in the array.
Using a counter variable in combination with a for loop can be a useful technique for counting iterations and keeping track of other types of data in your Java programs.
Find out more about Java here.