stars pattern using recursive function HELP
1 次查看(过去 30 天)
显示 更早的评论
My teacher is asking us to create a triangle of stars with a recursive function. Can someone help me ? I've got something but it's not a recursive function. This is what i have :
function [ x ] = Triangle( x )
for i = 1:x
for j = 1:x-i
x=fprintf(' ');
end
for c = 1:i;
x=fprintf('*');
end
fprintf('\n');
end
triangle(7)
*
**
***
****
*****
******
*******
0 个评论
回答(1 个)
Jan
2018-2-28
Do you know, what a recursive function is? You have to include a call to itself in the code. But this should not cause an infinite recursion, therefore you have to modify the inputs and outputs, such that the calling will end.
function Triangle(x)
disp(x)
if x > 0
Triangle(x - 1);
end
end
Now fill in your code to draw the stars.
By the way: repmat('*', 1, x) helps to create the string without a loop. See also:
sprintf('%20s', 'hello')
This fills in spaces on the left, such that the output has at least 20 characters.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!