I have this assignment that's due tonight at midnight, but I have completed all but 1 part. The second triangle, I am having problems grasping the concept of nested loops I believe, but it's part of it. Anyways, here is question then code.
Write a Java program that reads positive integer n, 1 ≤ n ≤ 13, and plots 3 triangles of size n as shown below.
For n = 4, for instance, the program should plot: (works for n = 5 and n = 6 etc.)
triangle 1
1
2 3
4 5 6
7 8 9 10
triangle 2
_ _ _ 1
_ _ 3 2
_ 6 5 4
10 9 8 7
triangle 3
_ _ _ 1
_ _ 3 3 3
_ 5 5 5 5 5
7 7 7 7 7 7 7
import java.util.Scanner; class Loops { void plotTriangle1(int n) { int t = 1; for (int i = 1; i <= n; i++) { System.out.println(" "); for (int j = 1; j <= i; j++) { System.out.printf("%3d", t++); } System.out.println(); } } void plotTriangle2(int n) { int t = 1; for (int i = 1; i <= n; i++) { for (int k = 1; k <= i; k++) { } for (int j = 1; j <= i; j++) { System.out.printf("%3d",t++); } System.out.println(); } } void plotTriangle3(int n) { for (int i = 1; i <= n; i++) { System.out.println(); for(int j = 1;j <= (n-i);j++) { System.out.print(" "); } for (int j = 1; j <= 2*i-1; j++) { System.out.print(" "); System.out.printf("%3d",2*i-1); } System.out.println(); } } } public class Lab7 { public static void main(String[] args) { Scanner in = new Scanner(System.in); Loops myL = new Loops(); int n; System.out.print("Enter n(1-13):"); n = in.nextInt(); //myL.plotTriangle1(n); myL.plotTriangle2(n); //myL.plotTriangle3(n); } }
Currently compiles to this: Enter n(1-13):4
1
2 3
4 5 6
7 8 9 10
--- Update ---
Sorry for the question format of the triangles, I couldnt get the spacing to work so I used underscores to replicate the blank space on the forum. Thanks.