Daa Manual 2 PDF
Daa Manual 2 PDF
Manavilai, Vellichanthai-629203
KanyaKumari District
LABORATORY RECORD
REGISTER NUMBER :
YEAR/SEM :
ARUNACHALA COLLEGE OF ENGINEERING FOR WOMEN
Manavilai, Vellichanthai-629203
Kanyakumari District
This record is submitted for the Practical University Examination held on …………………………..
Sl.
No. Date Program Name Signature
2
Ex No: 1a Factorial of a Number Using Recursion
Date:
Algorithm
• Start
• Get the input from the user, by using the entered value the fact() is called
• The n-1 value is passed to fact() from the function
• Every time the function is called the n value is decremented by 1
• Once the value of n is 1, the recursive function will be stopped and send the value to the main()
function.
• End
Program
#include<stdio.h>
long int fact(int x);
int main()
{
int x;
printf("Enter A Number To Find Factorial: ");
scanf("%d",&x);
printf("The Factorial of %d = %ld", x, fact(x));
return 0;
}
Output:
Enter A Number To Find Factorial: 7
The Factorial of 7 = 5040
3
Ex No: 1b Factorial Of A Number Using Non-Recursion
Date:
Output
Enter a number: 7
Factorial of 7 is 5040
Result: Thus the Program to implementing factorial of a number using non-recursion was executed and
verified successfully
4
Ex No: 2a Fibonacci series using non-recursion algorithms
Date:
Aim: To write a program for implementing Fibonacci series using non-recursion algorithms.
Algorithm
• Start.
• Read the integer x1, x2, and x3 are used to hold the Fibonacci sequence elements, and the
variable num is used to store the number of elements in the Fibonacci series.
• Enter the number of elements they want in the Fibonacci series using the printf and scanf
functions.
• The loop starts from a = 2 because the first two Fibonacci numbers 0 and 1 are already known
and printed outside the loop.
• Fibonacci Calculation: F(n) = F(n-1) + F(n-2).
• The printf statement inside the loop prints the value of x3, which is the next Fibonacci number in
the series.
• After printing the x3 value, the variables x1 and x2 are shifted to hold the values of the two
previous Fibonacci numbers for the next iteration.
• The program returns 0, indicating successful completion of the main function.
• End.
Program
#include<stdio.h>
int main()
{
int x1=0,x2=1,x3,a,num;
printf("Enter the number of elements:");
scanf("%d",&num);
printf("\n%d %d",x1,x2);//printing 0 and 1
for(a=2;a<num;++a)//loop starts from 2 because 0 and 1 are already printed
{
x3=x1+x2;
printf(" %d",x3);
x1=x2;
x2=x3;
}
return 0;
}
Output:
Enter the number of elements:15
Result: Thus the Program to implementing Fibonacci series using non-recursion algorithms was
executed and verified successfully
5
Ex No: 2b Fibonacci series using recursion algorithms
Date:
Aim: To write a program for implementing Fibonacci series using recursion algorithms.
Algorithm
• Start.
• variable a is initialized with the value 9 which represents the desired position of the Fibonacci
number in the sequence that we want to find.
• The printf statement in the main function prints the result.
• Fibonacci function to calculate the 9th Fibonacci number (a),
• displays the result with the format string: "%dth Fibonacci Number: %d".
• End.
Program
#include <stdio.h>
int fibonacci(int x)
{
if (x <= 1)
return x;
return fibonacci(x - 1) + fibonacci(x - 2);
}
int main()
{
int a = 9;
printf("%dth Fibonacci Number: %d", a, fibonacci(a));
return 0;
}
Output:
Result: Thus the Program to implementing Fibonacci series using recursion algorithms was executed and
verified successfully
6
Ex No: 3 Coin Change Problem with Dynamic Approach
Date:
Aim: To write a program for coin change problem with dynamic approach
Algorithm
4. Column: Total amount (sum). Because the first-column index is 0, the sum value is 0. The second
column index is 1, so the sum of the coins should be 1. Similarly, the third column value is 2, so a
change of 2 is required, and so on.
• If the coin value is greater than the dynamicprogSum, the coin is ignored, i.e.
dynamicprogTable[i][j]=dynamicprogTable[i-1][j].
• If the coin value is less than the dynamicprogSum, you can consider it, i.e.
dynamicprogTable[i][j]=dynamicprogTable[i-1].[dynamicprogSum]+dynamicprogTable[i][j-coins[i-
1]].
Program
#include <stdio.h>
int coins[] = {1,2,3}, sum=4;
int numberofCoins = 3;
//Function to initialize 1st column of dynamicprogTable with 1
void initdynamicprogTable(int dynamicprogTable[][5])
{
int i;
//First row to 0
for(i=1; i<=sum+1; i++)
{
dynamicprogTable[0][i] = 0;
7
}
//First column to 1
for(i=1; i<=numberofCoins; i++)
{
dynamicprogTable[i][0] = 1;
}
}
int solution(int dynamicprogTable[][5])
{
int coinindex, dynamicprogSum;
for(coinindex=1; coinindex<numberofCoins+1; coinindex++)
{
for(dynamicprogSum=1; dynamicprogSum< 5; dynamicprogSum++)
{
//value of coin should be less than or equal to sum value to consider it
if(coins[coinindex-1] > dynamicprogSum)
dynamicprogTable[coinindex][dynamicprogSum] =
dynamicprogTable[coinindex1][dynamicprogSum];
else
dynamicprogTable[coinindex][dynamicprogSum] = dynamicprogTable[coinindex-
1][dynamicprogSum]+dynamicprogTable[coinindex][dynamicprogSum-coins[coinindex-1]];
}
}
//return final row and column value
return dynamicprogTable[numberofCoins][sum];
}
int main()
{
int dynamicprogTable[numberofCoins+1][5];
initdynamicprogTable(dynamicprogTable);
printf("Total Solutions: %d",solution(dynamicprogTable));
return 0;
}
Output
Result: Thus the Program for coin change problem with dynamic approach was executed and verified
successfully.
8
Ex No:4 Strassen’s Matrix Multiplication
Date:
Aim: To write a program for strassen’s Matrix Multiplication
Algorithm
1. Divide the input matrices A and B into four equal-sized sub-matrices each.
2. Compute seven matrix multiplications recursively as follows:
- Multiply the top left sub-matrix of A with the top left sub-matrix of B.
- Multiply the top right sub-matrix of A with the bottom left sub-matrix of B.
- Multiply the bottom left sub-matrix of A with the top right sub-matrix of B.
- Multiply the bottom right sub-matrix of A with the bottom right sub-matrix of B.
- Add the results of these multiplications together to obtain four intermediate resultmatrices.
3. Combine the four intermediate result matrices to form the final result matrix:
- Construct the top left quadrant of the final result matrix by adding the top left andtopright
intermediate matrices.
- Construct the bottom left quadrant of the final result matrix by adding the bottomleftand
bottom right intermediate matrices.
- Construct the top right quadrant of the final result matrix by subtracting the topleft
intermediate matrix from the top right intermediate matrix.
- Construct the bottom right quadrant of the final result matrix by subtracting thebottom left
intermediate matrix from the bottom right intermediate matrix.
4. The final result matrix is the product of the input matrices A and B.
Program
#include<stdio.h>
int main()
{
int z[2][2];
int i, j;
int m1, m2, m3, m4 , m5, m6, m7;
intx[2][2] = {{12, 34},{22, 10}};
int y[2][2] = {{3, 4}{2, 1}};
printf("\nThe first matrix is\n");
for(i= 0; i < 2; i++)
{
printf("\n");
for(j = 0; j < 2; j++)
printf("%d\t", x[i][j]);
}
printf("\nThe second matrix is\n");
9
for(i = 0; i < 2; i++)
{
printf("\n");
for(j = 0; j < 2; j++)
printf("%d\t", y[i][j]);
}
m1= (x[0][0] + x[1][1]) * (y[0][0] + y[1][1]);
m2= (x[1][0] + x[1][1]) * y[0][0];
m3= x[0][0] * (y[0][1] - y[1][1]);
m4= x[1][1] * (y[1][0] - y[0][0]);
m5= (x[0][0] + x[0][1]) * y[1][1];
m6= (x[1][0] - x[0][0]) * (y[0][0]+y[0][1]);
m7= (x[0][1] - x[1][1]) * (y[1][0]+y[1][1]);
z[0][0]= m1 + m4- m5 + m7;
z[0][1] = m3 + m5;
z[1][0] = m2 + m4;
z[1][1] = m1 - m2 + m3 + m6;
printf("\nProduct achieved using Strassen's algorithm \n");
for(i = 0; i < 2 ; i++)
{
printf("\n");
for(j = 0; j < 2; j++)
printf("%d\t", z[i][j]);
}
return 0;
}
Output
Result: Thus the Program to multiply two matrices using strassens algorithm was executed and
verified successfully.
10
Ex No:5 Transform and conquer – Heap sort
Date:
Algorithm
1. Start
2. Print the unsorted array.
3. Creating the binary heap of the array.
4. Start iteration from the last leaf node of the heap to the root node.
5. Each iteration swaps the root node with the last leaf node and then calls the
heapify operation to rearrange the heap.
6. On heapify operation, swap the larger children element with the root node if
the root is smaller than the child.
7. Print the sorted array.
8. Stop.
Program
#include <stdio.h>
// Function to swap two elements
void swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
11
largest = right;
}
// If largest is not the root, swap the root with the largest element
if (largest != index) {
swap(&array[index], &array[largest]);
// Recursively heapify the affected sub-tree
heapify(array, size, largest);
}
}
12
printf("Original array: ");
printArray(arr, size);
heapSort(arr, size);
printf("Sorted array: ");
printArray(arr, size);
return 0;
}
Output:
Original array: 54 32 67 12 90 5
Sorted array: 5 12 32 54 67 90
Result: Thus the implementation of heap sort was done and verified successfully
13
Ex No:6 Dynamic Programming – FLOYD ALGORITHM
Date:
Aim: To write a c program for Dynamic Programming – FLOYD ALGORITHM
Algorithm
1. Start
2. Declare the variables.
3. Read the number of vertices and edges of the graph.
4. It takes the adjacency matrix as input and it find the transitive closure of the given graph.
5. Print the matrix
6.Stop.
Program
#include<stdio.h>
void floyd(int a[4][4], int n)
{
for(int k=0;k<n;k++)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(a[i][j]>a[i][k]+a[k][j])
{
a[i][j]=a[i][k]+a[k][j];
}
}
}
}
printf("All Pairs Shortest Path is :\n");
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
}
int main()
{
int cost[4][4] = {{0, 3, 999, 4}, {8, 0, 2, 999}, {5, 999, 0, 1}, {2, 999, 999, 0}};
int n = 4;
floyd(cost,n);
}
14
Output:
All Pairs Shortest Path is :
0354
5023
3601
2570
Result: Thus the implementation of FLOYD algorithm was done and verified successfully
15
Ex No: 7 Greedy technique – Dijkstra’s algorithm
Date:
Algorithm
2. Choose a starting vertex and assign infinity path values to all other devices
4. If the path length of the adjacent vertex is lesser than new path length, don't update it
6. After each iteration, we pick the unvisited vertex with the least path length. So we
choose 5 before 7
7. Notice how the rightmost vertex has its path length updated twice
Graph[1][0] = 0;
Graph[1][1] = 0;
Graph[1][2] = 2;
Graph[1][3] = 0;
Graph[1][4] = 0;
Graph[1][5] = 3;
Graph[1][6] = 0;
Graph[2][0] = 1;
17
Graph[2][1] = 2;
Graph[2][2] = 0;
Graph[2][3] = 1;
Graph[2][4] = 3;
Graph[2][5] = 0;
Graph[2][6] = 0;
Graph[3][0] = 2;
Graph[3][1] = 0;
Graph[3][2] = 1;
Graph[3][3] = 0;
Graph[3][4] = 0;
Graph[3][5] = 0;
Graph[3][6] = 1;
Graph[4][0] = 0;
Graph[4][1] = 0;
Graph[4][2] = 3;
Graph[4][3] = 0;
Graph[4][4] = 0;
Graph[4][5] = 2;
Graph[4][6] = 0;
Graph[5][0] = 0;
Graph[5][1] = 3;
Graph[5][2] = 0;
Graph[5][3] = 0;
Graph[5][4] = 2;
Graph[5][5] = 0;
Graph[5][6] = 1;
Graph[6][0] = 0;
Graph[6][1] = 0;
Graph[6][2] = 0;
Graph[6][3] = 1;
Graph[6][4] = 0;
Graph[6][5] = 1;
Graph[6][6] = 0;
u = 0;
Dijkstra(Graph, n, u);
return 0;
}
18
Output
Distance from source to 1: 3
Result: Thus the implementation of Dijkstra’s algorithm was done and verified successfully
19
Ex No: 8 Backtracking – n-queens problem
Date:
Algorithm
1. Start
2. N Queen’s problem is the puzzle.
3. Placing chess queens on a chessboard, so that no two queensattack each other.
4. Here we use the Brute-Force method to solve the problem.
5. Stop
Program
#include<stdio.h>
#define BOARD_SIZE 5
void displayChess(int chBoard[BOARD_SIZE][BOARD_SIZE]) {
for (int row = 0; row < BOARD_SIZE; row++) {
for (int col = 0; col < BOARD_SIZE; col++)
printf("%d ", chBoard[row][col]);
printf("\n");
}
}
int isQueenPlaceValid(int chBoard[BOARD_SIZE][BOARD_SIZE], int crntRow, int crntCol) {
// checking if queen is in the left or not
for (int i = 0; i < crntCol; i++)
if (chBoard[crntRow][i])
return 0;
for (int i = crntRow, j = crntCol; i >= 0 && j >= 0; i--, j--)
//checking if queen is in the left upper diagonal or not
if (chBoard[i][j])
return 0;
for (int i = crntRow, j = crntCol; j >= 0 && i < BOARD_SIZE; i++, j--)
//checking if queen is in the left lower diagonal or not
if (chBoard[i][j])
return 0;
return 1;
}
int solveProblem(int chBoard[BOARD_SIZE][BOARD_SIZE], int crntCol) {
20
//when N queens are placed successfully
if (crntCol >= BOARD_SIZE)
return 1;
// checking placement of queen is possible or not
for (int i = 0; i < BOARD_SIZE; i++) {
if (isQueenPlaceValid(chBoard, i, crntCol)) {
//if validate, place the queen at place (i, col)
chBoard[i][crntCol] = 1;
//Go for the other columns recursively
if (solveProblem(chBoard, crntCol + 1))
return 1;
//When no place is vacant remove that queen
chBoard[i][crntCol] = 0;
}
}
return 0;
}
int displaySolution() {
int chBoard[BOARD_SIZE][BOARD_SIZE];
for(int i = 0; i < BOARD_SIZE; i++)
for(int j = 0; j < BOARD_SIZE; j++)
//set all elements to 0
chBoard[i][j] = 0;
//starting from 0th column
if (solveProblem(chBoard, 0) == 0) {
printf("Solution does not exist");
return 0;
}
displayChess(chBoard);
return 1;
}
int main()
{
displaySolution();
return 0;
}
21
Output:
10000
00010
01000
00001
00100
Result: Thus the implementation of N-Queens Problem was done and verified successfully.
22
Ex No: 9 Branch and bound – traveling salesman problem
Date:
Aim: To write the c program for Branch and bound – traveling salesmanproblem
Algorithm:
1. Start
2. Read the number of cities and the cost matrix.
3. Find the path with minimum cost using mincost()
function.
4.4.Print the path with least cost.
5.Sto #include<stdio.h>
int ary[10][10],completed[10],n,cost=0;
void takeInput()
{
int i,j;
completed[i]=0;
}
completed[city]=1;
printf("%d--->",city+1);
ncity=least(city);
if(ncity==999)
{
ncity=0;
printf("%d",ncity+1);
cost+=ary[city][ncity];
return;
}
mincost(ncity);
}
int least(int c)
{
int i,nc=999;
int min=999,kmin;
if(min!=999)
cost+=kmin;
return nc;
}
int main()
{
takeInput();
return 0;
}
p
Program
OUTPUT:
Enter the number of villages: 4
Enter the Cost Matrix
Minimum cost is 7
Result: Thus the implementation of Traveling Salesman Problem was done and verifiedsuccessfully
25
Ex No: 10 Subset Sum Problem using Backtracking.
Date:
Aim: To write the C to solve the Subset Sum Problem using Backtracking.
Algorithm
• Input: A set of integers
• Target sum
• A temporary array, subset[], to store the current subset.
• Variables: to keep track of the size of the current subset, total to store the sum of the current
subset, and index to track the current position in the set.
• If total equals target, print the current subset and return.
• If total exceeds target or index is equal to the size of the set, return (backtrack).
• Include the current element (set[index]) in the subset and call the function recursively with
updated parameters (subsetSize + 1, total + set[index], index + 1).
• Exclude the current element from the subset and call the function recursively with updated
parameters (subsetSize, total, index + 1).
Program
#include <stdio.h>
#include <stdlib.h>
static int total_nodes;
void printValues(int A[], int size){
for (int i = 0; i < size; i++) {
printf("%*d", 5, A[i]);
}
printf("\n");
}
void subset_sum(int s[], int t[], int s_size, int t_size, int sum, int ite, int const target_sum){
total_nodes++;
if (target_sum == sum) {
printValues(t, t_size);
subset_sum(s, t, s_size, t_size - 1, sum - s[ite], ite + 1, target_sum);
return;
}
else {
for (int i = ite; i < s_size; i++) {
t[t_size] = s[i];
subset_sum(s, t, s_size, t_size + 1, sum + s[i], i + 1, target_sum);
}
}
}
void generateSubsets(int s[], int size, int target_sum){
int* tuplet_vector = (int*)malloc(size * sizeof(int));
subset_sum(s, tuplet_vector, size, 0, 0, 0, target_sum);
free(tuplet_vector);
26
}
int main(){
int set[] = { 5, 6, 12 , 54, 2 , 20 , 15 };
int size = sizeof(set) / sizeof(set[0]);
printf("The set is ");
printValues(set , size);
generateSubsets(set, size, 25);
printf("Total Nodes generated %d\n", total_nodes);
return 0;
}
Output:
The set is 5 6 12 54 2 20 15
5 6 12 2
5 20
Total Nodes generated 127
Result: Thus the implementation of Subset Sum Problem using Backtracking was done and verified
successfully
27