Contents

A04B.m - Nested For Loops

Print out a multiplication table to demonstrate the use of a nested for loop.

% maximum number to use in multiplication table
N = 13;

% print description to command window
fprintf('Multiplication Table\n')

% The outer loop cycles through the rows.
% The inner loop cycles along the columns of each row
% Because each loop executes N times, the total number of number printed
% will be N^2
for i=1:N
    for j=1:N
    	fprintf('%3i  ',i*j)  % prints a number without starting a new line
    end
    fprintf('\n')             % prints a carriage return to start a new line
end

Download L2ex4B.m

The outer loop cycles through the rows. The inner loop cycles along the columns of each row. Because each loop executes N times, the total number of number printed will be N^2.

Notice that the fprintf command uses '%3i' formatting to leave 3 spaces for the integer products. Without the 3, the multiplication table would not line up in neat rows. Try deleting the 3 and see what happens.

Output:

Multiplication Table
  1    2    3    4    5    6    7    8    9   10   11   12   13  
  2    4    6    8   10   12   14   16   18   20   22   24   26  
  3    6    9   12   15   18   21   24   27   30   33   36   39  
  4    8   12   16   20   24   28   32   36   40   44   48   52  
  5   10   15   20   25   30   35   40   45   50   55   60   65  
  6   12   18   24   30   36   42   48   54   60   66   72   78  
  7   14   21   28   35   42   49   56   63   70   77   84   91  
  8   16   24   32   40   48   56   64   72   80   88   96  104  
  9   18   27   36   45   54   63   72   81   90   99  108  117  
 10   20   30   40   50   60   70   80   90  100  110  120  130  
 11   22   33   44   55   66   77   88   99  110  121  132  143  
 12   24   36   48   60   72   84   96  108  120  132  144  156  
 13   26   39   52   65   78   91  104  117  130  143  156  169  

A04C.m - Another Pair of Nested For Loops

% get info from user
N = input('Enter number of rows:  ');

% The outer loop cycles through the rows.
% The inner loop prints the '*' along each row.
% Because the upper limit on the inner loop equals the index (i) of the outer
% loop, the number of '*' printed on each row will increases
for i=1:N
    for j=1:i
    	fprintf('*')    % prints an '*' without starting a new line
    end
    fprintf('\n')       % prints a carriage return to start a new line
end

Download L2ex4C.m

The outer loop in the above example is executed N times. The inner loop will first be executed once when i = 1 on the first row, twice when i=2 on the second row, and so on.

Output for N = 5:

*
**
***
****
*****


Monkey Home   |    Prev   |   Next