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

2 views (last 30 days)
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

Accepted Answer

Star Strider
Star Strider on 7 Apr 2015
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.

More Answers (1)

Eric
Eric on 7 Apr 2015
Beautiful! Thanks for the help

Community Treasure Hunt

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

Start Hunting!