How can I write the code below in a loop?

1 view (last 30 days)
Pedro Alves
Pedro Alves on 28 Feb 2017
Answered: Harshal Ritwik on 12 Jun 2023
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.

Answers (1)

Harshal Ritwik
Harshal Ritwik on 12 Jun 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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!