Chapter 6- Arrays and Strings

Example-age1.cpp, Page no-182

In [1]:
Sum=0.0
age1=int(raw_input("Enter person 1 age: "))
Sum+=age1
age2=int(raw_input("Enter person 2 age: "))
Sum+=age2
age3=int(raw_input("Enter person 3 age: "))
Sum+=age3
age4=int(raw_input("Enter person 4 age: "))
Sum+=age4
age5=int(raw_input("Enter person 5 age: "))
Sum+=age5
print "Average age = %g" %(Sum/5)
Enter person 1 age: 23
Enter person 2 age: 40
Enter person 3 age: 30
Enter person 4 age: 27
Enter person 5 age: 25
Average age = 29

Example-age2.cpp, Page no-182

In [1]:
age=[int]*5 #integer array of size 5
Sum=0.0
for i in range(5):
    print "Enter person", i+1, "age: ",
    age[i]=int(raw_input())
for i in range(5):
    Sum+=age[i]
print "Average age = %g" %(Sum/5)
Enter person 1 age: 23
 Enter person 2 age: 40
 Enter person 3 age: 30
 Enter person 4 age: 27
 Enter person 5 age: 25
 Average age = 29

Example-nodup.c, Page no-184

In [1]:
flag=0
a=[float]*50
n=int(raw_input("Enter the size of a vector: "))
num=n
print "Enter the vector elements..."
for i in range(n):
    print "a[", i, "] = ? ",
    a[i]=int(raw_input())
for i in range(n-1):
    for j in range(i+1, n):
        if a[i]==a[j]:
            n=n-1
            for k in range(j, n):
                a[k]=a[k+1]
            flag=1
            j=j-1
if flag:
    print "vector has ", num-n, "duplicate elements=(s)."
    print "Vector after removing duplicates..."
    for i in range(n):
        print "a[", i, "] = ", a[i]
else:
    print "vector has no duplicate elements"
Enter the size of a vector: 6
Enter the vector elements...
a[ 0 ] = ? 1
 a[ 1 ] = ? 5
 a[ 2 ] = ? 6
 a[ 3 ] = ? 8
 a[ 4 ] = ? 5
 a[ 5 ] = ? 9
 vector has  1 duplicate elements=(s).
Vector after removing duplicates...
a[ 0 ] =  1
a[ 1 ] =  5
a[ 2 ] =  6
a[ 3 ] =  8
a[ 4 ] =  9

Example-elder.cpp, Page no-187

In [1]:
age=[float]*25
n=int(raw_input("How many persons are there in list <max-25>? "))
for i in range(n):
    print "Enter person", i+1, "age: ",
    age[i]=int(raw_input())
younger=age[0]
elder=age[0]
for i in range(n):
    if age[i]<younger:
        younger=age[i]
    elif age[i]>elder:
        elder=age[i]
print "Age of eldest person is", elder
print "Age of youngest person is: ", younger
How many persons are there in list <max-25>? 7
Enter person 1 age: 25
 Enter person 2 age: 4
 Enter person 3 age: 45
 Enter person 4 age: 18
 Enter person 5 age: 35
 Enter person 6 age: 23
 Enter person 7 age: 32
 Age of eldest person is 45
Age of youngest person is:  4

Example-bubble.cpp, Page no-189

In [2]:
age=[int]*25
n=int(raw_input("How many elements to sort <max-25>? "))
for i in range(n):
    print "Enter age[", i, "]: ",
    age[i]=int(raw_input())
for i in range(n-1):
    flag=1
    for j in range(n-1-i):
        if age[j]>age[j+1]:
            flag=0
            temp=age[j]
            age[j]=age[j+1]
            age[j+1]=temp
    if flag:
        break
print "Sorted list..."
for i in range(n):
    print age[i],
How many elements to sort <max-25>? 7
Enter age[ 0 ]: 3
 Enter age[ 1 ]: 5
 Enter age[ 2 ]: 9
 Enter age[ 3 ]: 4
 Enter age[ 4 ]: 2
 Enter age[ 5 ]: 1
 Enter age[ 6 ]: 6
 Sorted list...
1 2 3 4 5 6 9

Example-comb.cpp, Page no-190

In [6]:
SHRINKINGFACTOR=1.3
age=[int]*25
n=int(raw_input("How many elements to sort <max-25>? "))
for i in range(n):
    print "Enter age[", i, "]: ",
    age[i]=int(raw_input())
size=n
gap=size
while 1:
    gap=int(float(gap)/SHRINKINGFACTOR)
    if gap==0:
        gap=1
    elif (gap==9 or gap==10):
        gap=11
    flag=1
    top=size-gap
    for i in range(top):
        j=i+gap
        if age[i]>age[j]:
            flag=0
            temp=age[j]
            age[j]=age[i]
            age[i]=temp
    if(flag==1 and gap<=1):
        break
print "Sorted list..."
for i in range(n):
    print age[i],
How many elements to sort <max-25>? 7
Enter age[ 0 ]: 3
 Enter age[ 1 ]: 5
 Enter age[ 2 ]: 9
 Enter age[ 3 ]: 4
 Enter age[ 4 ]: 2
 Enter age[ 5 ]: 1
 Enter age[ 6 ]: 6
 Sorted list...
1 2 3 4 5 6 9

Example-matrix.cpp, Page no-193

In [1]:
a=[]
b=[]
c=[]
m, n=[int(x) for x in raw_input("Enter row and column size of matrix A: ").split()]
p, q=[int(x) for x in raw_input("Enter row and column size of matrix B: ").split()]
if(m==p and n==q):
    print "Matrices can be added or subtracted..."
    print "Enter matrix A elements..."
    for i in range(m):
        a.append([])
        for j in range(n):
            a[i].append(int(raw_input()))
    print "Enter matrix B elements..."
    for i in range(m):
        b.append([])
        for j in range(n):
            b[i].append(int(raw_input()))
    for i in range(m):
        c.append([])
        for j in range(n):
            c[i].append(a[i][j]+b[i][j])
    print "Sum of A and B matrices..."
    for i in range(m):
        for j in range(n):
            print c[i][j], 
        print ""
    for i in range(m):
        for j in range(n):
            c[i][j]=a[i][j]-b[i][j]
    print "Difference of A and B matrices..."
    for i in range(m):
        for j in range(n):
            print c[i][j], 
        print ""
Enter row and column size of matrix A: 3 3
Enter row and column size of matrix B: 3 3
Matrices can be added or subtracted...
Enter matrix A elements...
1
2
3
4
3
1
3
1
2
Enter matrix B elements...
3
2
1
3
3
2
1
2
1
Sum of A and B matrices...
4 4 4 
7 6 3 
4 3 3 
Difference of A and B matrices...
-2 0 2 
1 0 -1 
2 -1 1 

Example-name.cpp, Page-196

In [2]:
name=[None]*50
name=raw_input("Enter your name <49-max>: ")
print "Your name is", name
Enter your name <49-max>: Archana
Your name is Archana

Example-succ.cpp, Page no-196

In [3]:
msg="C to C++\nC++ to Java\nJava to..." #string with special characters
print "Please note the following messgae: "
print msg
Please note the following messgae: 
C to C++
C++ to Java
Java to...

Example-strlen.cpp, Page no-197

In [2]:
s1=[None]*25
s1=raw_input("Enter your name: ")
print "strlen( s1 ) :", len(s1) #length of string
Enter your name: Smrithi
strlen( s1 ): 7

Example-strcpy.cpp, Page no-198

In [4]:
s1=[None]*25
s2=[None]*25
s1=raw_input("Enter a string: ")
s2=s1 #copying string
print "strcpy( s2, s1 ):", s2
Enter a string: Garbage
strcpy( s2, s1 ): Garbage

Example-strcat.cpp, Page no-198

In [6]:
s1=[None]*40
s2=[None]*25
s1=raw_input("Enter string s1: ")
s2=raw_input("Enter string s2: ")
s1=s1+s2 #concatenating string
print "strcat( s1, s2 ):", s1
Enter string s1: C
Enter string s2: ++
strcat( s1, s2 ): C++

Example-strcmp, Page no-199

In [8]:
s1=[None]*25
s2=[None]*25
s1=raw_input("Enter string s1: ")
s2=raw_input("Enter string s2: ")
print "strcmp( s1, s2 ):",
if s1==s2: #comparing strings
    print s1, "is equal to", s2
elif s1>s2:
    print s1, "is greater than", s2
else: 
    print s1, "is less than", s2
Enter string s1: Computer
Enter string s2: Computing
strcmp( s1, s2 ): Computer is less than Computing

Example-uprlwr.cpp, Page no-199

In [4]:
s1=[None]*25
temp=[None]*25
s1=raw_input("Enter a string: ")
temp=s1
print "strupr(temp):", temp.upper() #Upper case
print "strlwr(temp):", temp.lower() #lower case
Enter a string: Smrithi
strupr(temp): SMRITHI
strlwr(temp): smrithi

Example-name.cpp, Page no-200

In [2]:
person=[[None]*10]*LEN
n=int(raw_input("How many persons ? "))
for i in range(n):
    print "Enter person", i+1, "name: ",
    person[i]=raw_input()
print "------------------------------------------------------"
print "P#  Person Name  Length  In lower case  In UPPER case"
print "------------------------------------------------------"
for i in range(n):
    print '{:>2}'.format(i+1),
    print '{:>15}'.format(person[i]),
    print '{:>2}'.format(len(person[i])),
    print '{:>15}'.format(person[i].lower()),
    print '{:>15}'.format(person[i].upper())
How many persons ? 5
Enter person 1 name: Anand
 Enter person 2 name: Vishwanath
 Enter person 3 name: Archana
 Enter person 4 name: Yadunandan
 Enter person 5 name: Mallikarnun
 ------------------------------------------------------
P#  Person Name  Length  In lower case  In UPPER case
------------------------------------------------------
 1           Anand  5           anand           ANAND
 2      Vishwanath 10      vishwanath      VISHWANATH
 3         Archana  7         archana         ARCHANA
 4      Yadunandan 10      yadunandan      YADUNANDAN
 5     Mallikarnun 11     mallikarnun     MALLIKARNUN

Example-lex.cpp, Page no-202

In [7]:
Str=["Anand", "Vishwanath", "Archana", "Yadunandan", "MalliKarjun"]
print 'The given strings are:'
for i in range(5):
    print Str[i]
k=1
while k<5: #sorting strings
    for i in range(1, 5-k+1):
        if Str[i-1]>Str[i]:
            str_temp=Str[i-1]
            Str[i-1]=Str[i]
            Str[i]=str_temp
    k=k+1
print 'Strings in lexicographical order are:'
for i in range(5):
    print Str[i]
The given strings are:
Anand
Vishwanath
Archana
Yadunandan
MalliKarjun
Strings in lexicographical order are:
Anand
Archana
MalliKarjun
Vishwanath
Yadunandan

Example Page no-204

In [1]:
Str="In pursuit of Mastering	C++"
count=0
i=0
print "The given string is:\n",Str
while(i<len(Str)):
    if Str[i]=='\t' or Str[i]==' ':
        count+=1
    i+=1
count+=1
print "The number of words given in the string is", count
The given string is:
In pursuit of Mastering	C++
The number of words given in the string is 5