stars pattern using recursive function HELP

6 vues (au cours des 30 derniers jours)
Jade  Corbeil
Jade Corbeil le 28 Fév 2018
Commenté : Jade Corbeil le 28 Fév 2018
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)
*
**
***
****
*****
******
*******

Réponses (1)

Jan
Jan le 28 Fév 2018
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.
  2 commentaires
Jan
Jan le 28 Fév 2018
Modifié(e) : Jan le 28 Fév 2018
This is easier than the loops:
fprintf('%10s\n', repmat('*, 1, x))
Or:
fprintf('%s%s\n', repmat(' ', 1, 10-x), repmat(' ', 1, x));
Most of all omit the "for i = 1:x" loop. Remember that you have replaced this loop by the recursion.
Jade  Corbeil
Jade Corbeil le 28 Fév 2018
Great thank you a lot !! :)

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by