Chapter 8

Chapter 8 Code Examples

MATLAB Code Examples

for j=1:4
     j
end
for j=1:0.5:4
     j
end
for j=1:4
     for k=1:4
          a(j,k)=j*k;
     end
end
a
count=0;
while (count < 4 )
     count
     count=count+1;
end

Python Code Examples

for j in range(4):
     print(j)
import numpy as np
a = np.array([1,2,3])
for j in a:
     print(j)
count = 0
while (count < 4):
     print(count)
     count = count + 1

Exercises

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