Java Exercise
Create a Java program that allows the user to enter a positive integer, and then the program should print the first N natural numbers (starting from 1) using for
, while
, and do-while
loops to iterate.
Requirements:
- The program should prompt the user to enter a positive integer.
- Use a
for
loop to print the first N natural numbers.
- Use a
while
loop to print the same numbers, but with a different structure.
- Finally, use a
do-while
loop to print the numbers in the same way.
- The program should work correctly for any positive integer entered.
Tips:
- Use
Scanner
to receive user input.
- Make sure loops don't generate an infinite loop.
View Example Code
1. Loop for
import java.util.Scanner;
public class LoopExample {
public static void main(String[] args) {
// Ask the user for a number
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = scanner.nextInt();
// For loop: Prints the first N natural numbers
System.out.println("Using for loop:");
for (int i = 1; i <= number; i++) {
System.out.println(i);
}
}
}
Output:
Enter a positive integer: 5
Using for loop:
1
2
3
4
5
2. Loop while
import java.util.Scanner;
public class LoopExample {
public static void main(String[] args) {
// Ask the user for a number
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = scanner.nextInt();
// While loop: Prints the first N natural numbers
System.out.println("Using while loop:");
int i = 1;
while (i <= number) {
System.out.println(i);
i++;
}
}
}
Output:
Enter a positive integer: 5
Using while loop:
1
2
3
4
5
3. Loop do-while
import java.util.Scanner;
public class LoopExample {
public static void main(String[] args) {
// Ask the user for a number
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = scanner.nextInt();
// Do-while loop: Prints the first N natural numbers
System.out.println("Using do-while loop:");
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= number);
}
}
Output:
Enter a positive integer: 5
Using do-while loop:
1
2
3
4
5
This code presents three examples of Java loops for printing the first N natural numbers. In each case, the program prompts the user to enter a positive number and then uses different types of loops to print the numbers from 1 to that number. In all three examples, the output is the same: if the user enters the number 5, the program will print the numbers 1 through 5.