Welcome to the Java Loops (for) Tutorial! In this comprehensive guide, we'll dive deep into understanding for loops in Java. By the end of this lesson, you'll have a solid foundation to write clean, efficient, and practical code. Let's get started!
Loops are essential control structures in programming that allow us to repeat a block of code as many times as needed. In Java, we have two main types of loops: for loops and while loops. Today, we'll focus on the for loop.
for Loop Syntax 💡A for loop consists of three parts separated by semicolons (;):
Here's a basic for loop structure:
for (initialization; condition; increment) {
// code to be repeated
}Now, let's put this into practice! We'll create a simple example that prints numbers from 1 to 10 using a for loop.
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}In this example, i is the control variable, initially set to 1. The condition checks if i is less than or equal to 10, and the increment updates i by 1 after each iteration.
for Loops 💡You can declare and use variables inside a for loop, as well as include other control structures like if statements and break and continue.
Here's an example that demonstrates these concepts:
public class ForLoopExample2 {
public static void main(String[] args) {
for (int i = 2; i <= 10; i++) {
if (isPrime(i)) {
System.out.println(i);
}
}
}
private static boolean isPrime(int number) {
if (number <= 1) return false;
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) return false;
}
return true;
}
}In this example, we've created a helper method called isPrime to check if a number is prime. We're using a nested for loop within the main loop to check if the number is divisible by any numbers up to its square root.
for Loop 🎯What is the correct syntax for a `for` loop in Java?
By now, you should have a good understanding of for loops in Java! In the next lesson, we'll dive deeper into while loops and compare the differences between these two powerful control structures. Keep learning, keep coding! 🚀💻