While Loops | For Loops | Nested Iteration | Code Example | Hacks | Quiz |
Unit 4 - Iterations Examples
Iteration Examples
Iterating with a for
Loop Example
public class Main {
public static void main(String[] args) {
// An array of integers
int[] numbers = {12, 7, 19, 4, 21, 8, 14};
// Use a for loop to iterate over the array
for (int i = 0; i < numbers.length; i++) {
int number = numbers[i];
// Check if the number is even or odd
if (number % 2 == 0) {
System.out.println("Number " + number + " is even.");
} else {
System.out.println("Number " + number + " is odd.");
}
// Additional check for numbers greater than 10
if (number > 10) {
System.out.println("Number " + number + " is greater than 10.");
} else {
System.out.println("Number " + number + " is less than or equal to 10.");
}
// Separator for clarity in the output
System.out.println("-----------------------");
}
}
}
Main.main(null);
Refrence Types Example
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0;
int count = 0;
// Continue to ask the user for input until they enter a negative number
while (true) {
System.out.print("Enter a positive number (or a negative number to stop): ");
int number = scanner.nextInt();
// Check if the entered number is negative
if (number < 0) {
break; // Exit the loop
}
// Accumulate the sum
sum += number;
count++;
// Print the current total
System.out.println("Current total sum: " + sum);
}
// Check if any numbers were entered
if (count > 0) {
System.out.println("You entered " + count + " numbers. Final sum is: " + sum);
} else {
System.out.println("No positive numbers were entered.");
}
scanner.close(); // Close the scanner to prevent resource leaks
}
}
Main.main(null);