Use nested loops and formatted print statements to reproduce the following printed table of numbers.

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
My current code is this:
clear;
for i=1:10;
for j=1:10
fprintf( '%5d',j);
end
fprintf('\n');
end;
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

 채택된 답변

You’re almost there. You have to set the upper limit of your ‘j’ loop to be the current value of ‘i’:
for i=1:10;
for j=1:i
fprintf( '%5d',j);
end
fprintf('\n');
end;
By the way, it is generally not a good idea to use ‘i’ and ‘j’ as variables, including loop counters. MATLAB uses them for its imaginary operators, and using them as variables can cause confusion in those instances.

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2015년 4월 7일

댓글:

2015년 4월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by