Chapter 10: C Preprocessor

Example 10.1, Page number: 172

In [1]:
data = []
twice = []

# Calculation and result
for index in range (0, 10) :
   data.append(index)
   twice.append(2 * index)

print (data)
print (twice)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

Example 10.2, Page number: 173

In [2]:
data = []
twice = []

# Calculation and result
for index in range (0, 20) :
   data.append(index)
   twice.append(2 * index)

print (data)
print (twice)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38]

Example 10.3, Page number: 175

In [3]:
BIG_NUMBER = 10 * 10
index = 1

# Calculation and result
while (index < BIG_NUMBER) :
   index = index * 8
   print ('%d' % index)
8
64
512

Example 10.4, Page number: 176

In [4]:
FIRST_PART = 7
LAST_PART = 5
ALL_PARTS = FIRST_PART + LAST_PART

# Calculation and result
print ('The square of all the parts is %d' % (ALL_PARTS * ALL_PARTS))
The square of all the parts is 144

Example 10.5, Page number: 177

In [5]:
for i in reversed (range(10)) :
   print ('Hi there')
Hi there
Hi there
Hi there
Hi there
Hi there
Hi there
Hi there
Hi there
Hi there
Hi there

Example 10.6, Page number: 177

In [6]:
size = 10
fudge = size - 2

# Calculation and result
size = fudge
print ('Size is %d' % size)
Size is 8

Example 10.7, Page number: 178

In [7]:
import sys
value = 1

# Calculation and result
if (value < 0) :
   sys.exit()

print ('We did not die')
We did not die

Example 10.8, Page number: 184

In [8]:
def SQR (x) :
   return x * x
   
for counter in range (0, 5) :
   print ('x %d, x squared %d\n' % (counter + 1, SQR (counter + 1)))
x 1, x squared 1

x 2, x squared 4

x 3, x squared 9

x 4, x squared 16

x 5, x squared 25

Example 10.9, Page number: 184

In [9]:
counter = 0

# Function declaration, calculation and result
def SQR (x) :
   return x * x
   
while (counter < 5) :
   print ('x %d square %d\n' % (counter + 1, SQR (counter + 1)))
   counter += 1
x 1 square 1

x 2 square 4

x 3 square 9

x 4 square 16

x 5 square 25

Example 10.10, Page number: 185

In [10]:
def reciprocal (number) :
   return 1 / number
   
for counter in range (1, 10) :
   print ('1/%f = %f\n' % (counter, reciprocal (counter)))
1/1.000000 = 1.000000

1/2.000000 = 0.000000

1/3.000000 = 0.000000

1/4.000000 = 0.000000

1/5.000000 = 0.000000

1/6.000000 = 0.000000

1/7.000000 = 0.000000

1/8.000000 = 0.000000

1/9.000000 = 0.000000