# Chapter 6 : Iteration¶

### example 6.1 page no :56¶

In [1]:
'''
example 6.1 page no :56
'''

def countdown (n):
while (n > 0):
print n
n = n-1
print "Blastoff!"
return 0

countdown(5)

5
4
3
2
1
Blastoff!

Out[1]:
0

### example 6.2 page no :57¶

In [2]:
'''
example 6.2 page no :57
'''

def sequence (n):
while (n != 1):
print n
if (n%2 == 0):
n = n / 2
else:
n = n*3 + 1

sequence(10)

10
5
16
8
4
2


### example 6.3 page no :58¶

In [3]:
'''
example 6.3 page no :58
'''
import math
x = 1.0
while (x < 10.0):
print x , "\t" , math.log(x)
x = x + 1.0

1.0 	0.0
2.0 	0.69314718056
3.0 	1.09861228867
4.0 	1.38629436112
5.0 	1.60943791243
6.0 	1.79175946923
7.0 	1.94591014906
8.0 	2.07944154168
9.0 	2.19722457734


### example 6.4 page no :59¶

In [4]:
'''
example 6.4 page no :59
'''
import math
x = 1.0
while (x < 10.0):
print x , "\t" , math.log(x) / math.log(2.0)
x = x + 1.0

1.0 	0.0
2.0 	1.0
3.0 	1.58496250072
4.0 	2.0
5.0 	2.32192809489
6.0 	2.58496250072
7.0 	2.80735492206
8.0 	3.0
9.0 	3.16992500144


### example 6.5 page no :59¶

In [5]:
'''
example 6.5 page no :59
'''
import math
x = 1.0;
while (x < 100.0):
print x , "\t" , math.log(x) / math.log(2.0)
x = x * 2.0

1.0 	0.0
2.0 	1.0
4.0 	2.0
8.0 	3.0
16.0 	4.0
32.0 	5.0
64.0 	6.0


### example 6.6 page no: 60¶

In [6]:
'''
example 6.6 page no: 60
'''

i = 1;
while (i <= 6):
print 2*i ,
i = i + 1;

2 4 6 8 10 12


### example 6.7 page no:60¶

In [7]:
'''
example 6.7 page no:60
'''

def printMultiples (n):
i = 1
while (i <= 6):
print n*i,
i = i + 1;

printMultiples(3)

3 6 9 12 15 18


### example 6.8 page no:61¶

In [8]:
'''
example 6.8 page no:61
'''

def printMultiples (n):
i = 1
while (i <= 6):
print n*i,
i = i + 1;
print ''

i = 1;
while (i <= 6):
printMultiples (i);
i = i + 1;

1 2 3 4 5 6
2 4 6 8 10 12
3 6 9 12 15 18
4 8 12 16 20 24
5 10 15 20 25 30
6 12 18 24 30 36


### example 6.9 page no: 62¶

In [9]:
'''
example 6.9 page no: 62
'''

def printMultiples (n):
i = 1
while (i <= 6):
print n*i,
i = i + 1;
print ''

def printMultTable ():
i = 1;
while (i <= 6):
printMultiples (i)
i = i + 1

printMultTable()

1 2 3 4 5 6
2 4 6 8 10 12
3 6 9 12 15 18
4 8 12 16 20 24
5 10 15 20 25 30
6 12 18 24 30 36


### example 6.10 page no :63¶

In [10]:
'''
example 6.10 page no :63
'''

def printMultiples (n):
i = 1
while (i <= 6):
print n*i,
i = i + 1;
print ''

def printMultTable (high):
i = 1;
while (i <= high):
printMultiples (i);
i = i + 1;

printMultTable(4)

1 2 3 4 5 6
2 4 6 8 10 12
3 6 9 12 15 18
4 8 12 16 20 24


### example 6.11 page no :64¶

In [11]:
'''
example 6.11 page no :64
'''

def printMultiples(n,high):
i = 1;
while (i <= high):
print n*i ,
i = i + 1;
print ''

def printMultTable (high):
i = 1;
while (i <= high):
printMultiples (i, high)
i = i + 1;

printMultTable(5)

1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25

In [ ]: