A for loop is a fundamental construct in programming that allows you to repeat a block of code a specific number of times. It's an essential tool for automating repetitive tasks and iterating over collections of data. In Java, the for loop provides a concise and structured way to accomplish these tasks. In this article, we'll dive into the details of the for loop in Java, covering its syntax, usage, and providing multiple examples along the way.
The syntax of a for loop in Java consists of three essential components: initialization, condition, and iteration.
for (initialization; condition; iteration) {
// Code to be executed
}
Let's start with a simple example to illustrate the basic usage of a for loop. Suppose we want to print the numbers from 1 to 5.
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
Code Explanation:
Output
1
2
3
4
5
For loops are often used to iterate over arrays and collections. Let's explore how to use a for loop with an array and a collection of strings.
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Code Explanation:
Output
1
2
3
4
5
Example 2: Iterating over a Collection
List<String> fruits = Arrays.asList("Apple", "Banana", "Orange");
for (String fruit : fruits) {
System.out.println(fruit);
}
Code Explanation:
Output
Apple
Banana
Orange
Java provides the break and continue statements to control the flow of a loop.
Example 1: Using Break
for (int i = 1; i <= 10; i++) {
if (i == 6) {
break;
}
System.out.println(i);
}
Code Explanation:
Output
1
2
3
4
5
Example 2: Using Continue
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}
Code Explanation:
Output
1
2
4
5
Problem 1: Calculate the sum of numbers from 1 to 100.
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("Sum: " + sum);
Output
Sum: 5050
Problem 2: Print the elements of an array in reverse order.
int[] numbers = {1, 2, 3, 4, 5};
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.println(numbers[i]);
}
Output
5
4
3
2
1
In this article, we covered the basics of using a for loop in Java. We explored its syntax, demonstrated how to execute code, iterate over arrays and collections, and control the flow of a loop using the break and continue statements. By mastering for loops, you'll have a powerful tool to automate repetitive tasks and efficiently process data in your Java programs.
60 videos|37 docs|12 tests
|
|
Explore Courses for EmSAT Achieve exam
|