How can I write the code below in a loop?
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
My goal is to write a function that prints a pyramid of integers in a triangle shape given the number of rows as input. I wrote:
function pyramid = pyramid(rows)
if rows == 1
fprintf(' 1')
elseif rows == 2
fprintf(' 1 \n 123')
elseif rows == 3
fprintf(' 1 \n 123 \n 12345')
elseif rows == 4
fprintf(' 1 \n 123 \n 12345 \n 1234567')
elseif rows == 5
fprintf(' 1 \n 123 \n 12345 \n 1234567 \n 123456789')
else
fprintf('Enter number of rows smaller that 5')
end
This fulfills my goal, if the number of rows is up to 5. However, I'd like to do this in a loop and automatically instead of manually inserting the spaces as I did.
Thank you in advance.
0 Commenti
Risposte (1)
Harshal Ritwik
il 12 Giu 2023
Hi,
As per my understanding of your question you want to convert the switch case statement into a loop statement so that you don’t need to enter the spaces manually and is done automatically. The following Code Snippet may help.
%Code Section: -
function pyramid = pyramid(rows)
for i = 1:rows %number of rows
st="";
for j= 1:rows-I %number of spaces in each row
st=st.append(" ");
end
for k= 1:2*i-1
st = st+k; %numbers to be entered
end
disp(st);
end
end
Please refer to the following documentation for more information
I hope it helps!
Thanks.
0 Commenti
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!