48.5k views
2 votes
Write a recursive function called drawtriangle that outputs lines of 'k' to form a right side up isosceles triangle. The function 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 'k' increases by 2 for every line drawn. For example, if the input of the program is 3, the function drawtriangle() outputs:

k
kkk
kkkkk

If the input of the program is 19, the function drawtriangle() outputs:

k
kkk
kkkkk
kkkkkkk
kkkkkkkkk
kkkkkkkkkkk
kkkkkkkkkkkkk
kkkkkkkkkkkkkkk
kkkkkkkkkkkkkkkkk
kkkkkkkkkkkkkkkkkkk

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

User Caktux
by
6.6k points

1 Answer

2 votes

Final answer:

To write a recursive function called drawtriangle that outputs lines of 'k' to form a right-side-up isosceles triangle, you can follow these steps: create a base case, call the drawtriangle function recursively, print the appropriate number of spaces, and print the 'k' character.

Step-by-step explanation:

To write a recursive function called drawtriangle() that outputs lines of 'k' to form a right-side-up isosceles triangle, you can use the following steps:

  1. Create a base case: If the base length is 1, simply print 'k'.
  2. Otherwise, call the drawtriangle() function recursively with a smaller base length minus 2.
  3. Print the appropriate number of spaces based on the current line number.
  4. Print the 'k' character the number of times based on the current line number.

Here is an example implementation of the drawtriangle() function in Python:

def drawtriangle(base_length):
if base_length == 1:
print('k')
else:
drawtriangle(base_length - 2)
spaces = ' ' * ((base_length - 1) // 2)
stars = 'k' * ((base_length + 1) // 2)
print(spaces + stars)
# Example usage
drawtriangle(3)
User EaranMaleasi
by
7.0k points