222k views
4 votes
Write a Java program that prompts the user for an int n. You can assume that 1 ≤ n ≤ 9. Your program should use embedded for loops that produce the following output: 1 2 1 3 2 1 4 3 2 1 5 4 3 2 1 . . . n . . . 5 4 3 2 1 Your prompt to the user should be: Please enter a number 1...9 : Please note that your class should be named PatternTwo.

User Arxoft
by
5.6k points

1 Answer

1 vote

Final answer:

To create the desired pattern using embedded for loops in a Java program, prompt the user for an integer n and use two for loops to print the numbers in each row of the pattern.

Step-by-step explanation:

To write a Java program that prompts the user for an int n and produces the desired output, you can use embedded for loops. Start by using a for loop to iterate from 1 to n. Within this loop, use another for loop to iterate from the current value of n down to 1. Print the numbers in each iteration to create the pyramid-like pattern.

Here's an example implementation:

import java.util.Scanner;

public class PatternTwo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter a number 1...9 : ");
int n = scanner.nextInt();

for (int i = 1; i <= n; i++) {
for (int j = n; j >= 1; j--) {
if (j > i) {
System.out.print(" ");
} else {
System.out.print(j + " ");
}
}
System.out.println();
}
}
}
User ASMUIRTI
by
4.5k points