Flip stars pattern using recursive function HELP

I need to create a function that generates a star pattern like this (using a recursive fonction) :
*
**
***
****
*****
******
*******
I created this function :
function Triangle(x)
if x==0
fprintf('')
else
Triangle(x-1);
for i=1:x
fprintf('')
end
for j=1:x
fprintf('*')
end
fprintf('\n');
end
end
but my triangle is pointing to the left instead of to the right, what can I change so I get the correct output?

Answers (1)

Daniel - your code to print spaces (I think)
for i=1:x
fprintf('')
end
is not actually printing anything since the string is empty. You would need to include a single space character to get spaces to precede your star pattern. However, while that will "work" it won't be display what want since you will be printing x spaces and what you really want is to print m - x where m is the number of characters in the original string. So you will somehow need to pass that information down on each recursive step. One way to do this might be to nest the recursive function within Triangle so that it takes two inputs: x and m. For example,
function Triangle(x)
RecursiveTriangle(x,x);
function RecursiveTriangle(x,m)
% do something
end
end
The "do something" part of the code will be almost identical to what you have already, you just need to take into account the m.

2 Comments

thank you for the answer, but I still don't know how using m, I can change the orientation of my triangle? Sorry if my question seems ignorant, it's my first programming class.
Daniel - since this is homework, I can only give hints. But if your input (to the Triangle function) is 7, then
  • when you print 7 stars, you need 0 spaces
  • when you print 6 stars, you need 1 space
  • when you print 5 stars, you need 2 spaces
  • etc.
What is the pattern? What should the code to print your spaces look like?
for i=1:(???)
fprintf(' ');
end

Sign in to comment.

Categories

Asked:

on 27 Feb 2020

Commented:

on 28 Feb 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!