Chapter 9: Functions in C

Example 1, Page Number: FNC-5

In [1]:
def fact(k):
    p = 1
    for i in range(1,k+1):
        p = p * i
    return p

n = int(raw_input("\nEnter value to n and r : "))
r = int(raw_input(""))

ncr = fact(n)/ (fact(r)*fact(n-r))

print "\nValue of nCr = ",ncr
Enter value to n and r : 5
3

Value of nCr =  10

Example 2, Page Number: FNC-6

In [2]:
def big(a,b,c):
    if a > b:
        if a > c:
            return a
        else:
            return c
    else:
        if b > c:
            return b
        else:
            return c
        
t1 = int(raw_input("\nEnter three test scores : "))
t2 = int(raw_input(""))
t3 = int(raw_input(""))

a1 = int(raw_input("\nEnter three assignment scores : "))
a2 = int(raw_input(""))
a3 = int(raw_input(""))

total = big(t1,t2,t3) + big(a1,a2,a3)

print "\nTotal marks = ",total
Enter three test scores : 62
70
58

Enter three assignment scores : 17
21
23

Total marks =  93

Example 3, Page Number: FNC-8

In [5]:
import sys

def cosine(x):
    x = x * 3.14/180
    
    s = 0
    term = 1
    i = 0
    
    for k in range(1,15+1):
        s = s + term
        term = term*x*x*(-1)/((i+1)*(i+2))
        i = i + 2
    return s

x = 0
print "\n------------------------------------"
print "        x in degrees     cos(x)  "
print "------------------------------------"

while x <= 180:
    sys.stdout.write("\n\t%6.0f          %6.2f"%(x,cosine(x)))
    x = x + 30
    
print "\n------------------------------------"
------------------------------------
        x in degrees     cos(x)  
------------------------------------

	     0            1.00
	    30            0.87
	    60            0.50
	    90            0.00
	   120           -0.50
	   150           -0.87
	   180           -1.00
------------------------------------

Example 4, Page Number: FNC-9

In [6]:
def gcd(x,y):
    if x >= y:
        nr = x
        dr = y
    else:
        nr = y
        dr = x
    r = nr % dr
    while r != 0:
        nr = dr
        dr = r
        r = nr % dr
        
    return dr

a = int(raw_input("\nEnter three integers : "))
b = int(raw_input(""))
c = int(raw_input(""))

d1 = gcd(a,b)
d2 = gcd(a,c)
d3 = gcd(b,c)

if d1 == d2:
    if d1 == d3:
        print "\nGreatest common divisor is ",d1
    else:
        print "\nGreatest common divisor is ",gcd(d1,d3)
else:
    print "\nGreatest common divisor is ",gcd(d1,d2)
    
print "\n\nPress any key to continue..."
Enter three integers : 45
27
81

Greatest common divisor is  9


Press any key to continue...

Example 5, Page Number: FNC-10

In [7]:
def reverse(n):
    rn = 0
    while n > 0:
        r = n % 10
        rn = rn * 10 + r
        n = n / 10
    return rn

n = int(raw_input("\nEnter the integer : "))

print "\n",n," is erversed as ",reverse(n)
print "\nPress any key to continue..."
Enter the integer : 2846

2846  is erversed as  6482

Press any key to continue...

Example 6, Page Number: FNC-11

In [9]:
def compare(s1,s2):
    if s1 == s2:
        return 0
    if s1 > s2:
        return 1
    if s1 < s2:
        return -1
    
s1 = raw_input("\nEnter the first string : ")
s2 = raw_input("\nEnter the second string : ")

print "\nThe result is ",compare(s1,s2)
Enter the first string : MUMBAI

Enter the second string : MYSORE

The result is  -1

Example 7, Page Number: FNC-13

In [12]:
import sys

def amean(x,n):
    s = 0
    for i in range(0,n):
        s = s + x[i]
    return s/n

n = int(raw_input("\nHow many values? "))
print "\nEnter all values\n"

x = [0.0 for i in range(0,10)]

for i in range(0,n):
    x[i] = float(raw_input(""))
    
sys.stdout.write("\nArithmetic mean = %6.2f"%(amean(x,n)))
How many values? 6

Enter all values

3.1
3.8
3.6
4.0
3.4
3.8

Arithmetic mean =   3.62

Example 8, Page Number: FNC-14

In [2]:
def elem_sum(a,m,n):
    s = 0
    for i in xrange(m):
        for j in xrange(n):
            s = s + a[i][j]
           
    return s

m = int(raw_input("\nHow many rows and columns : "))
n = int(raw_input(""))

a = [[0 for i in range(0,10)] for i in range(0,10)]

print "\nEnter the matrix values\n"

for i in range(0,m):
    for j in range(0,n):
        a[i][j] = int(raw_input(""))


print "\nSum of all elements in the matrix = ",elem_sum(a,m,n)
How many rows and columns : 3
2

Enter the matrix values

2
3
4
2
0
1

Sum of all elements in the matrix =  12

Example 9, Page Number: FNC-15

In [20]:
def reverse(st):
    
    i = len(st) - 1
    rst = ""
    while i >= 0:
        rst = rst + st[i]
        i = i -1
        
    return rst

st = raw_input("\nEnter a string : ")

print "\n",st," is reversed as ",reverse(st)
Enter a string : NEW DELHI
 
NEW DELHI  is reversed as  IHLED WEN

Example 10, Page Number: FNC-16

In [21]:
def bi_search(x,n,s):
    flag = 0
    start = 0
    end = n
    
    while start < end and flag == 0:
        mid = (start+end)/2
        if x[mid] > s:
            end = mid
        else:
            if x[mid] < s:
                start = mid + 1
            else:
                flag = 1
    return flag

n = int(raw_input("\nHow many numbers ? "))

print "\nEnter all numbers in the list\n"

for i in range(0,n):
    x[i] = int(raw_input(""))
    
s = int(raw_input("\nEnter the number to be searched : "))

if bi_search(x,n,s):
    print "\nThe number ",s," is present in the list"
else:
    print "\nThe number ",s," is not present in the list"
How many numbers ? 10

Enter all numbers in the list

-3
8
13
19
21
25
26
29
35
42

Enter the number to be searched : 19

The number  19  is present in the list

Example 11, Page Number: FNC-19

In [22]:
def fact(k):
    if k == 1:
        return 1
    else:
        return k*fact(k-1)
    
n = int(raw_input("\nEnter values to n and r : "))
r = int(raw_input(""))

ncr = fact(n)/(fact(r)*fact(n-r))

print "\nValue of nCr = ",ncr
Enter values to n and r : 5
3

Value of nCr =  10

Example 12, Page Number: FNC-20

In [24]:
import sys

def power(x,n):
    if n == 1:
        return x
    else:
        return x*power(x,n-1)
    
x = float(raw_input("\nEnter value to x : "))
n = int(raw_input("\nEnter its power : "))

sys.stdout.write("\n%6.2f raise to %d is %6.2f"%(x,n,power(x,n)))
Enter value to x : 4.2

Enter its power : 3

  4.20 raise to 3 is  74.09

Example 13, Page Number: FNC-21

In [4]:
import sys


def fibo(t1,t2,count):
    if count >= n:
        return
    else:
        t3 = t1 + t2
        sys.stdout.write("%5d"%(t3))
        count = count + 1
        t1 = t2
        t2 = t3
        fibo(t1,t2,count)
        
n = int(raw_input("\nHow many terms to be printed ? "))
t1 = 0
t2 = 1

print "\nThe first ",n," terms in Fibonacci series are\n"
sys.stdout.write("%5d %5d"%(t1,t2))

count = 2
fibo(t1,t2,count)
How many terms to be printed ? 10

The first  10  terms in Fibonacci series are

    0     1    1    2    3    5    8   13   21   34

Example 14, Page Number: FNC-28

In [3]:
import sys

def matadd():
    for i in xrange(m):
        for j in xrange(n):
            c[i][j] = a[i][j] + b[i][j]
            
m = int(raw_input("\nHow many rows and columns ?"))
n = int(raw_input(""))

a = [[0 for i in range(0,10)]for i in range(0,10)]
b = [[0 for i in range(0,10)]for i in range(0,10)]
c = [[0 for i in range(0,10)]for i in range(0,10)]

#Read matrices
print "\nEnter A matrix values\n"
for i in range(0,m):
    for j in range(0,n):
        a[i][j] = int(raw_input(""))
        
print "\nEnter B matrix values\n"
for i in range(0,m):
    for j in range(0,n):
        b[i][j] = int(raw_input(""))

matadd()

print "\nResultant matrix is \n"
for i in range(0,m):
    for j in range(0,n):
        sys.stdout.write("%5d"%(c[i][j]))
    sys.stdout.write("\n")
How many rows and columns ?2
2

Enter A matrix values

2
-2
0
4

Enter B matrix values

6
2
4
-5

Resultant matrix is 

    8    0
    4   -1

Example 15, Page Number: FNC-29

In [4]:
import sys

def matmul():
    for i in xrange(m):
        for j in xrange(l):
            c[i][j] = 0
            for k in xrange(n):
                c[i][j] = c[i][j] + a[i][k] * b[k][j]
            
m = int(raw_input("\nEnter order of A matrix (m x n) : "))
n = int(raw_input(""))


a = [[0 for i in range(0,10)]for i in range(0,10)]
b = [[0 for i in range(0,10)]for i in range(0,10)]
c = [[0 for i in range(0,10)]for i in range(0,10)]

#Read matrices
print "\nEnter A matrix values\n"
for i in range(0,m):
    for j in range(0,n):
        a[i][j] = int(raw_input(""))

n = int(raw_input("\nEnter order of B matrix (n x l) : "))
l = int(raw_input(""))

print "\nEnter B matrix values\n"
for i in range(0,n):
    for j in range(0,l):
        b[i][j] = int(raw_input(""))

matmul()

print "\nResultant matrix is \n"
for i in range(0,m):
    for j in range(0,l):
        sys.stdout.write("%5d"%(c[i][j]))
    sys.stdout.write("\n")
Enter order of A matrix (m x n) : 2
2

Enter A matrix values

2
-2
0
4

Enter order of B matrix (n x l) : 2
2

Enter B matrix values

6
2
4
-5

Resultant matrix is 

    4   14
   16  -20

Example 16, Page Number: FNC-31

In [5]:
import sys

at = [[0,0],[0,0],[0,0]]

def transpose():
    for i in xrange(m):
        for j in xrange(n):
            at[j][i] = a[i][j] 
            
m = int(raw_input("\nHow many rows and columns ?"))
n = int(raw_input(""))

print "\nEnter the matrix values\n"
for i in range(0,m):
    for j in range(0,n):
        a[i][j] = int(raw_input(""))

transpose()

print "\nTranspose of the matrix is \n"
for i in xrange(n):
    for j in xrange(m):
        sys.stdout.write("%5d"%(at[i][j]))
    sys.stdout.write("\n")
How many rows and columns ?2
3

Enter the matrix values

-3
6
0
3
2
8

Transpose of the matrix is 

   -3    3
    6    2
    0    8

Example 17, Page Number: FNC-32

In [7]:
import sys


def sort():
    for i in xrange(n):
        for j in range(i+1,n):
            if x[i] > x[j]:
                temp = x[i]
                x[i] = x[j]
                x[j] = temp
                
x = [0 for i in range(0,50)]
n = int(raw_input("\nHow many numbers ? "))
print "\nEnter the list of values\n"

for i in range(0,n):
    x[i] = int(raw_input(""))

sort()

print "\nThe sorted list is\n"

for i in xrange(n):
    sys.stdout.write("%5d"%(x[i]))
How many numbers ? 4

Enter the list of values

32
-10
20
5

The sorted list is

  -10    5   20   32
In [ ]: