0% found this document useful (0 votes)
6 views42 pages

Daa Lab Man

The document outlines the implementation of recursive and non-recursive algorithms for calculating GCD, factorial, Fibonacci series, and binary search, along with a divide-and-conquer approach for Strassen's matrix multiplication. Each section includes the aim, algorithm steps, and example C programs demonstrating both recursive and non-recursive methods. The results confirm successful execution and verification of the programs.

Uploaded by

OLGA RAJEE C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views42 pages

Daa Lab Man

The document outlines the implementation of recursive and non-recursive algorithms for calculating GCD, factorial, Fibonacci series, and binary search, along with a divide-and-conquer approach for Strassen's matrix multiplication. Each section includes the aim, algorithm steps, and example C programs demonstrating both recursive and non-recursive methods. The results confirm successful execution and verification of the programs.

Uploaded by

OLGA RAJEE C
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Ex.

NO:1 IMPLEMENTATION OF RECURSIVE AND NON–RECURSIVE ALGORITHMS


a) GCD
DESCRIPTION:

RECURSIVE ALGORITHM
A recursive algorithm is a method of solving a problem by breaking it down into
smaller and smaller sub problems until the problem becomes simple enough to be
solved directly. In a recursive algorithm, a function calls itself in order to solve a
problem. The function will have a base case, which is a condition that stops the
recursion, and a recursive case, which is when the function calls itself with a simpler
version of the problem.
For example, the factorial function can be computed recursively by calling itself with
the input decremented by one until the input is one, at which point it returns one.

NON-RECURSIVE ALGORITHM
A non-recursive algorithm, also known as an iterative algorithm, solves a problem
without using recursion. Instead, it uses a looping construct such as a ‘for’ or ‘while’
loop to repeatedly perform a set of instructions until a certain condition is met. Non-
recursive algorithms can be more efficient in terms of memory and time complexity
than recursive algorithms. They are also easier to reason about for certain types of
problems. An example of non-recursive algorithm is a linear search algorithm in which
we iterate through an array and compare each element with the target value, until we
find the target value or end of array.

ORDER OF GROWTH
The order of growth is a way to express the performance of an algorithm in terms of
the size of the input. The order of growth is often represented using big O notation,
which describes the upper bound on the number of operations an algorithm takes to
solve a problem of size n.
 O (log2 n) represents logarithmic time complexity
 O (n) represents linear time complexity
In general, logarithmic time complexity (O(log 2n)) is considered more efficient than
linear time complexity (O(n)), as the input size increases, the logarithmic algorithm
will take fewer operations to solve the problem. However, there are other complexities
such as
O (n log2 n) which are considered to be more efficient than O(n) and less efficient than
O (log2 n).

AIM:
To write a C Program to find the GCD of given two positive integers.

ALGORITHM:
STEP 1: Start the Program.
STEP 2: Declare the required variables.
STEP 3: Read the value for num1 and num2.
STEP 4: Using for loop find a value which divides both num1 and num2.
STEP 5: Print the GCD of num1 and num2.
STEP 6: Stop the program.

PROGRAM (without Recursion):


#include <stdio.h>
1
int main()
{
int n1, n2, i, gcd;

printf("Enter two positive integers: ");


scanf("%d %d", &n1, &n2);
for(i=1; i <= n1 && i <= n2; ++i)
{
if(n1%i==0 && n2%i==0)
gcd = i;
}
printf("G.C.D of %d and %d is %d", n1, n2, gcd);
return 0;
}

ALGORITHM:
STEP 1: Start the Program.
STEP 2: Declare the required variables.
STEP 3: Read the value for num1 and num2.
STEP 4: Call the function Gcd().
STEP 5: Check is Num1 is 0 then return Num2 as Gcd to Main().
STEP 6: Check is Num2 is 0 then return Num1 as Gcd to Main().
STEP 7: Otherwise, make a recursive call to Gcd() as follows.
a. If Num1 > Num2 then call Gcd() with Num1%Num2 , Num2 as arguments.
b. If Num2 > Num1 then call Gcd() with Num1, Num2%Num1 as arguments.
STEP 8: Pass the GCD of Num1 and Num2 to Main().
STEP 9: Print the GCD of two numbers.
STEP 10: Stop the Program.

PROGRAM (with Recursion):


#include <stdio.h>
int gcd(int n1, int n2);
int main() {
int n1, n2;
printf("Enter two positive integers: ");
scanf("%d %d", &n1, &n2);
printf("G.C.D of %d and %d is %d.", n1, n2, gcd(n1, n2));
return 0;
}
int gcd(int n1, int n2){
if (n2 != 0)
return gcd(n2, n1 % n2);
else
return n1;
}

RESULT:
Thus, the program was executed successfully and the output was verified.

2
Ex.NO: 1 IMPLEMENTION OF RECURSIVE AND NON – RECURSIVE ALGORITHMS
b) FACTORIAL
AIM:
To write a C Program to find Factorial of a given number.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the required variables and Initialize fact as 1.
STEP 3: Read a number into Num.
STEP 4: Using for loop calculate factorial of the given number.
STEP 5: Calculate fact=fact*i until i <= Num.
STEP 6: Print the factorial of the given number.
STEP 7: Stop the Program.
PROGRAM (without recursion):
#include<stdio.h>
void main()
{
int fact=1,i,num;
printf("Enter the Number to Find Factorial :");
scanf("%d",&num);
for(i=1;i<=num;i++)
{
fact=fact*i;
}
printf("Factorial of %d is %d",num,fact);
}
ALGORITHM:
STEP 1: Start the Program.
STEP 2: Declare the required variables.
STEP 3: Read the value for N
STEP 4: Call Fact() with N as argument.
STEP 5: If N=0 then return 1 as factorial.
STEP 6: Otherwise, call Fact() with N-1 as argument.
STEP 7: Finally return the factorial to the Main().
STEP 8: Print the Factorial in Main().
STEP 9: Stop the Program.
PROGRAM (with recursion):
#include<stdio.h>
int fact(int);
int main()
{ int x,n;
printf(" Enter the Number to Find Factorial :");
scanf("%d",&n);
x=fact(n);
printf(" Factorial of %d is %d",n,x);
return 0;
}
int fact(int n)
{
if(n==0)
return(1);
return(n*fact(n-1));
}RESULT:
3
Thus, the program was executed successfully and the output was verified.
Ex.NO:1 IMPLEMENTION OF RECURSIVE AND NON – RECURSIVE ALGORITHMS
c) FIBONACCI SERIES
AIM:
To write a C Program to display the Fibonacci Series.
ALGORITHM:
STEP 1: Start the Program.
STEP 2: Declare the required variables.
STEP 3: Initialize f=0, f1=0, f2=1, i=1.
STEP 3: Read the value for n.
STEP 4: Using do while loop find the Fibonacci Series.
STEP 5: In each iteration, print a term in Fibonacci Series. i.e., Print f.
STEP 6: Calculate f=f1+f2
STEP 7: Assign f2=f1; f1=f; i=i+1.
STEP 8: Repeat the Steps 5 to 7 until i<=n.
STEP 9: Display the Series.
STEP 10: Stop the Program.
PROGRAM (without recursion):
#include<stdio.h>
void main()
{
int i=1,n,f,f1,f2;
printf("Enter the number of elements: ");
scanf("%d",&n);
f=0;
f1=0;
f2=1;
printf("Fibonacci series:\n");
do
{
i++;
printf("%d\n",f);
f=f1+f2;
f2=f1;
f1=f;
}while(i<=n);
}
ALGORITHM:
STEP 1: Start the Program.
STEP 2: Declare the required variables.
STEP 3: Read the value for N.
STEP 4: Initialize a loop counter variable C=1 and execute a for loop.
STEP 5: Call recursive function Fibonacci().
STEP 6: Print all the terms of Fibonacci Series until C<=N
STEP 7: Stop the Program.
PROGRAM (with recursion):
#include<stdio.h>
int Fibonacci(int);
int main()
{
int n, i = 0, c;
` printf("Enter the number of elements: ");
scanf("%d",&n);
4
printf("Fibonacci series:\n");
for ( c = 1 ; c <= n ; c++ )
{
printf("%d\n", Fibonacci(i));
i++;
}
return 0;
}
int Fibonacci(int n)
{
if ( n == 0 )
return 0;
else if ( n == 1 )
return 1;
else
return ( Fibonacci(n-1) + Fibonacci(n-2) );
}

RESULT:
Thus, the program was executed successfully and the output was verified.

5
Ex.NO:1 IMPLEMENTION OF RECURSIVE AND NON – RECURSIVE ALGORITHMS
d) BINARY SEARCH
AIM:
To write a C program to perform Binary Search in a sorted array of elements.
ALGORITHM:
STEP 1: Start the Program.
STEP 2: Read the sorted array of elements and the Key element to be searched.
STEP 3: Declare the required variables.
STEP 4: Initialize First=0; Last=n-1 and Calculate Mid= (First + Last)/2.
STEP 5: Compare the Key element with the element at the 'Mid' index:
a: If they are equal, the Key element is found at index Mid.
b: If the Key element<Mid, update Last=Mid-1 to search in the lower half.
c: If the Key element>Mid, update First=Mid +1 to search in the upper half.
STEP 6: Repeat Step 5 until First>Last.
STEP 7: If First>Last, the Key element is not found in the array.
STEP 8: Stop the Program.
PROGRAM (without recursion):
#include<stdio.h>
void main()
{
int c,first,last,middle,n,key,array[100];
printf("Enter the size of an array \n");
scanf("%d",&n);
printf("Enter the values in sorted order:\n");
for(c=0;c<n;c++)
scanf("%d",&array[c]);
printf("Enter a value to be searched:");
scanf("%d",&key);
first=0;
last=n-1;
middle=(first+last)/2;
while(first<=last)
{
if(array[middle]<key)
first=middle+1;
else if (array[middle]==key){
printf Element is found at index %d\n",middle);
break;
}
else
last=middle-1;
middle=(first+last)/2;
}
if(first>last)
printf("Element is not found\n”);
}
ALGORITHM:
STEP 1: Start the Program.
STEP 2: Declare the required variables.
STEP 3: Read the number of elements in Num.
STEP 4: Read the sorted elements into the array Arr[].
STEP 5: Read the Key element to be searched.
6
STEP 6: Initialize Beg=0, End=Num-1
STEP 7: Call BinarySearch(Arr[], Num, Beg, End)
STEP 8: Calculate Mid= (First + Last)/2 where First = Beg, Last = End.
STEP 9: Compare the Key element with the element at the 'Mid' index:
a: If they are equal, the Key element is found at index Mid.
b: If the Key element<Mid, Call BinarySearch(Arr[], Num, First, Mid-1) to search in
the lower half of the array.
c: If the Key element>Mid, Call BinarySearch(Arr[], Num, Mid +1, Last) to search in
the upper half of the array.
STEP 10: Repeat Step 9 until First>Last.
STEP 11: If First>Last, the Key element is not found in the array.
STEP 12: Stop the Program.
PROGRAM (with recursion):
#include <stdio.h>
#include <stdlib.h>
void Binary_search(int[],int,int,int);
void main()
{int arr[100],beg,mid,end,i,n,num;
printf("Enter the size of an array:");
scanf("%d",&n);
printf("Enter the values in sorted order:\n");
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
beg=0;
end=n-1;
printf("Enter a value to be searched:");
scanf("%d",&num);
Binary_search(arr,num,beg,end);
}
void Binary_search(int arr[],int num,int first, int last)
{
int mid;
if(first>last)
{
printf("Element is not found");
}
else
{
mid=(first+last)/2;
if(arr[mid]==num)
{
printf("Element is found at index %d",mid);
}
else if (arr[mid]>num)
{
Binary_search(arr,num,first,mid-1);
}
else
{Binary_search(arr,num,mid+1,last);
}}}
RESULT:
Thus, the program was executed successfully and the output was verified.

7
Ex.NO:2 DIVIDE AND CONQUER
a) STRASSEN’S MATRIX MULTIPLICATION
AIM:
To write a C program to implement Strassen’s Matrix Multiplication using the
Divide and Conquer technique.
DESCRIPTION:
STRASSEN’S MATRIX MULTIPLICATION
Strassen's matrix multiplication is an algorithm for multiplying two matrices
using a divide-and-conquer approach. Strassen's algorithm is more efficient than the
traditional matrix multiplication algorithm for large matrices, but the constant
overhead of the divide-and-conquer approach and the additional matrix products
make it less efficient for small matrices.
ALGORITHM:
STEP 1: Start
STEP 2: Divide the input matrices A and B into four equal-sized sub-matrices: A11,
A12, A21, and A22 for matrix A, and B11, B12, B21, and B22 for matrix B.
STEP 3: Compute the following seven matrix products:
P1 = A11 * (B12 - B22)
P2 = (A11 + A12) * B22
P3 = (A21 + A22) * B11
P4 = A22 * (B21 - B11)
P5 = (A11 + A22) * (B11 + B22)
P6 = (A12 - A22) * (B21 + B22)
P7 = (A11 - A21) * (B11 + B12)
STEP 4: Compute the four sub-matrices of the result matrix C using the following
equations:
C11 = P5 + P4 - P2 + P6
C12 = P1 + P2
C21 = P3 + P4
C22 = P5 + P1 - P3 - P7
STEP 5: Combine the sub-matrices C11, C12, C21, and C22 to form the final result
matrix C.
STEP 6: Return the final result matrix C.
STEP 7: Stop the Program.
PROGRAM:
#include<stdio.h>
int main()
{
int a[2][2], b[2][2], c[2][2], i, j;
int m1, m2, m3, m4 , m5, m6, m7;
printf("Enter the 4 elements of first matrix: ");
for(i = 0;i < 2; i++)
for(j = 0;j < 2; j++)
scanf("%d", &a[i][j]);
printf("Enter the 4 elements of second matrix: ");
for(i = 0; i < 2; i++)
for(j = 0;j < 2; j++)
scanf("%d", &b[i][j]);
printf("\nThe first matrix is\n");
for(i = 0; i < 2; i++){
printf("\n");
for(j = 0; j < 2; j++)
printf("%d\t", a[i][j]);
8
}
printf("\nThe second matrix is\n");
for(i = 0;i < 2; i++){
printf("\n");
for(j = 0;j < 2; j++)
printf("%d\t", b[i][j]);
}
m1= (a[0][0] + a[1][1]) * (b[0][0] + b[1][1]);
m2= (a[1][0] + a[1][1]) * b[0][0];
m3= a[0][0] * (b[0][1] - b[1][1]);
m4= a[1][1] * (b[1][0] - b[0][0]);
m5= (a[0][0] + a[0][1]) * b[1][1];
m6= (a[1][0] - a[0][0]) * (b[0][0]+b[0][1]);
m7= (a[0][1] - a[1][1]) * (b[1][0]+b[1][1]);
c[0][0] = m1 + m4- m5 + m7;
c[0][1] = m3 + m5;
c[1][0] = m2 + m4;
c[1][1] = m1 - m2 + m3 + m6;
printf("\nAfter multiplication using Strassen's algorithm \n");
for(i = 0; i < 2 ; i++){
printf("\n");
for(j = 0;j < 2; j++)
printf("%d\t", c[i][j]);
}

return 0;
}
RESULT:
Thus, the program was executed successfully and the output was verified.

Ex.NO:2 DIVIDE AND CONQUER


9
b) MERGESORT
AIM:
To write a C program to implement the concept of merge sort using the divide
and conquer technique.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Divide the list of elements into half.
STEP 3: Repeat the Step2 until we get single element in list.
STEP 4: Merge two list to create a new list.
STEP 5: Compare the elements with each other and place them in ascending order.
STEP 6: Repeat the process until one list is obtained.
STEP 7: Print the sorted list in ascending order.
STEP 8: Stop the program.
PROGRAM:
#include <stdio.h>
void merge(int arr[], int p, int q, int r) {
int i,j,k;
int n1 = q - p + 1;
int n2 = r - q;
int L[n1], M[n2];
for (i = 0; i < n1; i++)
L[i] = arr[p + i];
for (j = 0; j < n2; j++)
M[j] = arr[q + 1 + j];
i = 0;
j = 0;
k = p;
while (i < n1 && j < n2) {
if (L[i] <= M[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = M[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = M[j];
j++;
k++;
}}
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
10
}}
void printArray(int arr[], int size) {
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {6, 5, 12, 10, 9, 1};
int size = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, size - 1);
printf("Sorted array: \n");
printArray(arr, size);
}

RESULT:
Thus, the program was executed successfully and the output was verified.

Ex.NO:3 DECREASE AND CONQUER


TOPOLOGICAL SORTING
11
AIM:
To write a C program to implement topological sorting using the decrease and
conquer method.
DESCRIPTION:
"Decrease and conquer" is a general algorithmic technique that involves solving
the problem by breaking it down into smaller subproblems, and then solving each
subproblem independently. Topological sorting is a specific application of this
technique in the context of graph theory. It involves arranging the nodes of a directed
acyclic graph (DAG) in a linear order such that for every edge (u, v), the node u comes
before the node v in the order. One common use of topological sorting is to find a
valid sequence of steps for completing a set of tasks that have dependencies on one
another.
The "decrease and conquer" approach to topological sorting typically involves
repeatedly removing a node from the graph (i.e. decreasing the size of the problem)
and adding it to the sorted order, while ensuring that all of the node's dependencies
are satisfied. This process is repeated until all nodes have been removed and added
to the sorted order.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Initialize an empty sorted order array and initialize in-degree of all vertices.
STEP 3: Repeat the following steps until all vertices are added to the sorted order:
a. Find the next vertex with zero in degrees.
b. If no such vertex exists, print "Graph has a cycle" and return.
c. Add the vertex to the sorted order and decrease the in-degree of all its adjacent
vertices.
STEP 4: Print the sorted order of vertices.
STEP 5: Stop the program.
PROGRAM:
#include <stdio.h>
int main()
{
int i,j,k,n,a[10][10],indeg[10],flag[10],count=0;
printf("Enter the no of vertices:\n");
scanf("%d",&n);
printf("Enter the adjacency matrix:\n");
for(i=0;i<n;i++)
{
printf("Enter row %d\n",i+1);
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
for(i=0;i<n;i++)
{
indeg[i]=0;
flag[i]=0;
}
for(i=0;i<n;i++)
for(j=0;j<n;j++)
indeg[i]=indeg[i]+a[j][i];
printf("\nThe topological order is:");
while(count<n){
for(k=0;k<n;k++){
if((indeg[k]==0) && (flag[k]==0))
12
{
printf("%d ",(k+1));
flag [k]=1;
}
for(i=0;i<n;i++){
if(a[i][k]==1)
indeg[k]--;
}
}
count++;
}
return 0;
}

RESULT:
Thus, the program was executed successfully and the output was verified.

Ex.NO:4 TRANSFORM AND CONQUER


13
HEAP SORT
AIM:
To write a C program for heap sort using transform and conquer.
DESCRIPTION:
Heap Sort is a comparison-based sorting algorithm that uses a binary heap data
structure. The "transform and conquer" approach is a way of implementing Heap Sort,
where the input array is transformed into a binary heap and then the elements are
extracted from the heap in a sorted order.
The algorithm starts by creating a binary heap from the input array by repeatedly
inserting elements and maintaining the heap property. Then, repeatedly extract the
maximum element from the heap and place it at the end of the sorted output array,
by swapping the maximum element with the last element in the heap and reducing
the size of the heap by one.
The time complexity of Heap sort is O(n log n) which makes it more efficient than
many other sorting algorithms. The algorithm is not a stable sorting algorithm,
meaning that if there are multiple elements with the same value, their relative order
may change in the output.
ALGORITHM:
STEP 1: Create a function called "swap" that takes in two integers and swaps their
values.
STEP 2: Create a function called "heapify" that takes in an array, the size of the array,
and an integer "i" representing the current node.
a. Initialize a variable "largest" as "i"
b. Calculate the left and right child of the current node using the formulas left = 2i + 1
and right = 2i + 2
c. Compare the value of the left child and the right child with the current node. If any
of them is greater than the current node, set the "largest" variable to the index of the
larger child.
d. If the "largest" variable is not equal to "i", swap the values at the "i" and "largest"
indexes and call the "heapify" function recursively with the "largest" index.
STEP 3: Create a function called "heap Sort" that takes in an array and the size of the
array.
a. Starting from the middle of the array and going backwards, call the "heapify"
function for each index to build the binary heap.
b. Starting from the last element of the array, swap the first and last element and call
the "heapify" function with the first element as the current node and the size of the
array minus one. Repeat this step for the remaining elements of the array.
STEP 4: In the main function, initialize an array with some values and get the size of
the array.
a. Call the "heap Sort" function with the array and its size as arguments.
b. Print the sorted array
STEP 5: The input array is sorted in ascending order.
PROGRAM:
#include <stdio.h>
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// Function to maintain the heap property
void heapify(int arr[], int n, int i) {
int largest = i;
14
int left = 2*i + 1;
int right = 2*i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
}
void heapSort(int arr[], int n) {
// Build the heap
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// Extract elements from the heap
for (int i=n-1; i>=0; i--) {
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}
int main() {
int arr[] = {4, 10, 3, 5, 1};
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n);
printf("Sorted array: \n");
for (int i=0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}

RESULT:
Thus, the program was executed successfully and the output was verified.

Ex.NO:5 DYNAMIC PROGRAMMING


a) COIN CHANGING PROBLEM
15
AIM:
To write a C program to implement coin-changing problems using the Dynamic
programming technique.
DESCRIPTION:
COIN CHANGING PROBLEM:
In the coin-changing problem, we are given an array of coins having different
denominations and an integer sum representing the total money, you have to return
the fewest coins that you will need to make up that sum if it’s not possible to
construct that sum then return -1.
PROGRAM:
// Recursive C program for coin change problem.
#include <stdio.h>
// Returns the count of ways we can sum coins[0...n-1] coins to get sum "sum"
int count(int coins[], int n, int sum)
{
// If sum is 0 then there is 1 solution (do not include any coin)
if (sum == 0)
return 1;
// If sum is less than 0 then no solution exists
if (sum < 0)
return 0;
// If there are no coins and sum is greater than 0, then no solution exist
if (n <= 0)
return 0;
// count is sum of solutions (i) including coins[n-1] (ii) excluding coins[n-1]
return count(coins, n - 1, sum) + count(coins, n, sum - coins[n - 1]);
}
// Driver program to test above function
int main()
{
int i, j;
int coins[] = { 10, 25, 50 };
int n = sizeof(coins) / sizeof(coins[0]);
printf("Number of Ways: %d ", count(coins, n, 85));
return 0;
}

RESULT:
Thus, the program was executed successfully and the output was verified.

Ex.NO:5 DYNAMIC PROGRAMMING


b) WARSHALL’S ALGORITHM
16
AIM:
To write a C program to implement Warshall’s Algorithm using the Dynamic
programming technique.
DESCRIPTION:
WARSHALL’S ALGORITHM
Warshall's algorithm is used to determine the transitive closure of a directed
graph or all paths in a directed graph by using the adjacency matrix. For this, it
generates a sequence of n matrices. Where n is used to describe the number of
vertices.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Read the number of vertices n.
STEP 3: Read the adjacency matrix A[1...n, 1...n]
STEP 4: R(0) ← A
STEP 5: for k ← 1 to n do
for i ← 1 to n do
for j ← to n do
STEP 6: Compute R(k)[i, j] ← R(k-1)[i, j] or (R(k-1)[i, k] and R(k-1)[k, j])
STEP 7: return R(n)
STEP 8: Stop the program.
PROGRAM:
#include <stdio.h>
int n,a[10][10],p[10][10];
void path()
{
int i,j,k;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
p[i][j]=a[i][j];
for(k=0;k<n;k++)
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(p[i][k]==1&&p[k][j]==1)
p[i][j]=1;
}
void main()
{int i,j;
printf("Enter the number of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
path();
printf("\nThe path matrix is shown below\n");
for(i=0;i<n;i++){
for(j=0;j<n;j++)
printf("%d ",p[i][j]);printf("\n");
}}
RESULT:
Thus, the program was executed successfully and the output was verified.
Ex.NO:5 DYNAMIC PROGRAMMING

17
c) FLOYD’S ALGORITHM
AIM:
To write a C program to implement Floyd’s Algorithm using the Dynamic
programming technique.
DESCRIPTION:
FLOYD’S ALGORITHM
Floyd’s algorithm is an algorithm for finding the shortest paths in a directed
weighted graph with positive or negative edge weights. A single execution of the
algorithm will find the lengths of the shortest paths between all pairs of vertices.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Read the weight matrix.
STEP 3: Initialize the distance matrix with infinity.
STEP 4: Find all pair shortest paths using k intermediate vertices by considering all N
vertices as intermediate nodes.
STEP 5: For every pair (i, j) vertices, there are two possible cases.
 k is not an intermediate vertex in the shortest path from i to j.
o We keep the value of dist[i][j] as it is.
 k is an intermediate vertex in the shortest path from i to j.
o We update the value of dist[i][j] as dist[i][k] + dist[k][j].
STEP 6: Print the updated distance matrix.
STEP 7: Stop the program.
PROGRAM:
#include<stdio.h>
int min(int,int);
void floyds(int dist[10][10],int n)
{
int i,j,k;
for(k=1;k<=n;k++)
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
if(i==j)
dist[i][j]=0;
else
dist[i][j]=min(dist[i][j],dist[i][k]+dist[k][j]);
}
int min(int a,int b){
if(a<b)
return(a);
else
return(b);
}
void main()
{
int dist[10][10],w,n,e,u,v,i,j;
printf("\n Enter the number of vertices:");
scanf("%d",&n);
printf("\n Enter the number of edges:\n");
scanf("%d",&e);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
18
dist[i][j]=99999999;
}
for(i=1;i<=e;i++)
{
printf("\n Enter the end vertices of edge %d with its weight \n",i);
scanf("%d %d %d",&u,&v,&w);
dist[u][v]=w;
}
printf("\n Matrix of input data:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d \t",dist[i][j]);
printf("\n");
}
floyds(dist,n);
printf("\n Transitive closure:\n");
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
printf("%d \t",dist[i][j]);
printf("\n");
}
printf("\n The shortest paths are:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
if(i!=j)
printf("\n <%d,%d>=%d",i,j,dist[i][j]);
}
}

RESULT:
Thus, the program was executed successfully and the output was verified.

Ex.NO:5 DYNAMIC PROGRAMMING


d) KNAPSACK PROBLEM
19
AIM:
To write a C program to implement a knapsack problem using the Dynamic
programming technique.
DESCRIPTION:
KNAPSACK PROBLEM:
The knapsack problem is a classic optimization problem where you have to choose
a subset of items with some weight and profit and put them into a bag with capacity
W. Given a set of items, each with a weight and a value, determine which items to
include in the collection so that the total weight is less than or equal to a given limit
and the total value is as large as possible.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Read the input for the number of items, weight & value of items, and
knapsack capacity W.
STEP 3: for w := 0 to W do
STEP 4: Initialize V[0,w] :=0;
STEP 5: for i :=1 to n do
for w:=0 to W do
STEP 6: Check if (w[i]<=W) then,
STEP 7: V[i,w]=max{V[i-1,w],v[i]+V[i-1,w-w[i]]};
STEP 8: Otherwise, assign V[i,w]=V[i-1,w];
STEP 9: return V[n,W];
STEP 10: Stop the program.
PROGRAM:
#include <stdio.h>
// A utility function that returns a maximum of two integers
int max(int a, int b)
{
return (a > b) ? a : b;
}
// Returns the maximum value that can be put in a knapsack of capacity W
int knapSack(int W, int wt[], int val[], int n)
{
// Base Case
if (n == 0 || W == 0)
return 0;
// If weight of the nth item is more than Knapsack capacity W, then this item cannot
be included in the optimal solution
if (wt[n - 1] > W)
return knapSack(W, wt, val, n - 1);
// Return the maximum of two cases: (1) nth item included (2) not included
else
return max(val[n - 1]+ knapSack(W - wt[n - 1], wt, val, n - 1),knapSack(W, wt,
val, n - 1));
}
// Driver code
int main()
{
int profit[] = { 60, 100, 120 };
int weight[] = { 10, 20, 30 };
int W = 50;
int n = sizeof(profit) / sizeof(profit[0]);
printf("The Knapsack capacity is %d", knapSack(W, weight, profit, n));
20
return 0;
}

RESULT:
Thus, the program was executed successfully and the output was verified.

Ex.NO:6 GREEDY TECHNIQUE


a) DIJKSTRA’S ALGORITHM
AIM:
21
To write a C program to implement Dijkstra’s algorithm to find a single source
shortest path for the given weighted graph using Greedy Technique.
DESCRIPTION:
DIJKSTRA’S ALGORITHM:
Given a weighted graph and a source vertex in the graph, Dijkstra's algorithm
allows us to find the shortest paths from the source to all the other vertices in the
given graph.
ALGORITHM:
STEP 1: Start the program
STEP 2: Read the cost matrix of any weighted graph.
STEP 2: Choose a starting vertex and assign infinity path values to all other vertices.
STEP 3: Go to each vertex and update its path length.
STEP 4: If the path length of the adjacent vertex is lesser than the new path length,
don’t update it.
STEP 5: Avoid updating path lengths of already visited vertices.
STEP 6: After each iteration, we pick the unvisited vertex with the least path length.
STEP 7: Repeat until all the vertices have been visited.
STEP 8: Stop.
PROGRAM:
#include<stdio.h>
#define INFINITY 9999
#define MAX 10
void Dijkstra(int Graph[MAX][MAX], int n, int start);
void Dijkstra(int Graph[MAX][MAX], int n, int start)
{
int cost[MAX][MAX], distance[MAX], pred[MAX];
int visited[MAX], count, mindistance, nextnode, i, j;
// Creating cost matrix
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
if (Graph[i][j] == 0)
cost[i][j] = INFINITY;
else
cost[i][j] = Graph[i][j];
for (i = 0; i < n; i++)
{
distance[i] = cost[start][i];
pred[i] = start;
visited[i] = 0;
}
distance[start] = 0;
visited[start] = 1;
count = 1;
while (count < n - 1)
{
mindistance = INFINITY;
for (i = 0; i < n; i++)
if (distance[i] < mindistance && !visited[i])
{
mindistance = distance[i];
nextnode = i;
}
visited[nextnode] = 1;
22
for (i = 0; i < n; i++)
if (!visited[i])
if (mindistance + cost[nextnode][i] < distance[i])
{
distance[i] = mindistance + cost[nextnode][i];
pred[i] = nextnode;
}
count++;
}
// Printing the distance
for (i = 0; i < n; i++)
if (i != start)
{
printf("\n Distance from source to %d: %d", i, distance[i]);
}
}
int main()
{
int Graph[MAX][MAX], i, j, n, u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&Graph[i][j]);
printf("\nEnter the starting node:");
scanf("%d",&u);
Dijkstra(Graph, n, u);
return 0;
}

RESULT:
Thus, the program was executed successfully and the output was verified.

Ex.NO:6 GREEDY TECHNIQUE


b) HUFFMAN TREES AND CODES
AIM:
To write a C program to implement Huffman trees and codes to find the coding

23
for the symbols used in encoding data using Greedy Technique.
DESCRIPTION:
HUFFMAN TREES:
The Huffman tree is the binary tree with minimum external path weight, i.e., the
one with the minimum sum of weighted path lengths for the given set of leaves. Here
the goal is to build a tree with the minimum external path weight.
HUFFMAN CODING:
Huffman Coding is a technique of compressing data to reduce its size without
losing any of the details. It was first developed by David Huffman. Huffman Coding is
generally useful to compress the data in which there are frequently occurring
characters.
ALGORITHM:
Step 1: Start the program.
Step 2: Create a priority queue Q consisting of each unique character.
Step 3: Sort them in ascending order of their frequencies.
Step 4: For all unique characters:
 Create a new node.
 Extract the minimum value from Q and assign it to the left child of the new
node.
 Extract the minimum value from Q and assign it to the right child of the new
node.
 Calculate the sum of these two minimum values and assign it to the value of the
new node.
 Insert this new node into the tree.
Step 5: Return the root node.
Step 6: Stop the program.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#define MAX_TREE_HT 100
struct MinHeapNode {
char data;
unsigned freq;
struct MinHeapNode *left, *right;
};
struct MinHeap
{
unsigned size;
unsigned capacity;
struct MinHeapNode** array;
};
struct MinHeapNode* newNode(char data, unsigned freq)
{
struct MinHeapNode* temp = (struct MinHeapNode*)malloc(sizeof(struct
MinHeapNode));
temp->left = temp->right = NULL;
temp->data = data;
temp->freq = freq;
return temp;
}
struct MinHeap* createMinHeap(unsigned capacity)
{
24
struct MinHeap* minHeap = (struct MinHeap*)malloc(sizeof(struct MinHeap));
minHeap->size = 0;
minHeap->capacity = capacity;
minHeap->array = (struct MinHeapNode**)malloc(minHeap->capacity *
sizeof(struct MinHeapNode*));
return minHeap;
}
void swapMinHeapNode(struct MinHeapNode** a, struct MinHeapNode** b)
{
struct MinHeapNode* t = *a;
*a = *b;
*b = t;
}
void minHeapify(struct MinHeap* minHeap, int idx)
{
int smallest = idx;
int left = 2 * idx + 1;
int right = 2 * idx + 2;
if (left < minHeap->size && minHeap->array[left]->freq < minHeap-
>array[smallest]->freq)
smallest = left;
if (right < minHeap->size && minHeap->array[right]->freq < minHeap-
>array[smallest]->freq)
smallest = right;
if (smallest != idx) {
swapMinHeapNode(&minHeap->array[smallest], &minHeap->array[idx]);
minHeapify(minHeap, smallest);
}
}
int isSizeOne(struct MinHeap* minHeap)
{
return (minHeap->size == 1);
}
struct MinHeapNode* extractMin(struct MinHeap* minHeap)
{
struct MinHeapNode* temp = minHeap->array[0];
minHeap->array[0] = minHeap->array[minHeap->size - 1];
--minHeap->size;
minHeapify(minHeap, 0);
return temp;
}
void insertMinHeap(struct MinHeap* minHeap, struct MinHeapNode* minHeapNode)
{
++minHeap->size;
int i = minHeap->size - 1;
while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq)
{
minHeap->array[i] = minHeap->array[(i - 1) / 2];
i = (i - 1) / 2;
}
minHeap->array[i] = minHeapNode;
}
void buildMinHeap(struct MinHeap* minHeap)
25
{
int n = minHeap->size - 1;
int i;
for (i = (n - 1) / 2; i >= 0; --i)
minHeapify(minHeap, i);
}
void printArr(int arr[], int n)
{
int i;
for (i = 0; i < n; ++i)
printf("%d", arr[i]);
printf("\n");
}
int isLeaf(struct MinHeapNode* root)
{
return !(root->left) && !(root->right);
}
struct MinHeap* createAndBuildMinHeap(char data[], int freq[], int size)
{
int i;
struct MinHeap* minHeap = createMinHeap(size);
for(i = 0; i < size; ++i)
minHeap->array[i] = newNode(data[i], freq[i]);
minHeap->size = size;
buildMinHeap(minHeap);
return minHeap;
}
struct MinHeapNode* buildHuffmanTree(char data[], int freq[], int size)
{
struct MinHeapNode *left, *right, *top;
struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size);
while (!isSizeOne(minHeap))
{
left = extractMin(minHeap);
right = extractMin(minHeap);
top = newNode('$', left->freq + right->freq);
top->left = left;
top->right = right;
insertMinHeap(minHeap, top);
}
return extractMin(minHeap);
}
void printCodes(struct MinHeapNode* root, int arr[], int top)
{
if (root->left)
{
arr[top] = 0;
printCodes(root->left, arr, top + 1);
}
if (root->right)
{
arr[top] = 1;
printCodes(root->right, arr, top + 1);
26
}
if (isLeaf(root))
{
printf("%c: ", root->data);
printArr(arr, top);
}
}
void HuffmanCodes(char data[], int freq[], int size)
{
struct MinHeapNode* root = buildHuffmanTree(data, freq, size);
int arr[MAX_TREE_HT], top = 0;
printCodes(root, arr, top);
}
int main()
{
char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
int freq[] = { 5, 9, 12, 13, 16, 45 };
int size = sizeof(arr) / sizeof(arr[0]);
HuffmanCodes(arr, freq, size);
return 0;
}

RESULT:
Thus, the program was executed successfully and the output was verified.

Ex.NO:6 GREEDY TECHNIQUE


c) KNAPSACK PROBLEM
AIM:
To write a C program to implement a knapsack problem using the greedy
technique.

27
DESCRIPTION:
KNAPSACK PROBLEM:
Given a set of items, each with a weight and a value. Determine the number of
each item to include in a collection so that the total weight is less than a given limit
and the total value is as large as possible. The basic idea of the greedy approach is to
calculate the ratio profit/weight for each item and sort the item based on this ratio.
Then take the item with the highest ratio and add as much as we can (can be the
whole element or a fraction of it). This will always give the maximum profit because,
in each step, it adds an element such that this is the maximum possible profit for that
much weight.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Read the input for the number of items, weight & value of items, and
knapsack capacity W.
STEP 3: Calculate the ratio (profit/weight) for each item.
STEP 4: Sort all the items in decreasing order of the ratio.
STEP 5: Initialize profit tp =0.
STEP 6: Do the following for every item i in the sorted order:
6.1. Check if the weight of the current item is less than or equal to the remaining
capacity then add the value of that item to the profit.
6.2. Otherwise, add a fraction of the current item.
STEP 7: Return the result vector and the profit.
STEP 8: Stop the program.
PROGRAM:
# include<stdio.h>
void knapsack(int n, float weight[], float profit[], float capacity) {
float x[20], tp = 0;
int i, j, u;
u = capacity;
for (i = 0; i < n; i++)
x[i] = 0.0;
for (i = 0; i < n; i++) {
if (weight[i] > u)
break;
else {
x[i] = 1.0;
tp = tp + profit[i];
u = u - weight[i];
}
}
if (i < n)
x[i] = u / weight[i];
tp = tp + (x[i] * profit[i]);
printf("\nThe result vector is:- ");
for (i = 0; i < n; i++)
printf("%f\t", x[i]);
printf("\nMaximum profit is:- %f", tp);
}
int main() {
float weight[20], profit[20], capacity;
int num, i, j;
float ratio[20], temp;
28
printf("\nEnter the no. of objects:- ");
scanf("%d", &num);
printf("\nEnter the weights and profits of each object:\n ");
for (i = 0; i < num; i++) {
scanf("%f %f", &weight[i], &profit[i]);
}
printf("\nEnter the capacity of knapsack:- ");
scanf("%f", &capacity);
for (i = 0; i < num; i++) {
ratio[i] = profit[i] / weight[i];
}
for (i = 0; i < num; i++) {
for (j = i + 1; j < num; j++) {
if (ratio[i] < ratio[j]) {
temp = ratio[j];
ratio[j] = ratio[i];
ratio[i] = temp;

temp = weight[j];
weight[j] = weight[i];
weight[i] = temp;

temp = profit[j];
profit[j] = profit[i];
profit[i] = temp;
}
}
}
knapsack(num, weight, profit, capacity);
return(0);
}

RESULT:
Thus, the program was executed successfully and the output was verified.

Ex.NO:7 ITERATIVE IMPROVEMENT


SIMPLEX METHOD
AIM:
To write a C program to implement simplex method using Iterative
improvement technique.
29
ALGORITHM:
STEP 1: Initialize the tableau with the coefficients of the constraints and objective
function, and read the tableau from a file.
STEP 2: Select the pivot column, which is the most negative column in the objective
function row (mat[0][1..n]).
STEP 3: Select the pivot row, which is the row with the smallest positive ratio of the
right-hand side to the pivot column element.
STEP 4: Perform the pivot operation by dividing the pivot row by the pivot element,
and then for each remaining row in the tableau.
STEP 5: Eliminate the pivot column by subtracting the product of the pivot element
and the element in the pivot column from each element in that row.
STEP 5: Repeat steps 2-4 until the objective function is no longer negative or the
algorithm reaches an optimal solution.
STEP 6: The optimal solution is the last basic feasible solution when the objective
function is no longer negative.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <assert.h>
#define M 20
#define N 20
static const double epsilon = 1.0e-8;
int equal(double a, double b) { return fabs(a-b) < epsilon; }
typedef struct {
int m, n; // m=rows, n=columns, mat[m x n]
double mat[M][N];
} Tableau;
void nl(int k){ int j; for(j=0;j<k;j++) putchar('-'); putchar('\n'); }
void print_tableau(Tableau *tab, const char* mes) {
static int counter=0;
int i, j;
printf("\n%d. Tableau %s:\n", ++counter, mes);
nl(70);
printf("%-6s%5s", "col:", "b[i]");
for(j=1;j<tab->n; j++) { printf(" x%d,", j); } printf("\n");
for(i=0;i<tab->m; i++) {
if (i==0) printf("max:"); else
printf("b%d: ", i);
for(j=0;j<tab->n; j++) {
if (equal((int)tab->mat[i][j], tab->mat[i][j]))
printf(" %6d", (int)tab->mat[i][j]);
else
printf(" %6.2lf", tab->mat[i][j]);
}
printf("\n");
}
nl(70);
}
void read_tableau(Tableau *tab, const char * filename) {
int err, i, j;
FILE * fp;
30
fp = fopen(filename, "r" );
if( !fp ) {
printf("Cannot read %s\n", filename); exit(1);
}
memset(tab, 0, sizeof(*tab));
err = fscanf(fp, "%d %d", &tab->m, &tab->n);
if (err == 0 || err == EOF) {
printf("Cannot read m or n\n"); exit(1);
}
for(i=0;i<tab->m; i++) {
for(j=0;j<tab->n; j++) {
err = fscanf(fp, "%lf", &tab->mat[i][j]);
if (err == 0 || err == EOF) {
printf("Cannot read A[%d][%d]\n", i, j); exit(1);
}
}
}
printf("Read tableau [%d rows x %d columns] from file '%s'.\n",
tab->m, tab->n, filename);
fclose(fp);
}
void pivot_on(Tableau *tab, int row, int col) {
int i, j;
double pivot;
pivot = tab->mat[row][col];
assert(pivot>0);
for(j=0;j<tab->n;j++)
tab->mat[row][j] /= pivot;
assert( equal(tab->mat[row][col], 1. ));
for(i=0; i<tab->m; i++) { // foreach remaining row i do
double multiplier = tab->mat[i][col];
if(i==row) continue;
for(j=0; j<tab->n; j++) { // r[i] = r[i] - z * r[row];
tab->mat[i][j] -= multiplier * tab->mat[row][j];
}
}
}
// Find pivot_col = most negative column in mat[0][1..n]
int find_pivot_column(Tableau *tab) {
int j, pivot_col = 1;
double lowest = tab->mat[0][pivot_col];
for(j=1; j<tab->n; j++) {
if (tab->mat[0][j] < lowest) {
lowest = tab->mat[0][j];
pivot_col = j;
}
}
printf("Most negative column in row[0] is col %d = %g.\n", pivot_col, lowest);
if( lowest >= 0 ) {
return -1; // All positive columns in row[0], this is optimal.
}
return pivot_col;
}
31
// Find the pivot_row, with smallest positive ratio = col[0] / col[pivot]
int find_pivot_row(Tableau *tab, int pivot_col) {
int i, pivot_row = 0;
double min_ratio = -1;
printf("Ratios A[row_i,0]/A[row_i,%d] = [",pivot_col);
for(i=1;i<tab->m;i++){
double ratio = tab->mat[i][0] / tab->mat[i][pivot_col];
printf("%3.2lf, ", ratio);
if ( (ratio > 0 && ratio < min_ratio ) || min_ratio < 0 ) {
min_ratio = ratio;
pivot_row = i;
}
}
printf("].\n");
if (min_ratio == -1)
return -1; // Unbounded.
printf("Found pivot A[%d,%d], min positive ratio=%g in row=%d.\n",
pivot_row, pivot_col, min_ratio, pivot_row);
return pivot_row;
}
void add_slack_variables(Tableau *tab) {
int i, j;
for(i=1; i<tab->m; i++) {
for(j=1; j<tab->m; j++)
tab->mat[i][j + tab->n -1] = (i==j);
}
tab->n += tab->m -1;
}
void check_b_positive(Tableau *tab) {
int i;
for(i=1; i<tab->m; i++)
assert(tab->mat[i][0] >= 0);
}
// Given a column of identity matrix, find the row containing 1.
// return -1, if the column as not from an identity matrix.
int find_basis_variable(Tableau *tab, int col) {
int i, xi=-1;
for(i=1; i < tab->m; i++) {
if (equal( tab->mat[i][col],1) ) {
if (xi == -1)
xi=i; // found first '1', save this row number.
else
return -1; // found second '1', not an identity matrix.

} else if (!equal( tab->mat[i][col],0) ) {


return -1; // not an identity matrix column.
}
}
return xi;
}
void print_optimal_vector(Tableau *tab, char *message) {
int j, xi;
printf("%s at ", message);
32
for(j=1;j<tab->n;j++) { // for each column.
xi = find_basis_variable(tab, j);
if (xi != -1)
printf("x%d=%3.2lf, ", j, tab->mat[xi][0] );
else
printf("x%d=0, ", j);
}
printf("\n");
}
void simplex(Tableau *tab) {
int loop=0;
add_slack_variables(tab);
check_b_positive(tab);
print_tableau(tab,"Padded with slack variables");
while( ++loop ) {
int pivot_col, pivot_row;
pivot_col = find_pivot_column(tab);
if( pivot_col < 0 ) {
printf("Found optimal value=A[0,0]=%3.2lf (no negatives in row 0).\n",
tab->mat[0][0]);
print_optimal_vector(tab, "Optimal vector");
break;
}
printf("Entering variable x%d to be made basic, so pivot_col=%d.\n",
pivot_col, pivot_col);

pivot_row = find_pivot_row(tab, pivot_col);


if (pivot_row < 0) {
printf("unbounded (no pivot_row).\n");
break;
}
printf("Leaving variable x%d, so pivot_row=%d\n", pivot_row, pivot_row);
pivot_on(tab, pivot_row, pivot_col);
print_tableau(tab,"After pivoting");
print_optimal_vector(tab, "Basic feasible solution");
if(loop > 20) {
printf("Too many iterations > %d.\n", loop);
break;
}
}
}
Tableau tab = { 4, 5, { // Size of tableau [4 rows x 5 columns ]
{ 0.0 , -0.5 , -3.0 ,-1.0 , -4.0, }, // Max: z = 0.5*x + 3*y + z + 4*w,
{ 40.0 , 1.0 , 1.0 , 1.0 , 1.0, }, // x + y + z + w <= 40 .. b1
{ 10.0 , -2.0 , -1.0 , 1.0 , 1.0, }, // -2x - y + z + w <= 10 .. b2
{ 10.0 , 0.0 , 1.0 , 0.0 , -1.0, }, // y - w <= 10 .. b3
}
};
int main(int argc, char *argv[]){
if (argc > 1) { // usage: cmd datafile
read_tableau(&tab, argv[1]);
}
print_tableau(&tab,"Initial");
33
simplex(&tab);
return 0;
}

RESULT:
Thus, the program was executed successfully and the output was verified.

Ex.NO:8 BACK TRACKING


a) SUBSET SUM PROBLEM
AIM:
To write a C program to implement subset sum problem using Backtracking
technique.
DESCRIPTION:
SUBSET SUM PROBLEM:
To find subset of elements that are selected from a given set whose sum adds
up to a given number K. We are considering the set contains non-negative values. It is
34
assumed that the input set is unique (no duplicates are presented).
ALGORITHM:
STEP 1: Start with an empty set.
STEP 2: Add the next element from the list to the set.
STEP 3: If the subset is having sum M, then stop with that subset as solution.
STEP 4: If the subset is not feasible or if we have reached the end of the set, then
backtrack through the subset until we find the most suitable value.
STEP 5: If the subset is feasible (sum of subset < M) then go to step 2.
STEP 6: If we have visited all the elements without finding a suitable subset and if no
backtracking is possible then stop without solution.
STEP 7: Stop the program.
PROGRAM:
#include<stdio.h>
#include<conio.h>
void SumOfSub(int,int,int);
int x[25],n,m=0,sum=0,w[25];;
void readf()
{
int i;
printf("\n Enter the no of values in the set:");
scanf("%d",&n);
printf("\n Enter the %d weights of the values in the set:",n);
for(i=1;i<=n;i++)
{
scanf("%d",&w[i]);
sum=sum+w[i];
x[i]=0;
}
printf("\n Enter the required sum of the values in the subset:");
scanf("%d",&m);
printf("\n The Total sum of the weights is:%d",sum);
SumOfSub(0,1,sum);
}
void SumOfSub(int s,int k,int r)
{
int i,j;
x[k]=1;
if(sum>=m)
{
if(s+w[k]==m)
{
printf("\n");
for(j=1;j<=n;j++)
{
printf("%d\t",x[j]);
}
printf("\n-->");
for(j=1;j<=k;j++)
{
if(x[j] == 1)
printf("%d\t",w[j]);
}
}
35
else if(s+w[k]+w[k+1]<=m)
SumOfSub(s+w[k],k+1,r-w[k]);
if((s+r-w[k]>=m) && (s+w[k+1]<=m))
{
x[k]=0;
SumOfSub(s,k+1,r-w[k]);
}
}
else
{
printf("\n No Solutions Available because sum of all weights is %d less than required
sum %d",sum,m);
}
}
int main()
{
readf();
return 0;
}

RESULT:
Thus, the program was executed successfully and the output was verified.

Ex.NO:8 BACK TRACKING


b) N-QUEEN PROBLEM
AIM:
To write a C program to implement N – Queen problem using Backtracking
technique.
ALGORITHM:
STEP 1: Start in the leftmost column.
STEP 2: If all queens are placed return true.
STEP 3: Try all rows in the current column.
Do following for every unoccupied row.
36
a) If the queen can be placed safely in this row, then mark this [row, column]
as part of the solution and recursively check if placing queen here leads to a
solution.
b) If placing the queen in [row, column] leads to a solution then return true.
c) If placing queen doesn't lead to a solution then unmark this [row, column]
(Backtrack) and go to step (a) to try other rows.
STEP 4: If all rows have been tried and nothing worked, return false to trigger
backtracking.
STEP 5: Stop the program.
PROGRAM:
#include<stdio.h>
#include<math.h>
int a[30],count=0;
int place(int pos)
{
int i;
for(i=1;i<pos;i++){
if((a[i]==a[pos])||((abs(a[i]-a[pos])==abs(i-pos))))
return 0;
}
return 1;
}
void print_sol(int n)
{
int i,j;
count++;
printf("\n\nSolution #%d:\n",count);
for(i=1;i<=n;i++){
for(j=1;j<=n;j++)
{
if(a[i]==j)
printf("Q\t");
else
printf("*\t");
}
printf("\n");
}
}
void queen(int n){
int k=1;
a[k]=0;
while(k!=0){
a[k]=a[k]+1;
while((a[k]<=n)&&!place(k))
a[k]++;
if(a[k]<=n){
if(k==n)
print_sol(n);
else
{
k++;
a[k]=0;
}
37
}
else
k--;
}
}
void main(){
int i,n;
printf("Enter the number of Queens\n");
scanf("%d",&n);
queen(n);
printf("\nTotal solutions=%d",count);
}

RESULT:
Thus, the program was executed successfully and the output was verified.

Ex.NO:9 BRANCH AND BOUND


a) ASSIGNMENT PROBLEM
AIM:
To write a C program to implement assignment problem using branch and bound
technique.
ALGORITHM:
STEP 1: Initialize the variables and arrays: Set the minimum cost to a large value,
initialize the row_covered and col_covered arrays to 0, and initialize the path
and min_path arrays to -1.
STEP 2: Define the recursive function findMinCost() that takes in the current cost,
current worker, and current level as input.
38
STEP 3: In the findMinCost() function, check if the current level is equal to the number
of workers. If it is, compare the current cost to the minimum cost. If the current
cost is less than the minimum cost, update the minimum cost and copy the
current path to the min_path.
STEP 4: If the current level is not equal to the number of workers, iterate through all
the jobs and check if the current worker and job can be assigned using the
isSafe() function. If the assignment is valid, mark the current worker and job as
assigned, and call the findMinCost() function recursively with the updated cost,
worker, and level.
STEP 5: After the recursive call, unmark the current worker and job as assigned, and
continue the loop to check the next job.
STEP 6: Once all possible assignments have been checked and the minimum cost and
optimal assignment have been found, call the printAssignment() function to
print the results.
STEP 7: The algorithm terminates when the function findMinCost is called with a level
of N, at this point we have the optimal solution.
PROGRAM:
#include <stdio.h>
#include <stdbool.h>
#include <limits.h>
#define N 4
int cost[N][N] = { { 90, 75, 75, 80 },
{ 35, 85, 55, 65 },
{ 125, 95, 90, 105 },
{ 45, 110, 95, 115 } };
int row_covered[N], col_covered[N];
int path[N], min_path[N];
int min_cost;
void printAssignment()
{
int i;
printf("The Optimal Assignment is: \n");
for (i = 0; i < N; i++)
printf("Worker %d -> Job %d\n", i + 1, min_path[i] + 1);
printf("\nMinimum Cost: %d\n", min_cost);
}
bool isSafe(int i, int j)
{
return (row_covered[i] == 0 && col_covered[j] == 0);
}
void findMinCost(int curr_cost, int curr_worker, int level)
{
int i;
if (level == N)
{
if (curr_cost < min_cost)
{
min_cost = curr_cost;
for (i = 0; i < N; i++)
min_path[i] = path[i];
}
return;
}
39
for (i = 0; i < N; i++)
{
if (isSafe(curr_worker, i))
{
path[level] = i;
row_covered[curr_worker] = 1;
col_covered[i] = 1;
findMinCost(curr_cost + cost[curr_worker][i], curr_worker + 1, level + 1);
row_covered[curr_worker] = 0;
col_covered[i] = 0;
}
}
}
int main()
{
min_cost = INT_MAX;
findMinCost(0, 0, 0);
printAssignment();
return 0;
}

RESULT:
Thus, the program was executed successfully and the output was verified.

Ex.NO:9 BRANCH AND BOUND


b) TRAVELLING SALESMAN PROBLEM
AIM:
To write a C program to implement Travelling salesman problem using branch
and bound technique.
ALGORITHM:
STEP 1: Input the number of cities and the cost matrix for traveling between them.
STEP 2: Initialize the current city as the starting point and mark it as visited.
STEP 3: Find the next city to visit by selecting the city with the least cost from the
current city using the "least" function.
STEP 4: Mark the new city as visited and add the cost of the path to the total cost.
STEP 5: Repeat steps 3 and 4 until all cities have been visited.
40
STEP 6: Return to the starting city and add the final cost of the path.
STEP 7: Keep track of the minimum cost of the path so far, and prune any branches
that have a cost greater than this minimum.
STEP 8: The final result is the minimum cost path that visits each city once and
returns to the starting city.
PROGRAM:
#include<stdio.h>
#include<conio.h>
int a[10][10], visited[10], n, cost = 0;
void get() {
int i, j;
printf("Enter No. of Cities: ");
scanf("%d", &n);
printf("\nEnter Cost Matrix: \n");
for (i = 0; i < n; i++) {
printf("Enter Elements of Row %d:\n", i + 1);
for (j = 0; j < n; j++)
scanf("%d", &a[i][j]);
visited[i] = 0;
}
printf("\n\nThe cost list is:\n\n");
for (i = 0; i < n; i++) {
printf("\n\n");
for (j = 0; j < n; j++)
printf("\t % d", a[i][j]);
}
}
int least(int c) {
int i, nc = 999;
int min = 999, kmin;
for (i = 0; i < n; i++) {
if ((a[c][i] != 0) && (visited[i] == 0))
if (a[c][i] < min) {
min = a[i][0] + a[c][i];
kmin = a[c][i];
nc = i;
}
}
if (min != 999)
cost += kmin;
return nc;
}
void mincost(int city) {
int i, ncity;
visited[city] = 1;
printf("%d ->", city + 1);
ncity = least(city);
if (ncity == 999) {
ncity = 0;
printf("%d", ncity + 1);
cost += a[city][ncity];
return;
}
41
mincost(ncity);
}
void put() {
printf("\n\nMinimum cost:");
printf("%d", cost);
}
int main()
{
get();
printf("\n\nThe Path is:\n\n");
mincost(0);
put();
}

RESULT:
Thus, the program was executed successfully and the output was verified.

42

You might also like