Chapter 22 : Sample C Programs(Lab Exercise)

Exercise 1: Page no.:L.4

In [5]:
#Area of Triangle

import math

#User Inputs
a,b,c=input("Enter three sides: ")

#calculation of semi perimeter
s=(a+b+c)/2

#Calculation of Area of Triangle
d=(s*(s-a)*(s-b)*(s-c))

area=math.sqrt(d)

#Result
print "Area of triangle = %f sq units \n"%area
Enter three sides: 5,6,7
Area of triangle = 14.696938 sq units 

Exercise 2: Page No. L.5

In [1]:
#Square root for the given value.

import math

#User Input
x=input("Enter the Value: ")

#Result
print "Square root of %.2f is: "%(x)

print math.sqrt(x)
Enter the Value: 81
Square root of 81.00 is: 
9.0

Exercise 3: Page.No.L.6

In [3]:
#Sum of the series 0+1+(1+2)+...+n

#User Input
n=input("Enter the Value of n : ")

#Variable Declaration
s=term=0
i=j=0

#Computing Values in loop
for i in range(n):
    for j in range(n):
        if j<=i:
            term=term+j
            j=j+1        
s=s+term
if i<=n:
    i=i+1
    
#Result
print "Sum of the series S= %d"%(s)
    
Enter the Value of n :5
Sum of the series S= 20

Exercise 4: Page No.:L.9

In [1]:
#Decimal into binary number.

n=input("Enter the decimal number: ")
s=n
k=[]

#Calculation
while (s>0):
    a=int(float(s%2))
    k.append(a)
    s=(s-a)/2
k.append(0)
bi=""

for j in k[::1]:
    bi=bi+str(j)

#Result
print('The binary value of %d is %s'%(n, bi))
Enter the decimal number: 14
The binary value of 14 is 01110

Exercise 5: Page No. L.10

In [10]:
#The given number is armstrong or not.

#Variable declaration
a=b=c=d=e=0

#User Input
a=input("Enter the Number: ")

#Assigning variable 'a' value to variable 'e'
e=a

#Calculation for finding Armstrong or not
while a>0:
    b=a%10
    c=b*b*b
    a=a/10
    d=c+d
 
#Result
if e==d:
    print "%d is an armstrong number. "%e
    
else:
    print "%d is not an armstrong number. "%e
Enter the Number: 153
153 is an armstrong number. 

Exercise 6: Page No.L.12

In [11]:
#Centigrade and Farenheit Values.


#Variable Declaration
c=f=cn=fn=0.0

#User Input1 for calculating farenheit
c=input("Enter temperature in centigrade : ")

#Farenheit Calculation
f=1.8*c+32

#Result1
print "Farenheit Equivalent is: %.1f\n" %(f)

#User input2 for calculating centigrade
fn=input("Enter temperature in farenheit : ")

#Centigrade Calculation
cn=(fn-32)/1.8

#Result2
print "Centigrade Equivalent is : %.1f\n"%(cn)
Enter temperature in centigrade : 20
Farenheit Equivalent is: 68.0

Enter temperature in farenheit : 68
Centigrade Equivalent is : 20.0

Exercise 7: Page .no.L.13

In [12]:
#Converting Decimal value to binary number


#Variable declaration
bnum=digit=decimal=bina=base=0

#User input
bnum=input("Enter the binary number: ")

bina=bnum

while(bnum!=0):
    digit=bnum%10
    decimal=decimal+(digit<<base)
    base=base+1
    bnum=bnum/10
    
print "The binary equivalent of %d in decimal = %d"%(bina,decimal)
Enter the binary number: 1111
The binary equivalent of 1111 in decimal = 15

Exercise 8: Page no.L.15

In [22]:
#Reverse number of the given number.

#Function  Definition.
def rev(n):
    digit=rev_of=0
    while n!=0:
        digit=n%10
        rev_of=rev_of*10+digit
        n=n/10
    return rev_of

#Variable Declaration


#User input
p=input("Enter the number: ")

q=rev(p)

print "Reverse of %d is %d.\n"%(p,q)
Enter the number: 1234
Reverse of 1234 is 4321.

Exercise 9: Page no.L.17

In [29]:
#Square of given value

#Function definition
def square(y):
    return y*y

#User input
n=input("Enter the nth element : ")

#Calculation
for x in range(1,n+1):
     print "%d " %(square(x))
Enter the nth element : 8
1 
4 
9 
16 
25 
36 
49 
64 

Exercise 10: Page no.:L.18

In [34]:
#Maximum value of given numbers

#Function definition
def maximum(x,y,z):
    
    maxi=x
    if y>maxi:
        maxi=y
        if z>maxi:
            maxi=z
    return maxi
    
    
#User input
a,b,c=input("Enter three integers : ")

#Result
print "Maximum is : %d\n"%(maximum(a,b,c))


    
    
Enter three integers : 2,6,9
Maximum is : 9

Exercise 11: Page no.L.19

In [36]:
#Factorial of the given number using recursion.

#funtion declaration
def fact(n):
    if n==0:
        return 1
    else:
        return(n*fact(n-1))
    
#USer Input

n=input("Enter the number whose factorial is to be found: ")

#Result
print "The Factorial of %d is : %d \n"%(n,fact(n))
Enter the number whose factorial is to be found: 6
The Factorial of 6 is : 720 

Exercise 12: Page no.L.20

In [9]:
#Palindrome or not.

print "Enter the String to check palindrome or not \n"

#User Input

string = raw_input("Enter the String: ")

#reverse the string 

rev_string = reversed(string)

#Check if the string is palindrome or not

if list(rev_string) == list(string) :
    print "\nThe given string %s is a palindrome"%(string)
    
else:
    print "\nThe given string %s is not a palindrome"%(string)
Enter the String to check palindrome or not 

Enter the String: madam

The given string madam is a palindrome

Exercise 13: Page No. L.24

In [40]:
#Largest and smallest number in array

#User input
n= input("Enter the nth term of an array: ")

for i in range(0,n):
    a[i]=eval(raw_input())

#check if the given array is large or small.    
    for i in range(1,n):
        if a[i]>large:
           large=a[i]
            
        else:
           if a[i]<small:
              small=a[i]
       
         
print "Largest element in an array is: %.2f"%large
print "Smallest element in an array is: %.2f"%small
Enter the nth term of an array: 4
12
79
50
-21
Largest element in an array is: 79.00
Smallest element in an array is:-21.00

Exercise 14: Page no. L.26

In [47]:
#Given array in ascending order

#User Input
n=input("Enter the last term of the array: ")

for i in range(0,n):
    a[i]=eval(raw_input())
for i in range(0,n-1):

    for j in range(i+1,n):
        if a[i]>a[j]:
            temp=a[i]
            a[i]=a[j]
            a[j]=temp
        
print "\nThe Elements in ascending order\n"

for i in range(0,n):
    print "%.2f"%a[i]
Enter the last term of the array: 6
23
14
-90
-67
48
01

The Elements in ascending order

-90.00
-67.00
1.00
14.00
23.00
48.00

Exercise 15: Page No. L.27

In [3]:
#Insert element in specified position in an array

import array

#User input
n=input("Enter the last value: ")
a=[0 for i in range(0,n) ]
print "Enter the elements of array: "
for i in range(0,n):
    a[i]=eval(raw_input())
    
#Getting inserting element and position from users
item=input("Enter the element to be inserted: ")
pos=input("Enter the position of insertion: ")
a.insert(pos,item)
#Result
print "\nElements after insertion is : "
for i in range(0,n+1):
    print "%.2f"%a[i]
    
Enter the last value: 5
Enter the elements of array: 
12
34
56
90
32
Enter the element to be inserted: 36
Enter the position of insertion: 4

Elements after insertion is : 
12.00
34.00
56.00
90.00
36.00
32.00

Exercise 16: Page.no.L.29

In [52]:
#Transpose of the matrix

#User Input

a=[]

n,m=input("Enter the Row and Columns: ")
print "Enter the elements of matrix:"
for i in range(n):
    a.append([])
    
    for j in range(m):
        element=input()
        a[i].append(element)

#print matrix
print "\nElements in matrix: "
for i in range(n):
    for j in range(m):
        print a[i][j],
    print '\n'


#generate transpose
transpose=[]
for j in range(m):
    transpose.append([])
    for i in range (n):
        b=a[i][j]
        transpose[j].append(b)

#print transpose
print "Transpose of the matrix is: "
for i in range (m):
    for j in range (n):
        print transpose[i][j],
    print '\n'
Enter the Row and Columns: 3,3
Enter the elements of matrix:
1
2
3
4
5
6
7
8
9

Elements in matrix: 
1 2 3 

4 5 6 

7 8 9 

Transpose of the matrix is: 
1 4 7 

2 5 8 

3 6 9 

Exercise 17: Page no. L.32

In [80]:
#Program to find sum of an array matrix
#Array Declaration

a=[]
b=[]
c=[[0 for i in xrange(0,5)] for i in xrange(0,5)]
#User Input1
n,m=input("Enter the Row and Columns of A Matrix: ")
print "Enter the elements of A matrix:"
for i in range(n):
    a.append([])
    
    for j in range(m):
        element=input()
        a[i].append(element)

#print matrix1
print "\nElements in A matrix: "
for i in range(n):
    for j in range(m):
        print a[i][j],
    print '\n'

    
#User Input 2
p,q=input("Enter the Row and Columns of B Matrix: ")
print "Enter the elements of B matrix:"
for i in range(p):
    b.append([])
    
    for j in range(q):
        element=input()
        b[i].append(element)

#print matrix 2
print "\nElements in B matrix: "
for i in range(p):
    for j in range(q):
        print b[i][j],
    print '\n'

#Addition of array in matrix    
for i in range(n):
    for j in range(m):
        c[i][j] += a[i][j] + b[i][j]

#Result
print "\nThe Sum of A and B matrix: "
for i in range(n):
    for j in range(m):
        print "%5d"%c[i][j],
    print '\n'
Enter the Row and Columns of A Matrix: 3,3
Enter the elements of A matrix:
1
2
3
4
5
6
7
8
9

Elements in A matrix: 
1 2 3 

4 5 6 

7 8 9 

Enter the Row and Columns of B Matrix: 3,3
Enter the elements of B matrix:
1
2
3
4
5
6
6
7
4

Elements in B matrix: 
1 2 3 

4 5 6 

6 7 4 


The Sum of A and B matrix: 
    2     4     6 

    8    10    12 

   13    15    13 

Exercise 18: Page No. :L.35

In [93]:
#Program to find Matrix Multiplication 
#Array Declaration

a=[]
b=[]
c=[[0 for i in xrange(0,5)] for i in xrange(0,5)]

while True:
#User Input1
    n,m=input("Enter the Row and Columns of A Matrix: ")
    p,q=input("Enter the Row and Columns of B Matrix: ")
    if (n==m&p==q):
        print "Enter the elements of A matrix:"   
        for i in range(n):
            a.append([]) 
            for j in range(m):
                element=input()
                a[i].append(element)
#print matrix1
        print "\nElements in A matrix: "
        for i in range(n):
            for j in range(m):
                print a[i][j],
            print '\n'
   
#User Input 2    
        print "Enter the elements of B matrix:"
        for i in range(p):
            b.append([])
            for j in range(q):
                element=input()
                b[i].append(element)

#print matrix 2
        print "\nElements in B matrix: "
        for i in range(p):
            for j in range(q):
                print b[i][j],
            print '\n'

#Multiplication of array in matrix    
        for i in range(0,m):
            for j in range(0,n):
                c[i][j] = 0
                for k in range(0,n):
                    c[i][j] += a[i][k] * b[k][j]
        
#Result
        print "\nThe Multiplication of A and B matrix: "
        for i in range(n):
            for j in range(m):
                print "%5d"%c[i][j],
            print '\n'
        break
    else:
        print "The No. of rows and columns are not equal.\n"
Enter the Row and Columns of A Matrix: 3,3
Enter the Row and Columns of B Matrix: 2,2
The No. of rows and columns are not equal.

Enter the Row and Columns of A Matrix: 3,3
Enter the Row and Columns of B Matrix: 3,3
Enter the elements of A matrix:
1
2
3
4
5
6
7
8
9

Elements in A matrix: 
1 2 3 

4 5 6 

7 8 9 

Enter the elements of B matrix:
2
4
1
6
7
4
3
5
7

Elements in B matrix: 
2 4 1 

6 7 4 

3 5 7 


The Multiplication of A and B matrix: 
   23    33    30 

   56    81    66 

   89   129   102 

Exercise 19: Page No. L.38

In [43]:
#Student grade using structure

#User Input
n=input("Enter the number of students: ")

#Defining Structure
class std:
    no=0
    name = ''
    m1 = m2 = m3 =0
    total=avg=0.0
    grade= ''
    
s=[std() for i in range(0,n)]

#User Input
for i in range(0,n):
    print "\nEnter the student %d details"%(i+1)
    print "\n"
    s[i].no=int(input("Give Student Number: "))
    s[i].name=raw_input("Enter the Student Name: ")
    s[i].m1=int(input("Enter Student Mark1: "))
    s[i].m2=int(input("Enter Student Mark2: "))
    s[i].m3=int(input("Enter Student Mark3: "))


#Calculation    
    s[i].total = (s[i].m1 + s[i].m2 + s[i].m3)
    s[i].avg=(s[i].total / 3)
    if s[i].avg<=40:
        s[i].grade='D'
    elif s[i].avg<60:
        s[i].grade='C'
    elif s[i].avg<80:
        s[i].grade='B'
    else:
        s[i].grade='A'
        
#Result
print "\tStudent mark details.... \n"
print "Roll No\t Name \t\tMark1 \tMark2 \tMark3 \tTotal \tAverage \tGrade"
for i in range(0,n):
    print "%d\t"%(s[i].no),"%s\t\t"%(s[i].name), "%d\t"%(s[i].m1),"%d\t"%(s[i].m2),"%d\t"%(s[i].m3), "%.2f\t"%(s[i].total), "%.2f\t\t"%(s[i].avg), "%s\t"%(s[i].grade)
   
Enter the number of students: 2

Enter the student 1 details


Give Student Number: 100
Enter the Student Name: Venkat
Enter Student Mark1: 89
Enter Student Mark2: 87
Enter Student Mark3: 76

Enter the student 2 details


Give Student Number: 101
Enter the Student Name: Shankar
Enter Student Mark1: 87
Enter Student Mark2: 90
Enter Student Mark3: 67
	Student mark details.... 

Roll No	 Name 		Mark1 	Mark2 	Mark3 	Total 	Average 	Grade
100	Venkat		89	87	76	252.00	84.00		A	
101	Shankar		87	90	67	244.00	81.00		A	

Exercise 20: Page No. L.40

In [58]:
#Employee details using Union

#Defining Union

class union:
    name=""
    idno=0
    salary=0.0
    
desc=union()

desc.name="vinod"

print "Employee details:"

print "The name is %s\n"%(desc.name)
print "The idno is %d\n"%(desc.idno)
print "The salary is %6.2f\n"%(desc.salary)

desc.idno=10

print "Employe details:"

print "The name is %s\n"%(desc.name)
print "The idno is %d\n"%(desc.idno)
print "The salary is %6.2f\n"%(desc.salary)

desc.salary=6500.00

print "Employee details:"

print "The name is %s\n"%(desc.name)
print "The idno is %d\n"%(desc.idno)
print "The salary is %6.2f\n"%(desc.salary)
Employee details:
The name is vinod

The idno is 0

The salary is   0.00

Employe details:
The name is vinod

The idno is 10

The salary is   0.00

Employee details:
The name is vinod

The idno is 10

The salary is 6500.00

Exercise 21: Page No. L.41

In [66]:
#Swap the contents of two variable using pointer.

#swapping function.

def interchange(x,y):
    temp=x
    x=y
    y=temp
    return x,y

#User Input
a,b = input("Enter the values of A and B: ")
#Result before interchanging
print "a=%d b=%d\n"%(a,b)


#Result after interchanging
print "After interchanging: \n"

print "a=%d b=%d\n"%(interchange(a,b))
Enter the values of A and B: 23,56
a=23 b=56

After interchanging: 

a=56 b=23

Exercise 22: Page No.: L.43

In [4]:
#Concatenate two strings using Dynamic Memory Allocation 

s1= raw_input("Enter String One: ")
s2=raw_input("Enter String two: ")

s3=''
s3=s1+s2                    
#Result
print "Concatenated String: ", s1+s2
Enter String One: venkat
Enter String two: raman
Concatenated String:  venkatraman

Exercise 23: Page No. L.44

In [13]:
#program to store and print same data to and from the file.

#open file
fp=open("Text.txt","w")

#User Input
c=raw_input("Enter the Text: ")

#Store given input into a file "text.txt"
fp.write(c)

#Closing file
fp.close()

#Again open text.txt
fp=open("Text.txt", "r")

#display the content from the file "text.txt"
print "Displaying text from file:\n",c 
fp.close()
Enter the Text: VRB PUBLISHERS
Displaying text from file:
VRB PUBLISHERS

Exercise 24: Page No. L.46

In [23]:
#Program to count number of characters in a file.

#create a file
fp=open("str.txt","w")
c=""
print "Enter the Characters:"
print "Press ctrl+z to stop entry"

#User Input
c=raw_input()
#store input into the file
fp.write(c)
fp.close()

#Again open the file to read
fp=open("str.txt","r")

#Result
print "\n%s"%(c)
print "Number of characters in the file: ",len(c)
fp.close()
Enter the Characters:
Press ctrl+z to stop entry
vrb publishers private limited

vrb publishers private limited
Number of characters in the file:  30

Exercise 25: Page No.: L.48

In [19]:
#Program using Memory Allocation function

NULL=0
buffer_size=10

buffer1 = "BOMBAY"
print "Buffer of size %d created"%(buffer_size)
print "Buffer contains", buffer1
    

if buffer_size==NULL:
    print "Malloc failed"
    
else:
    print "Buffer size modified"
    print "Buffer still contains:", buffer1
    
buffer1="MUMBAI"
print "Buffer now contains:", buffer1
Buffer of size 10 created
Buffer contains BOMBAY
Buffer size modified
Buffer still contains: BOMBAY
Buffer now contains: MUMBAI