Flip stars pattern using recursive function HELP
4 ビュー (過去 30 日間)
古いコメントを表示
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?
0 件のコメント
回答 (1 件)
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 件のコメント
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 Exchange で String についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!