In: Computer Science
Write a program using a Scanner that asks the user for a number n between 1 and 9 (inclusive). The program prints a triangle with 2n - 1 rows. The first row contains only the square of 1, and it is right-justified. The second row contains the square of 2 followed by the square of 1, and is right justified. Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2 and 1, and so forth until n rows are printed. Starting at row n + 1, the squares between (n - 1) to 1 are printed, again right justified. Row n + 2 prints the squares between (n -2) to 1.
Assuming the user enters 4, the program prints the following triangle of 7 rows to the console
1 4 1 9 4 1 16 9 4 1 9 4 1 4 1 1
If the user enters 7, the following 13-row triangle is printed
1 4 1 9 4 1 16 9 4 1 25 16 9 4 1 36 25 16 9 4 1 49 36 25 16 9 4 1 36 25 16 9 4 1 25 16 9 4 1 16 9 4 1 9 4 1 4 1 1
Notes
Hint
Don't think of the output as a triangle. Think of it as two rectangular tables: one of the first n rows, the second of the last (n-1) rows.
Within each table, some cells are three spaces, some are one space and two digits, and some are two spaces and one digit.
Start by printing an entire table with each cell its appropriate square value. Then figure out how to replace the cells that should "empty" with three spaces instead of a number.
Finally, figure out how to print the one-digit numbers as two spaces and one digit, and the two-digit numbers as one space and two digits.
Grading Elements
/* Read the comments and see the output */
import java.util.Scanner; // Package for Scanner Class
class TriangleSolution { // Name of the Solution Class having main Method
public static void printTriangle(int n) { // Method to do the printing work based on input
for(int i=1;i<=n;i++){
for(int j=n+1;j>i;j--)
System.out.printf("%2s"," "); // Print space first
for(int k=i;k>=1;k--)
System.out.printf("%d ",k*k); // Print square of numbers
System.out.println(); // Print new line
}
for(int i=1;i<=n;i++){ // Do reverse work here
for(int j=1;j<=i+1;j++)
System.out.printf("%2s"," "); // Print space first
for(int k=n-i;k>=1;k--)
System.out.printf("%d ",k*k); // Print square of number
System.out.println();// Print new line
}
}
public static void main(String arg[]) { //main method or driver method
//Declare Scanner class for the input
Scanner sc = new Scanner(System.in);
int number; // Variable to read number from 1 to 9 inclusive
do {
System.out.print("Enter the Number: ");
number = sc.nextInt();
} while(!(number>=1 && number<=9));
printTriangle(number);
}
}
/* Here is output */