CS3401 Lab Manual Final
CS3401 Lab Manual Final
IV SEMESTER – R 2021
LABORATORY MANUAL
IQAC
ARASU ENGINEERING COLLEGE, KUMBAKONAM
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
VISION:
To be in the forefront of Computer Science and Engineering by producing competing
professional with innovative skills, moral values, and societal concerns with a commitment towards
building a strong nation.
MISSION:
DM1 (Problem – Solving Skills):
To equip students with fundamental computing knowledge and problem - solving skills which
are necessary to solve real-world engineering challenges to meet industry and societal needs.
DM2 (Quality Education):
To impart quality education through continuous Teaching – Learning process, including
interdisciplinary areas that extend the scope of Computer Science.
DM3 (Societal Commitment):
To inculcate students with analytical ability, innovative spirit and entrepreneur skills with
ethical values and societal commitment.
Graph Algorithms
1. Develop a program to implement graph traversal using Breadth First Search
2. Develop a program to implement graph traversal using Depth First Search
3. From a given vertex in a weighted connected graph, develop a program to find the shortest
paths to other vertices using Dijkstra’s algorithm.
4. Find the minimum cost spanning tree of a given undirected graph using Prim’s algorithm.
5. Implement Floyd’s algorithm for the All-Pairs- Shortest-Paths problem.
6. Compute the transitive closure of a given directed graph using Warshall's algorithm.
COURSE OUTCOMES:
At the end of this course, the students will be able to:
CO1: Analyze the efficiency of algorithms using various frameworks
CO2: Apply graph algorithms to solve problems and analyze their efficiency.
CO3: Make use of algorithm design techniques like divide and conquer, dynamic programming and
greedy techniques to solve problems
CO4: Use the state space tree method for solving problems.
CO5: Solve problems using approximation algorithms and randomized algorithms
List of Programs
Ex. No PROGRAMS
1. Linear Search
2. Binary Search
3. Pattern Matching
7. Dijkstra’s Algorithm
8. Prim’s Algorithm
9. Floyd’s Algorithm
Additional Experiments
Aim
To implement Linear Search and determine the time required to search for an element.
Repeat the experiment for different values of n, the number of elements in the list to be searched and
plot a graph of the time taken versus n.
Algorithm
Program
import matplotlib.pyplot as plt
import numpy as np
import timeit import
math import random
def linear_Search(list1,n,key):
for i in range(0,n):
if(list1[i]==key):
return i
return -1
list1=[1,3,5,4,7,9]
key=7
n=len(list1)
res=linear_Search(list1,n,key)
if(res==-1):
print("element not found")
else:
print("element found at index:",res)
def contains(lst,x):
for y in lst:
if x==y:
return True
return False
ns=np.linspace(10,10_000,100,dtype=int)
ts=[timeit.timeit('contains(lst,0)',
setup='lst=list(range({}));random.shuffle(lst)'.format(n),
globals=globals(),number=100) for n in ns]
plt.plot(ns,ts,'or')
degree=4
coeffs=np.polyfit(ns,ts,degree)
p=np.poly1d(coeffs)
plt.plot(ns,[p(n) for n in ns],'-r')
ts=[timeit.timeit('contains(lst,-1)',
setup='lst=list(range({}));random.shuffle(lst)'.format(n), globals=globals(),
number=100)
for n in ns]
plt.plot(ns,ts,'ob')
degree=4
coeffs=np.polyfit(ns,ts,degree)
p=np.poly1d(coeffs)
plt.plot(ns,[p(n) for n in ns],'-b')
OUTPUT
element found at index: 4
Result
Thus the program has been created, executed and the output is verified.
Ex. No: 2 Binary Search
Aim
To implement recursive Binary Search and determine the time required to search an element.
Repeat the experiment for different values of n, the number of elements in the list to be searched and
plot a graph of the time taken versus n.
Algorithm
Program
OUTPUT
Result:
Thus the program has been created, executed and the output is verified.
Ex. No: 3 Pattern Matching
Aim
To write a function search (char pat [ ], char txt [ ]) that prints all occurrences of pat [ ] in txt [ ].
Algorithm
1. Create the search function and declare the two parameters pat and txt.
2. Initialize the for loop i=0 to i≤N-M+1, and the inner loop will range from j=0 to j<m, where ‘M’ is
the length of the input pattern and N is the length of the text string.
3. If a match is not found, we will break from the loop(using the 'break' keyword), and the j
pointer of the inner loop will move one index more and start the search algorithm in the next
window
4. If a match is found, we will match the entire pattern with the current window of the text string.
And if found the pattern string is found.print the result.
Program
# Python3 program for Naive Pattern
# Searching algorithm
def search(pat, txt):
M = len(pat)
N = len(txt)
# A loop to slide pat[] one by one */
for i in range(N - M + 1):
j=0
# For current index i, check
# for pattern match */
while(j < M):
if (txt[i + j] != pat[j]):
break
j += 1
if (j == M):
print("Pattern found at index ", i)
# Driver's Code
if __name__ == '__main__':
txt = "AABAACAADAABAAABAA"
pat = "AABA"
# Function call
search(pat, txt)
Output
Pattern found at index 0
Pattern found at index 9
Pattern found at index 13
Result:
Thus the program has been created, executed and the output is verified.
Ex. No: 4 Sorting the elements using Insertion and Heap
Aim
To sort a given set of elements using the Insertion sort and Heap sort methods and determine
the time required to sort the elements. Repeat the experiment for different values of n, the number of
elements in the list to be sorted and plot a graph of the time taken versus n.
Algorithm
Program
import matplotlib.pyplot as plt
import numpy as np
import timeit import
math import random
def insertionSort(arr):
for i in range(1,len(arr)):
key=arr[i]
j=i-1
while j>=0 and key<arr[j]:
arr[j+1]=arr[j]
j-=1
arr[j+1]=key
arr=[12,11,13,5,6]
insertionSort(arr)
for i in range(len(arr)):
print("%d"%arr[i])
def insertion_sort(lst):
for i in range(1,len(lst)):
for j in range(i,0,-1):
if lst[j-1]>lst[j]:
lst[j-1],lst[j]=lst[j],lst[j-1]
else:
break
ns=np.linspace(100,2000,15,dtype=int)
ts=[timeit.timeit('insertion_sort(lst)',
setup='lst=list(range({}));random.shuffle(lst)'.format(n),
globals=globals(),
number=1)
for n in ns]
plt.plot(ns,ts,'or')
degree=4
coeffs=np.polyfit(ns,ts,degree)
p=np.poly1d(coeffs)
plt.plot(ns,[p(n) for n in ns],'-r')
OUTPUT
5
6
11
12
13
Heap Sort
Output
Sorted array is
5 6 7 11 12 13
Result:
Thus the program has been created, executed and the output is verified.
Ex. No: 5 Graph Traversal using Breadth First Search
Aim:
Algorithm
Program
class Graph:
# Constructor
def __init__(self):
self.graph = defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
queue = []
# Mark the source node as
queue.append(s)
visited[s] = True
while queue:
s = queue.pop(0)
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
g.BFS(2)
Output
Result :
Thus the program has been created, executed and the output is verified.
Ex. No: 6 Graph Traversal using Depth First Search
Aim
Algorithm
1. Create a recursive function that takes the index of the node and a visited array.
2. Mark the current node as visited and print the node.
3. Traverse all the adjacent and unmarked nodes and call the recursive function with the
index of the adjacent node.
Program
Output:
0 1 2 3
Result:
Thus the program has been created, executed and the output is verified.
Ex. No: 7 Dijkstra’s Algorithm
Aim
To develop a program to find the shortest paths to other vertices using Dijkstra’s algorithm.
Algorithm
1. Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest
path tree, i.e., whose minimum distance from source is calculated and finalized. Initially, this
set is empty.
2. Assign a distance value to all vertices in the input graph. Initialize all distance values as
INFINITE. Assign distance value as 0 for the source vertex so that it is picked first.
3. While sptSet doesn’t include all vertices:
Pick a vertex u which is not there in sptSet and has minimum distance value.
Include u to sptSet.
Update distance value of all adjacent vertices of u. To update the distance
values, iterate through all adjacent vertices. For every adjacent vertex v, if the sum of a
distance value of u (from source) and weight of edge u-v, is less than the distance value
of v, then update the distance value of v.
Program
class Graph():
class Graph():
def init (self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
def printSolution(self, dist):
print("Vertex \t Distance from Source")
for node in range(self.V):
print(node, "\t\t", dist[node])
def minDistance(self, dist, sptSet):
min = 1e7
for v in range(self.V):
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v
return min_index def
dijkstra(self, src):
dist = [1e7] * self.V
dist[src] = 0
sptSet = [False] * self.V for cout
in range(self.V):
u = self.minDistance(dist, sptSet)
sptSet[u] = True
for v in range(self.V):
if (self.graph[u][v] > 0 and
sptSet[v] == False and
dist[v] > dist[u] + self.graph[u][v]):
dist[v] = dist[u] + self.graph[u][v]
self.printSolution(dist)
g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0] ]
g.dijkstra(0)
Output:
Result:
Thus the program has been created, executed and the output is verified.
Ex. No: 8 Prim’s Algorithm
Aim
To find the minimum cost spanning tree of a given undirected graph using Prim’s algorithm.
Algorithm
1. Create a set mstSet that keeps track of vertices already included in MST.
2. Assign a key value to all vertices in the input graph. Initialize all key values as INFINITE.
Assign the key value as 0 for the first vertex so that it is picked first.
3. While mstSet doesn’t include all vertices
Pick a vertex u that is not there in mstSet and has a minimum key value.
Include u in the mstSet.
Update the key value of all adjacent vertices of u. To update the key values, iterate
through all adjacent vertices.
For every adjacent vertex v, if the weight of edge u-v is less than the
previous key value of v, update the key value as the weight of u-v.
Program
class Graph:
def init (self, num_of_nodes):
self.m_num_of_nodes = num_of_nodes
self.m_graph = [[0 for column in range(num_of_nodes)]
for row in range(num_of_nodes)]
def add_edge(self, node1, node2, weight):
self.m_graph[node1][node2] = weight
self.m_graph[node2][node1] = weight
def prims_mst(self): postitive_inf =
float('inf')
selected_nodes = [False for node in range(self.m_num_of_nodes)]
result = [[0 for column in range(self.m_num_of_nodes)]
for row in range(self.m_num_of_nodes)]
indx = 0
for i in range(self.m_num_of_nodes):
print(self.m_graph[i])
print(selected_nodes)
while(False in selected_nodes):
minimum = postitive_inf
start = 0
end = 0
for i in range(self.m_num_of_nodes):
if selected_nodes[i]:
for j in range(self.m_num_of_nodes):
if(not selected_nodes[j] and self.m_graph[i][j]>0):
if self.m_graph[i][j] < minimum:
minimum = self.m_graph[i][j]
start, end = i, j
selected_nodes[end] = True
result[start][end] = minimum
if minimum == postitive_inf:
result[start][end] = 0
print("(%d.) %d - %d: %d" % (indx, start, end, result[start][end]))
indx += 1
result[end][start] = result[start][end]
for i in range(len(result)):
for j in range(0+i, len(result)):
if result[i][j] != 0:
print("%d - %d: %d" % (i, j, result[i][j]))
example_graph = Graph(9)
example_graph.add_edge(0, 1, 4)
example_graph.add_edge(0, 2, 7)
example_graph.add_edge(1, 2, 11)
example_graph.add_edge(1, 3, 9)
example_graph.add_edge(1, 5, 20)
example_graph.add_edge(2, 5, 1)
example_graph.add_edge(3, 6, 6)
example_graph.add_edge(3, 4, 2)
example_graph.add_edge(4, 6, 10)
example_graph.add_edge(4, 8, 15)
example_graph.add_edge(4, 7, 5)
example_graph.add_edge(4, 5, 1)
example_graph.add_edge(5, 7, 3)
example_graph.add_edge(6, 8, 5)
example_graph.add_edge(7, 8, 12)
example_graph. _mst()
OUTPUT
[0, 4, 7, 0, 0, 0, 0, 0, 0]
[4, 0, 11, 9, 0, 20, 0, 0, 0]
[7, 11, 0, 0, 0, 1, 0, 0, 0]
[0, 9, 0, 0, 2, 0, 6, 0, 0]
[0, 0, 0, 2, 0, 1, 10, 5, 15]
[0, 20, 1, 0, 1, 0, 0, 3, 0]
[0, 0, 0, 6, 10, 0, 0, 0, 5]
[0, 0, 0, 0, 5, 3, 0, 0, 12]
[0, 0, 0, 0, 15, 0, 5, 12, 0]
0 - 1: 4
0 - 2: 7
2 - 5: 1
3 - 4: 2
3 - 6: 6
4 - 5: 1
5 - 7: 3
6 - 8: 5
Result:
Thus the program has been created, executed and the output is verified.
Ex. No: 9 Floyd’s Algorithm
Aim
Algorithm
1. Initialize the solution matrix same as the input graph matrix as a first step.
2. considering all vertices as an intermediate vertex. pick all vertices and updates all shortest
paths which include the picked vertex as an intermediate vertex in the shortest path.
3. When we pick vertex number k as an intermediate vertex, we already have considered
vertices {0, 1, 2, .. k-1} as intermediate vertices.
4. For every pair (i, j) of the source and destination vertices respectively, there are two possible
cases.
k is not an intermediate vertex in shortest path from i to j. We keep the value of dist[i][j]
as it is.
k is an intermediate vertex in shortest path from i to j. We update the value of dist[i][j]
as dist[i][k] + dist[k][j] if dist[i][j] > dist[i][k] + dist[k][j]
Program
nV = 4
INF = 999
def floyd_warshall(G):
distance = list(map(lambda i: list(map(lambda j: j, i)), G))
for k in range(nV):
for i in range(nV):
for j in range(nV):
distance[i][j] = min(distance[i][j], distance[i][k] + distance[k][j])
print_solution(distance)
def print_solution(distance):
for i in range(nV):
for j in range(nV):
if(distance[i][j] == INF):
print("INF", end=" ") else:
print(distance[i][j], end=" ")
print(" ")
G = [[0, 3, INF, 5],
[2, 0, INF, 4],
[INF, 1, 0, INF],
[INF, INF, 2, 0]]
floyd_warshall(G)
OUTPUT
0 3 7 5
2 0 6 4
3 1 0 5
5 3 2 0
Result:
Thus the program has been created, executed and the output is verified.
Aim
To compute the transitive closure of a given directed graph using Warshall's algorithm.
Algorithm
Program
from collections import defaultdict
class Graph:
def init (self, vertices):
self.V = vertices
def printSolution(self, reach):
print("Following matrix transitive closure of the given graph ")
for i in range(self.V):
for j in range(self.V):
if (i == j):
print("%7d\t" % (1),end=" ")
else:
print("%7d\t" %(reach[i][j]),end=" ")
print()
def transitiveClosure(self,graph):
reach =[i[:] for i in graph]
for k in range(self.V):
for i in range(self.V):
for j in range(self.V):
reach[i][j] = reach[i][j] or (reach[i][k] and reach[k][j])
self.printSolution(reach)
g= Graph(4)
graph = [[1, 1, 0, 1],
[0, 1, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1]]
g.transitiveClosure(graph)
OUTPUT
Result:
Thus the program has been created, executed and the output is verified.
Aim:
To implement N Queens problem using Backtracking.
Algorithm
1. Initialize an empty chessboard of size NxN.
2. Start with the leftmost column and place a queen in the first row of that column.
3. Move to the next column and place a queen in the first row of that column.
4. Repeat step 3 until either all N queens have been placed or it is impossible to place a queen
in the current column without violating the rules of the problem.
5. If all N queens have been placed, print the solution.
6. If it is not possible to place a queen in the current column without violating the rules of the
problem, backtrack to the previous column.
7. Remove the queen from the previous column and move it down one row.
8. Repeat steps 4-7.
Program
global N N = 4
def PrintSolution(board):
for i in range(N):
for j in range(N):
print(board[i][j],end='')
print()
def isSafe(board,row,col):
for i in range(col):
if board[row][i] == 1:
return False
for i,j in zip(range(row,-1,-1),range(col,-1,-1)):
if board[i][j] == 1:
return False
for i,j in zip(range(row,-1,-1),range(col,-1,-1)):
if board[i][j] == 1:
return False
return True
def SolveNQUtil(board,col):
if col >= N:
return True
for i in range(N):
if isSafe(board,i,col):
board[i][col] = 1
if SolveNQUtil(board,col+1) == True:
return True
board[i][col] = 0
return False
def SolveNQ():
board= [[0,0,0,0],
[0,0,0,0],
[0,0,0,0],
[0,0,0,0] ]
ifSolveNQUtil(board,0)==False:
print("SOlution does not exist")
return False
PrintSolution(board)
return True
SolveNQ()
OUTPUT
0010
1000
0001
0100
True
Result:
Thus the program has been created, executed and the output is verified.
Ex. No: 12 Travelling Salesman Problem
Aim
To find the optimal solution for the Traveling Salesperson problem and then solve the same
problem instance using any approximation algorithm and determine the error in the approximation.
Algorithm
1. Construct MST .
2. Determine an arbitrary vertex as the starting vertex of the MST.
3. Follow steps 3 to 5 till there are vertices that are not included in the MST
4. Find edges connecting any tree vertex with the fringe vertices.
5. Find the minimum among these edges.
6. Add the chosen edge to the MST if it does not form any cycle.
7. Return the MST and exit.
Program
OUTPUT
80
Result:
Thus the program has been created, executed and the output is verified.
Ex. No: 13 Merge Sort
Aim
To Implement Merge sort method to sort an array of elements and determine the time required to
sort. Repeat the experiment for different values of n, the number of elements in the list to be sorted
and plot a graph of the time taken versus n.
ALGORITHM:
1: The program first defines the merge_sort() function which implements the Merge sort algorithm.
2: It then defines a test_merge_sort() function which generates a list of n random numbers, sorts
the list using Merge sort, and measures the time required to sort the list.
3: Finally, the program tests the test_merge_sort() function for different values of n and plots a
graph of the time taken versus n using the Matplotlib library
Program:
import random
import time
def merge_sort(arr):
left_half = arr[:mid]
right_half = arr[mid:]
merge_sort(left_half)
merge_sort(right_half)
i=j=k=0
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1
arr[k] = left_half[i]
i += 1
k += 1
arr[k] = right_half[j]
j += 1
k += 1
def test_merge_sort(n):
for _ in range(n)]
start_time = time.time()
merge_sort(arr)
end_time = time.time()
if __name__ == '__main__':
times = []
for n in ns:
t = test_merge_sort(n)
times.append(t)
plt.title('Merge Sort')
plt.show()
Output
Result:
Thus the program has been created, executed and the output is verified.
Ex. No: 14 Quick Sort
Aim
To Implement Quick sort method to sort an array of elements and determine the time required
to sort. Repeat the experiment for different values of n, the number of elements in the list to be sorted
and plot a graph of the time taken versus n.
Algorithm
1: This program generates a list of random integers of size n, sorts the list using the quicksort
function, and measures the time required to sort the list.
2: It repeats this process num_repeats times and returns the average time taken.
3: The main function of the program tests the measure_time function for different values of n and
plots a graph of the time taken versus n.
4: The maximum value of n is set to max_n, and the step size between values of n is set to
step_size.
5: The program uses the built-in random and time modules to generate random integers and measure
time, respectively. Additionally, the quicksort function is implemented recursively and sorts the list in
ascending order
Program
import random
import time
def quicksort(arr):
if len(arr) <= 1:
return arr
pivot = arr[0]
left = []
right = []
for i in range(1, len(arr)):
if arr[i] < pivot:
left.append(arr[i])
else:
right.append(arr[i])
return quicksort(left) + [pivot] + quicksort(right)
def measure_time(n, num_repeats):
times = []
for _ in range(num_repeats):
arr = [random.randint(0, 1000000)
for _ in range(n)]
start_time = time.time()
quicksort(arr)
end_time = time.time()
times.append(end_time - start_time)
return sum(times) / len(times)
if __name__ == '__main__':
num_repeats = 10
max_n = 10000
step_size = 100
ns = range(0, max_n + step_size, step_size)
times = []
for n in ns:
if n == 0:
times.append(0)
else:
times.append(measure_time(n, num_repeats))
print(times)
Output:
[0, 0.00013625621795654297, 0.0006334543228149414, 0.000517892837524414,
0.0009247779846191407, 0.000916147232055664, 0.0010011672973632812,]
Result:
Thus the program has been created, executed and the output is verified.
Ex. No: 15 Randomized Algorithms for kth Smallest element
Aim
To implement randomized algorithms for finding the kth smallest number.
Algorithm
The partition() function takes an array arr, low index low, and high index high as input and partitions
the array around a randomly chosen pivot. It returns the index of the pivot element.
2. The randomized_select() function takes an array arr, low index low, high index high, and the value
of k as input and returns the kth smallest element in the array. It first selects a random pivot element
using random.randint() function and partitions the array using the partition() function. Then it
recursively calls itself on either the left or right partition depending on the position of the pivot
element.
3. In the main section, we define an array arr and the value of k. Then we calculate the length of the
array n and call the randomized_select() function on the array to find the kth smallest element.
Program
import random
# Function to partition the array around a pivot
def partition(arr, low, high):
i = low - 1
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i+1
# Function to find the kth smallest number using randomized algorithm
def randomized_select(arr, low, high, k):
if low == high:
return arr[low]
pivot_index = random.randint(low, high)
arr[pivot_index], arr[high] = arr[high], arr[pivot_index]
index = partition(arr, low, high)
if k == index:
return arr[k]
elif k < index:
return randomized_select(arr, low, index-1, k)
else:
return randomized_select(arr, index+1, high, k)
# Testing the function
arr = [9, 4, 2, 7, 3, 6]
k=3
n = len(arr)
result = randomized_select(arr, 0, n-1, k-1)
print(f"The {k}th smallest number is: {result}")
OUTPUT:
The 3th smallest number is: 4
Result:
Thus the program has been created, executed and the output is verified.
EX.NO: 16 MATRIX MULTIPLICATION
Aim:
To write a C program to find the product of the two matrices.
Algorithm:-
Step 1: Start the program.
Step 2: Read the no. of rows and columns in matrix A and B.
Step 3: check if the row size of Matrix A and column size of Matrix B is equal (r1=c2),
goto step 4 otherwise goto Step 7
Step 4: Read the elements of two matrices one by one by using for loop.
Step 5: Multiply the elements of two matrices by using the condition
c[i][j]=a[i][k] * b[k][j]
Step 6: Print the resultant matrix.
Step 7: Print “Matrix Multiplication is not possible”
Step 8: Stop the program.
Program:-
#include <stdio.h>
#include<conio.h>
void main()
{
int a[3][3], b[3][3], c[3][3];
int r1,c1,r2,c2,i,j,k;
clrscr();
printf("\n Enter the no.of rows in matrx A:");
scanf("%d",&r1);
printf("\n Enter the no.of columns in matrx A:");
scanf("%d",&c1);
printf("\n Enter the no.of rows in matrx B:");
scanf("%d",&r2);
printf("\n Enter the no.of columns in matrx B:");
scanf("%d",&c2);
if(r1!=c2)
{
printf("\n Matrix multiplication is not possible..");
}
else
{
printf("Enter the elements in matrix A:\n");
for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
{
scanf("%d", &a[i][j]);
}
}
Output:-
12 12
12 12
Result:
Thus the program has been created, executed and the output is verified.
EX.NO: 17 Finding Maximum and Minimum element in the given array
Aim:
To write a C program to find the product of the two matrices.
Algorithm
Program
#include<stdio.h>
#include<stdio.h>
int max, min;
int a[100];
void maxmin(int i, int j)
{
int max1, min1, mid;
if(i==j)
{
max = min = a[i];
}
else
{
if(i == j-1)
{
if(a[i] <a[j])
{
max = a[j];
min = a[i];
}
else
{
max = a[i];
min = a[j];
}
}
else
{
mid = (i+j)/2;
maxmin(i, mid);
max1 = max; min1 = min;
maxmin(mid+1, j);
if(max <max1)
max = max1;
if(min > min1)
min = min1;
}
}
}
int main ()
{
int i, num;
printf ("\nEnter the total number of numbers : ");
scanf ("%d",&num);
printf ("Enter the numbers : \n");
for (i=1;i<=num;i++)
scanf ("%d",&a[i]);
max = a[0];
min = a[0];
maxmin(1, num);
printf ("Minimum element in an array : %d\n", min);
printf ("Maximum element in an array : %d\n", max);
return 0;
}
output:-
Result:
Thus the program has been created, executed and the output is verified.