Welcome back to CodeYourCraft! Today, we're diving into the world of Java Loops, specifically focusing on the while loop. By the end of this lesson, you'll be able to understand, implement, and use the while loop in your own projects. 📝 Let's get started!
A loop is a control structure that allows a section of code to repeat until a certain condition is met. In Java, we have two main types of loops: while loops and for loops. Today, we'll be focusing on the while loop.
while Loop 💡The while loop continues to execute a block of code as long as a given condition remains true. The loop checks the condition at the beginning of each iteration. If the condition is false, the loop terminates, and the program continues with the next statement.
Here's the basic structure of a while loop:
while (condition) {
// code to be executed as long as the condition is true
}Let's look at an example:
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}In this example, we're printing the count from 0 to 4. The loop will continue as long as the condition count < 5 is true. Each time the loop iterates, we increment the count variable by 1.
Let's consider a simple example where we want to check if a number is prime. A prime number is a number greater than 1 that can only be divided by 1 and itself. Here's how we can use a while loop to check for prime numbers:
import java.util.Scanner;
public class PrimeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
boolean isPrime = true;
int counter = 2;
while (counter * counter <= number) {
if (number % counter == 0) {
isPrime = false;
break;
}
counter++;
}
if (isPrime) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
}
}In this example, we're asking the user to enter a number. We're checking if the number is prime by testing its divisibility from 2 up to the square root of the number. If the number is not divisible by any number up to its square root, it's considered prime.
What is a loop in programming?
What is the purpose of the `count++` statement in the `while` loop example?
Remember, practice makes perfect! Keep experimenting with while loops, and soon you'll be able to use them like a pro in your own projects. Happy coding! 🎉