Borrar filtros
Borrar filtros

How can I write the code below in a loop?

1 visualización (últimos 30 días)
Pedro Alves
Pedro Alves el 28 de Feb. de 2017
Respondida: Harshal Ritwik el 12 de Jun. de 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.

Respuestas (1)

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

Categorías

Más información sobre Logical en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by