Date: 31/03/2018 10:00 AM Day: Saturday Section Num.: (05)

Loops

• For Loop

>> for i=1:5

disp(i)

end

1

2

3

4

5

--------------------------------------------

>> for i=1:2:5

disp(i)

end

1

3

5

--------------------------------------------

• Prints even numbers from 1 to 10

>> for i=2:2:10

disp(i)

end

--------------------------------------------

• Prints odd numbers from 1 to 10

>> for i=1:2:10

disp(i)

end

--------------------------------------------

• Summation odd numbers from 1 to 100

>> sum = 0;

>> for i=1:2:100

sum = sum + i;

end

>> sum

sum =

2500

--------------------------------------------

• Factorial of n

>> n = 5;

>> f = 1;

>> for i=1:n

f = f*i;

end

>> f

f =

120

--------------------------------------------

• Print all numbers from 1 to 35 except divided by 7

>> for i=1:35

if(mod(i,7)~=0) disp(i)

end

end

--------------------------------------------

• Print all numbers from 1 to 35 except divided by 7 and 5

>> for i=1:35

if(mod(i,7)~=0 & mod(i,5)~=0)

disp(i)

end

end

• Nested Loop For

for i=1:3

for j=1:3

disp ([i j])

end

end

1     1

1     2

1     3

2     1

2     2

2     3

3     1

3     2

3     3