### Chapter 8 Code Examples

### MATLAB Code Examples

1 2 3 |
for j=1:4 j end |

1 2 3 |
for j=1:0.5:4 j end |

1 2 3 4 5 6 |
for j=1:4 for k=1:4 a(j,k)=j*k; end end a |

1 2 3 4 5 |
count=0; while (count < 4 ) count count=count+1; end |

### Python Code Examples

1 2 |
for j in range(4): print(j) |

1 2 3 4 |
import numpy as np a = np.array([1,2,3]) for j in a: print(j) |

1 2 3 4 |
count = 0 while (count < 4): print(count) count = count + 1 |

### Exercises

- Write a for loop that prints all integers from 1 to n.
- Write a for loop that prints all integers in reverse from n to 1.
- Write a while loop that prints all even numbers from 1 to 100.
- Write a while loop that prints all integers in reverse from n to 1.
- Write a loop that calculates the factorial of n (n! – the product of all positive integers less than or equal to n).