for loop
for (initialExpression; testExpression; updateExpression) {...}
for
loop has the same concept of general loop. In while loop we needed to manually update the iteration inside the code block. However, in for
loop, it automatically iterates through the loop.
For example, I want to find the sum of the numbers 1 to 100.
public class Loops {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println(sum);
}
}
Step01: Using for
we initialise a loop
Step02: Inside the loop parenthesis, initialExpression
is int i = 1
, declaring the iteration variable
Step03: testExpression
is i <= 100
, returns a boolean
value to check whether it is true
or false
Step04: updateExpression
is i++
, updating the iteration variable every time the loop repeats
Step05: Code inside the loop block will execute until the loop terminates
Step06: Once the iteration variable i
becomes 101
, the testExpression
becomes false
and the loop will terminate
Output
5050
for...each loop
for (dataType item: array) {...}
for...each
loop is actually performed in an array to iterate through the elements inside it. So, I recommend you to take a look at the Arrays section before learning for...each
loop.
An example of for...each
loop is given below,
public class Loops {
public static void main(String[] args) {
int[] numbers = {98, 92, 98, 85};
for (int number: numbers) {
System.out.println(number);
}
}
}
Step01: Using for
we initialise the loop
Step02: Inside the loop parenthesis, we declare the data type of the elements inside the array. In this case int
Step03: Then we declare a new variable number
for each elements. In every iteration, the values inside the array will be assigned to this variable one by one. For example in first iteration number = 98
, second iteration number = 92
and so on.
Step04: Then we pass the array which we want to iterate through separating by :
Step05: The loop will repeat n
number of times, where n
is the length of the array
Output
98
92
98
85
Try to iterate through an array of Strings and print the elements by yourself.
Happy Coding
Top comments (0)