193k views
3 votes
13.19 : Drawing a right side up triangle

Write a recursive method called drawTriangle() that outputs lines of '*' to form a right side up isosceles triangle. Method drawTriangle() has one parameter, an integer representing the base length of the triangle. Assume the base length is always odd and less than 20. Output 9 spaces before the first '*' on the first line for correct formatting.

Hint: The number of '*' increases by 2 for every line drawn.

Ex: If the input of the program is:

3

the method drawTriangle() outputs:

*
***

Ex: If the input of the program is:

19

the method drawTriangle() outputs:

*
***
*****
*******
*********
***********
*************
***************
*****************
*******************

Note: No space is output before the first '*' on the last line when the base length is 19.

LabProgram.java

import java.util.Scanner;

public class LabProgram {

/* TODO: Write recursive drawTriangle() method here. */


public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int baseLength;

baseLength = scnr.nextInt();
drawTriangle(baseLength);

User Lightrek
by
8.5k points

1 Answer

3 votes

Final answer:

To draw a right-side up isosceles triangle using recursion, a recursive method called drawTriangle() can be defined. The method checks the base case, then recursively calls itself with a smaller base length. Finally, it prints the current line of the triangle, along with the appropriate number of '*' characters. The drawTriangle() method is called with the given base length to draw the right-side up isosceles triangle.

Step-by-step explanation:

To draw a right-side up isosceles triangle using recursion, we can define a recursive method called drawTriangle() with the following steps:

  1. Check the base case: if the base length is 1, simply print a single '*' character.
  2. For the recursive case, recursively call drawTriangle() with a base length of baseLength - 2. This will draw the smaller triangle above the current line, shifting it to the right by two spaces.
  3. After the recursive call, print the current line of the triangle, consisting of the appropriate number of '*' characters. To ensure correct formatting, add 9 spaces before the first '*' character on the first line, and decrease the number of spaces by 2 for each subsequent line.

Here is the Java code for the drawTriangle() method:

public static void drawTriangle(int baseLength) {
if (baseLength == 1) {
System.out.println(" *");
} else {
drawTriangle(baseLength - 2);
for (int i = 0; i <= (baseLength - 1) / 2; i++) {
System.out.print(" ");
}
for (int i = 0; i < baseLength; i++) {
System.out.print("*");
}
System.out.println();
}
}
User Andrew WC Brown
by
7.3k points