Chapter 2- Moving from C to C++

Example-hello.c, Page no-32

In [1]:
print "Hello World" #printing a statement
Hello World

Example-hello.cpp, Page no-32

In [2]:
print "Hello World" #printing a statement
Hello World

Example-output.cpp, Page no-36

In [1]:
msg="C++ cout object"
sex='M'
age=24
number=420.5
print sex, 
print " ", age, " ", number
print msg
print '%d%d%d' %(1,2,3)
print number+1
print 99.99
M   24   420.5
C++ cout object
123
421.5
99.99

Example-read.cpp, Page no-38

In [4]:
name=[None]*25   #char name[25]
address=[None]*25 #char address[25]
name=raw_input("Enter name: ") #take input from user
age=int(raw_input("Enter Age: "))
address=raw_input("Enter address: ")
print "The data entered are: "
print "Name =", name
print "Age =", age
print "Address =", address
Enter name: Rajkumar
Enter Age: 24
Enter address: C-DAC-Bangalore
The data entered are: 
Name = Rajkumar
Age = 24
Address = C-DAC-Bangalore

Example-simpint.cpp, Page no-41

In [6]:
principle=int(raw_input("Enter Principle Amount: "))
time=int(raw_input("Enter time (in years): "))
rate=int(raw_input("Enter Rate of Interest: "))
SimpInt=(principle*time*rate)/100
print "Simple Interest =", SimpInt
total= principle + SimpInt
print "Total Amount =", total
Enter Principle Amount: 1000
Enter time (in years): 2
Enter Rate of Interest: 5
Simple Interest = 100
Total Amount = 1100

Example-area.cpp, Page no-42

In [1]:
PI=3.1452 
radius=float(raw_input("Enter Radius of Circle: "))
area=PI*radius*radius
print "Area of Circle =", area
Enter Radius of Circle: 2
Area of Circle = 12.5808

Example-disp.c, Page no-43

In [5]:
def display(msg): #pass by reference
    print msg
    msg="Misuse"
    return msg
string=[None]*15
string="Hello World"
string=display(string)
print string
Hello World
Misuse

Example-disp.cpp, Page No-44

In [6]:
def display(msg): #pass by value
    print msg
string=[None]*15
string="Hello World"
display(string)
print string
Hello World
Hello World

Example-global.cpp, Page no-45

In [2]:
num=20
def main():
    global num
    x=num
    num=10
    print "Local =", num
    print "Global =",x
    print "Global+Local =", x+num
main()
Local = 10
Global = 20
Global+Local = 30

Example-loop.cpp, Page no-45

In [3]:
counter=50
def main():
    global counter
    x=counter
    for counter in range(1, 10):
        print x/counter
main()
50
25
16
12
10
8
7
6
5

Example-var1.cpp, Page no-46

In [4]:
for i in range(5):
    print i
i+=1;
print i
0
1
2
3
4
5

Example-def2.cpp, Page no-46

In [1]:
a=10
def main():
    global a
    global_a=a
    print global_a
    a=20
    def temp():
        a=30
        print a
        print global_a
    temp()
    print a
    print global_a
main()
10
30
10
20
10

Example-refvar.cpp, Page no-48

In [1]:
a=z=1
b=2
c=3
print "a=",a, "b=", b, "c=", c, "z=", z
a=z=b
print "a=",a, "b=", b, "c=", c, "z=", z
a=z=c
print "a=",a, "b=", b, "c=", c, "z=", z
print "&a=", hex(id(a)),"&b=", hex(id(b)) , "&c=", hex(id(c))
a= 1 b= 2 c= 3 z= 1
a= 2 b= 2 c= 3 z= 2
a= 3 b= 2 c= 3 z= 3
&a= 0x1d95f68L &b= 0x1d95f80L &c= 0x1d95f68L

Example-reftest.cpp, Page no-49

In [3]:
from ctypes import c_int, pointer
n=c_int(100)
p=pointer(n)
m=p[0]
print "n =", n.value, "m =", m, "*p =", p[0]
k=c_int(100)
p=pointer(k)
k.value=200
print "n =", n.value, "m =", m, "*p =", p[0]
n = 100 m = 100 *p = 100
n = 100 m = 100 *p = 200

Example-newmax.cpp, Page no-50

In [1]:
def Max(a, b):
    if(a>b):
        return a
    else:
        return b
x, y=[int(x) for x in raw_input("Enter two integers: ").split()] #takes input in a single line separated by white space
print "Maximum =", Max(x,y)
Enter two integers: 10 20
Maximum = 20

Example-swap.cpp, Page no-53

In [3]:
def swap (x, y): #pass by reference
    i=x
    x=y
    y=i
    return x, y
a, b=[int(x) for x in raw_input("Enter two integers <a, b>: ").split()]
(a,b)=swap(a, b)
print "On swapping <a, b>:", a, b 
Enter two integers <a, b>: 2 3
On swapping <a, b>: 3 2

Example-square.cpp, Page no-54

In [1]:
def square(x):
    x=x*x
    return x
num=float(raw_input('Enter a number <float>: '))
print 'Its square =', square(num)
Enter a number <float>: 5.5
Its square = 30.25

Example-show.c, Page no-56

In [7]:
def show_integer(val):
    print "Integer: ", val
def show_double(val):
    print "Double: ", val
def show_string(val):
    print "String: ", val
show_integer(420)
show_double(3.1415)
show_string("Hello World\n!")
Integer:  420
Double:  3.1415
String:  Hello World
!

Example-Show.cpp, Page no-56

In [1]:
def show(val): #function overloading
    if (isinstance(val, int)):
        print "Integer: ", val
    if (isinstance(val, float)):
        print "Double: ", val
    if(isinstance(val, str)):
        print "String: ", val
show(420)
show(3.1415)
show("Hello World\n!")
Integer:  420
Double:  3.1415
String:  Hello World
!

Example-prnstr.cpp, Page no-58

In [2]:
def showstring(string="Hello World!"): #default arguments
    print string
showstring("Here is an explicit argument")
showstring()
Here is an explicit argument
Hello World!

Example-defarg1.cpp, Page no-59

In [3]:
import sys
def PrintLine(ch='-', RepeatCount=70): #default arguments
    print "\n"
    for i in range(RepeatCount):
        sys.stdout.write(ch)
PrintLine()
PrintLine('!')
PrintLine('*', 40)
PrintLine('R', 55)

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

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

****************************************

RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR

Example-defarg2, Page no-59

In [4]:
import sys
def PrintLine(ch='-', RepeatCount=70, nLines=1): #default arguments
    for j in range(nLines):
        print "\n"
        for i in range(RepeatCount):
            sys.stdout.write(ch)
PrintLine()
PrintLine('!')
PrintLine('*', 40)
PrintLine('R', 55)
PrintLine('&', 25, 2)

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

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

****************************************

RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR

&&&&&&&&&&&&&&&&&&&&&&&&&

&&&&&&&&&&&&&&&&&&&&&&&&&

Example-date1.cpp, Page no-61

In [1]:
from collections import namedtuple
struct_date = namedtuple('struct_date', 'day month year')
d1 = struct_date(26, 3, 1958)
d2 = struct_date(14, 4, 1971)
d3 = struct_date(1, 9, 1973)
print "Birth Date of the First Author:", 
print "%s-%s-%s" %(d1.day, d1.month, d1.year)
print "Birth Date of the Second Author:", 
print "%s-%s-%s" %(d2.day, d2.month, d2.year)
print "Birth Date of the Third Author:",
print "%s-%s-%s" %(d3.day, d3.month, d3.year)
Birth Date of the First Author: 26-3-1958
Birth Date of the Second Author: 14-4-1971
Birth Date of the Third Author: 1-9-1973

Example-date2.cpp, Page no-63

In [1]:
from ctypes import Structure, c_int
class date(Structure):
    _fields_=[("day", c_int),("month", c_int),("year",c_int)]
    def show(self):
            print "%s-%s-%s" %(self.day, self.month, self.year)
d1=date(26, 3, 1958)
d2 = date(14, 4, 1971)
d3 = date(1, 9, 1973)
print "Birth Date of the First Author:", 
d1.show()
print "Birth Date of the Second Author:", 
d2.show()
print "Birth Date of the Third Author:",
d3.show()
Birth Date of the First Author: 26-3-1958
Birth Date of the Second Author: 14-4-1971
Birth Date of the Third Author: 1-9-1973

Example-cast.cpp, Page no-65

In [1]:
a=int
b=420.5
print "int(10.4) =", int(10.4)
print "int(10.99) =", int(10.99)
print "b =", b
a=int(b)
print "a = int(b) =", a
b=float(a)+1.5
print "b = float(a)+1.5 =", b
int(10.4) = 10
int(10.99) = 10
b = 420.5
a = int(b) = 420
b = float(a)+1.5 = 421.5

Example-mswap.cpp, Page no-66

In [1]:
def swap(x, y):
    t=x
    x=y
    y=t
    return x, y
ch1, ch2=raw_input("Enter two Characters <ch1, ch2>: ").split()
ch1, ch2=swap(ch1, ch2)
print "On swapping <ch1, ch2>:", ch1, ch2
a, b=[int(x) for x in raw_input("Enter integers <a, b>: ").split()]
a, b=swap(a, b)
print "On swapping <a, b>:", a, b
c, d=[float(x) for x in raw_input("Enter floats <c, d>: ").split()]
c, d=swap(c, d)
print "On swapping <c, d>:", c, d
Enter two Characters <ch1, ch2>: R K
On swapping <ch1, ch2>: K R
Enter integers <a, b>: 5 10
On swapping <a, b>: 10 5
Enter floats <c, d>: 20.5 99.5
On swapping <c, d>: 99.5 20.5

Example-gswap.cpp, Page no-67

In [4]:
def swap(x, y):
    t=x
    x=y
    y=t
    return x, y
ch1, ch2=raw_input("Enter two Characters <ch1, ch2>: ").split()
ch1, ch2=swap(ch1, ch2)
print "On swapping <ch1, ch2>:", ch1, ch2
a, b=[int(x) for x in raw_input("Enter integers <a, b>: ").split()]
a, b=swap(a, b)
print "On swapping <a, b>:", a, b
c, d=[float(x) for x in raw_input("Enter floats <c, d>: ").split()]
c, d=swap(c, d)
print "On swapping <c, d>:", c, d
Enter two Characters <ch1, ch2>: R K
On swapping <ch1, ch2>: K R
Enter integers <a, b>: 5 10
On swapping <a, b>: 10 5
Enter floats <c, d>: 20.5 99.5
On swapping <c, d>: 99.5 20.5

Example-vector.cpp, Page no-72

In [1]:
def AddVectors(a, b, c, size):
    for i in range(size):
        c[i]=a[i]+b[i]
def ReadVector(vector, size):
    for i in range(size):
        vector[i]=int(raw_input())
def ShowVector(vector, size):
    for i in range(size):
        print vector[i],
vec_size=int(raw_input("Enter size of vector: "))
x=[int]*vec_size
y=[int]*vec_size
z=[int]*vec_size
print "Enter Elements of vector x: "
ReadVector(x, vec_size)
print "Enter Elements of vector y: "
ReadVector(y, vec_size)
AddVectors(x, y, z, vec_size)
print "Summation Vector z=a+b:",
ShowVector(z, vec_size)
del x
del y
del z
Enter size of vector: 5
Enter Elements of vector x: 
1
2
3
4
5
Enter Elements of vector y: 
2
3
1
0
4
Summation Vector z=a+b: 3 5 4 4 9

Example Page no-73

In [1]:
def area(s1, s2=None):#function overloading and default parameters
    if (isinstance(s1, int)):
        if(isinstance(s2, int)):
            return (s1*s2)
        else:
            return (s1*s1)
    elif (isinstance(s1, float)):
        return (3.14*s1*s1)
s=int(raw_input("Enter the side length of the square: "))
l, b=[int(x) for x in raw_input("Enter the length and breadth of the rectangle: ").split()]
r=float(raw_input("Enter the radius of the circle: "))
print "Area of square = ", area(s)
print "Area of rectangle = ", area(l, b)
print "Area of circle = ", area(r)
Enter the side length of the square: 2
Enter the length and breadth of the rectangle: 2 4
Enter the radius of the circle: 2.5
Area of square =  4
Area of rectangle =  8
Area of circle =  19.625