How can I write the code below in a loop?

1 次查看(过去 30 天)
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.

回答(1 个)

Harshal Ritwik
Harshal Ritwik 2023-6-12
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.

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by