Chapter - 4 Loops and Files
4.1 The while Loop
Purpose
A while loop repeatedly executes a block of code as long as its condition evaluates to true.
Syntax
while (condition) {
// Statements
}
Example
int count = 1;
while (count <= 5) {
System.out.println(“Count: ” + count);
count++;
}
Explanation
count = 1: Initializes the counter variable.
count <= 5: The loop condition.
count++: Increments count after each iteration.
4.2 The do-while Loop
Purpose
Executes the loop body at least once and then continues if the condition is true.
Syntax
do {
// Statements
} while (condition);
Example
int num = 0;
do {
System.out.println(“Number: ” + num);
num++;
} while (num < 3);
Explanation
The loop body executes once before checking the condition.
Useful when the code block must run at least once.
4.3 The for Loop
Purpose
Ideal for loops with a known number of iterations.
Syntax
for (initialization; condition; update) {
// Statements
}
Example
for (int i = 1; i <= 5; i++) {
System.out.println(“Iteration: ” + i);
}
Explanation
int i = 1: Initializes the counter.
i <= 5: Loop continues while this condition is true.
i++: Increments i after each iteration.
4.4 Nested Loops
Purpose
A loop inside another loop.
Useful for working with multi-dimensional data.
Example
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 2; j++) {
System.out.println(“i: ” + i + “, j: ” + j);
}
}
Output
i: 1, j: 1
i: 1, j: 2
i: 2, j: 1
i: 2, j: 2
i: 3, j: 1
i: 3, j: 2
4.5 Loop Control Statements
break Statement
Exits the loop immediately.
Example
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
System.out.println(“i: ” + i);
}
Output
i: 1
i: 2
continue Statement
Skips the current iteration and continues with the next one.
Example
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(“i: ” + i);
}
Output
i: 1
i: 2
i: 4
i: 5
4.6 Using Loops for Validation
Example
Scanner scanner = new Scanner(System.in);
int number;
do {
System.out.print(“Enter a positive number: “);
number = scanner.nextInt();
} while (number <= 0);
System.out.println(“You entered: ” + number);
4.7 Generating Random Numbers
Using java.util.Random Class
Generate random numbers using the Random class.
Example
import java.util.Random;
public class RandomExample {
public static void main(String[] args) {
Random random = new Random();
int randomNumber = random.nextInt(10); // 0 to 9
System.out.println(“Random number: ” + randomNumber);
}
}
Using Math.random()
Generates a random double between 0.0 and 1.0.
Example
double randomValue = Math.random();
System.out.println(“Random value: ” + randomValue);
4.8 Working with Files
Reading from a File
Example
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileReadExample {
public static void main(String[] args) {
try {
File file = new File(“input.txt”);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
} catch (FileNotFoundException e) {
System.out.println(“File not found.”);
}
}
}
Writing to a File
Example
import java.io.FileWriter;
import java.io.IOException;
public class FileWriteExample {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter(“output.txt”);
writer.write(“Hello, file!\n”);
writer.write(“Writing to a file in Java.\n”);
writer.close();
System.out.println(“Data written successfully.”);
} catch (IOException e) {
System.out.println(“An error occurred.”);
}
}
}
4.9 Common Errors and Debugging Tips
Infinite Loops
Forgetting to update the loop control variable.
Example:
int count = 1;
while (count <= 5) {
out.println(count);
// Missing count++ will result in an infinite loop.
}
File Handling Errors
File not found: Ensure the file path is correct.
Missing permissions: Verify access rights to the file.
Summary
Loops (while, do-while, for) allow repetition of tasks.
Control statements (break, continue) manage loop execution.
File handling involves reading from and writing to files.
Random numbers can be generated using Random or Math.random().