Question 1
public static void simpleWhileLoop() {
// Define constants
final int MIN_VALUE = 1;
final int MAX_VALUE = 10;
// Initialize counter variable
int num = MIN_VALUE;
// Loop until counter exceeds maximum value
while (num <= MAX_VALUE) {
// Print current number
System.out.println(num);
// Increment counter
num++;
}
}
Question 2
private static final int START_NUMBER = 1; // IDA
private static final int END_NUMBER = 10; // IDA
public static void simpleDoWhile() { // IDA
int counter = START_NUMBER; // IDA
do { // IDA
System.out.println(counter); // IDA
counter++; // IDA
} while (counter <= END_NUMBER); // IDA
}
Question 3
public void simpleForLoop() {
// Define constants
final int START = 1;
final int END = 10;
// Iterate from START to END and print each number
for (int i = START; i <= END; i++) {
System.out.println(i);
}
}
Question 4
private static final int START_NUMBER = 1; // IDA
public static void simpleDoWhile(int upperLimit) { // IDA
int counter = START_NUMBER; // IDA
do { // IDA
System.out.println(counter); // IDA
counter++; // IDA
} while (counter <= upperLimit); // IDA
}
Question 5
public void simpleForLoop(int upperLimit) { // IDA
final int START = 1; // IDA
for (int i = START; i <= upperLimit; i++) { // IDA
System.out.println(i); // IDA
} // IDA
}
Question 6
public static void simpleWhileLoop(int upperLimit) { // IDA
final int START_NUMBER = 1; // IDA
int counter = START_NUMBER; // IDA
while (counter <= upperLimit) { // IDA
System.out.println(counter); // IDA
counter++; // IDA
}
}
Question 7
private static final int QUIT_VALUE = 0; // IDA
public static void sumOfEven() { // IDA
Scanner scanner = new Scanner(System.in); // IDA
int sum = 0; // IDA
int number; // IDA
do {
System.out.print("Enter a number (0 to quit): \n"); // IDA
number = scanner.nextInt(); // IDA
if (number % 2 == 0 && number != QUIT_VALUE) { // IDA
sum += number;
}
} while (number != QUIT_VALUE); // IDA
System.out.println("The sum of even numbers is " + sum); // IDA
scanner.close();
}
Question 8
public static void sumOfOdd() {
int number;
int sum = 0;
// Create scanner
Scanner input = new Scanner(System.in);
// Start of do-while loop
do{
// Number input
System.out.print("Enter a number (0 to quit): \n");
number = input.nextInt();
// Check if the number is odd
if (number % 2 == 1) {
sum += number; // Add the odd number to the sum
}
} while (number != 0); // Loop until 0 is entered
// Print the sum of odd numbers
System.out.println("The sum of odd numbers is " + sum);
}