clc clear all % Structure Examples the for-end loop %% Example 1 disp('for-end loop Example 1') % i=1,2,3,4,5,6,7,8,9,10 for i=1:1:10 fprintf(' i=%g\n',i) end disp(' ') %% Example 2 disp('for-end loop Example 2') % i=1,3,5,7,9 for i=1:2:10 fprintf(' i=%g\n',i) end disp(' ') %% Example 3 disp('for-end loop Example 3') % i=10,9,8,7,6,5,4,3,2,1 for i=10:-1:1 fprintf(' i=%g\n',i) end disp(' ') % Structure Examples for the while-end loop %% Example 4 disp('for-end loop Example 4') for i=3:2:11 h=i^2; fprintf('\nSquare of %g is %g',i,h) end disp(' ') %% Example 1 disp('while-end loop Example 1') j=1; % starting point of j, so the loop will start while j<=10 fprintf(' j=%g\n',j) j=j+1; % increase the count of j to avoid an infinite loop end disp(' ') %% Example 2 disp('while-end loop Example 2') j=1; while j<=10 fprintf(' j=%g\n',j) j=j+2; end disp(' ') %% Exmaple 3 disp('while-end loop Example 3') j=10; while j>0 fprintf(' j=%g\n',j) j=j-1; end disp(' ') %% Example 4 disp('while-end loop Example 4') i=3 while i<=11 h=i^2; fprintf('\nSquare of %g is %g',i,h) i=i+2; end disp(' ')