Problem Problem Write a program to prompt for the number of triangles and the he
ID: 3599590 • Letter: P
Question
Problem
Problem
Write a program to prompt for the number of triangles and the height of each triangle, then print out all the specified triangles.
The triangles should have the following format:
How many triangles: 2
The height of the triangle: 3
1 3 5
7 9
11
The height of the triangle: 4
1 3 5 7
9 11 13
15 17
19
Process finished with exit code 0
How many triangles: 3
The height of the triangle: 1
1
The height of the triangle: 3
1 3 5
7 9
11
The height of the triangle: 5
1 3 5 7 9
11 13 15 17
19 21 23
25 27
29
Process finished with exit code 0
Explanation / Answer
Implemented code in java, as no programming language is specified. Please comment if you want it in some other language.
code:
========
import java.util.Scanner;
public class Traingles {
public static void main(String[] args) {
System.out.println("How many triangles: ");
Scanner sc = new Scanner(System.in);
int inp = sc.nextInt(), hi;
for(int i=0; i<inp; i++) {
System.out.println("The height of the triangle: ");
hi = sc.nextInt();
triangle(hi);
}
System.out.println("Process finished with exit code 0");
}
public static void triangle(int h) {
int nums = 1;
for(int i=h; i>0; i--) {
for(int j=1;j<=i ; j++) {
System.out.print(nums +" ");
nums = nums+2;
}
System.out.println();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.