필터 지우기
필터 지우기

How can I write the code below in a loop?

조회 수: 1 (최근 30일)
Pedro Alves
Pedro Alves 2017년 2월 28일
답변: Harshal Ritwik 2023년 6월 12일
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