Flip stars pattern using recursive function HELP

4 ビュー (過去 30 日間)
Daniel Mendoza
Daniel Mendoza 2020 年 2 月 27 日
コメント済み: Geoff Hayes 2020 年 2 月 28 日
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?

回答 (1 件)

Geoff Hayes
Geoff Hayes 2020 年 2 月 27 日
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 件のコメント
Daniel Mendoza
Daniel Mendoza 2020 年 2 月 27 日
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.
Geoff Hayes
Geoff Hayes 2020 年 2 月 28 日
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

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeString についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by