0% found this document useful (0 votes)
9 views11 pages

Discrete Math Practical Student - 05!04!2021

The document contains multiple C programs demonstrating various algorithms and data structures, including Tower of Hanoi, graph representation using adjacency list and matrix, string matching with finite state machines, power set generation, GCD calculation, binomial coefficients, permutations and combinations, and prime number checking. Each program is accompanied by its output for clarity. The document serves as a comprehensive guide for implementing fundamental algorithms in C.

Uploaded by

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

Discrete Math Practical Student - 05!04!2021

The document contains multiple C programs demonstrating various algorithms and data structures, including Tower of Hanoi, graph representation using adjacency list and matrix, string matching with finite state machines, power set generation, GCD calculation, binomial coefficients, permutations and combinations, and prime number checking. Each program is accompanied by its output for clarity. The document serves as a comprehensive guide for implementing fundamental algorithms in C.

Uploaded by

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

1. Write the programs using “C” for Tower of Hanoi.

C Program:
#include <stdio.h>

// C recursive function to solve tower of hanoi puzzle


void ToH(int n, char from_rod, char to_rod, char aux_rod)
{
if (n = = 1)
{
printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod);
return;
}
ToH(n-1, from_rod, aux_rod, to_rod);
printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);
ToH(n-1, aux_rod, to_rod, from_rod);
}

int main()
{
int n = 3; // Number of disks
ToH(n, 'A', 'C', 'B'); // A, B and C are names of rods
return 0;
}

Output:
Move disk 1 from rod A to rod B
Move disk 1 from rod A to rod C
Move disk 2 from rod A to rod B
Move disk 1 from rod C to rod B
Move disk 3 from rod A to rod C
Move disk 1 from rod B to rod A
Move disk 2 from rod B to rod C
Move disk 1 from rod A to rod C

Important Note: For “n” disks, total 2n – 1 moves are required.

2. Write the programs using “C” for Graph representation using Adjacency List.
C Program:
// A C Program to demonstrate adjacency list representation of graphs
#include <stdio.h>
#include <stdlib.h>

// A structure to represent an adjacency list node


struct AdjListNode
{
int dest;
struct AdjListNode* next;
};

// A structure to represent an adjacency list


struct AdjList
{
struct AdjListNode *head;
};

// A structure to represent a graph. A graph is an array of adjacency lists.


// Size of array will be V (number of vertices in graph)
struct Graph
{
int V;
struct AdjList* array;
};

// A utility function to create a new adjacency list node


struct AdjListNode* newAdjListNode(int dest)
{
struct AdjListNode* newNode = (struct AdjListNode*) malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}

// A utility function that creates a graph of V vertices


struct Graph* createGraph(int V)
{
struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
graph->V = V;

// Create an array of adjacency lists. Size of array will be V


graph->array = (struct AdjList*) malloc(V * sizeof(struct AdjList));

// Initialize each adjacency list as empty by making head as NULL


int i;
for (i = 0; i < V; ++i)
graph->array[i].head = NULL;
return graph;
}

// Adds an edge to an undirected graph


void addEdge(struct Graph* graph, int src, int dest)
{
// Add an edge from src to dest. A new node is added to the adjacency list of src.
// The node is added at the begining
struct AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;

// Since graph is undirected, add an edge from dest to src also


newNode = newAdjListNode(src);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
}

// A utility function to print the adjacency list representation of graph


void printGraph(struct Graph* graph)
{
int v;
for (v = 0; v < graph->V; ++v)
{
struct AdjListNode* pCrawl = graph->array[v].head;
printf("\n Adjacency list of vertex %d\n head ", v);
while (pCrawl)
{
printf("-> %d", pCrawl->dest);
pCrawl = pCrawl->next;
}
printf("\n");
}
}

// Driver program to test above functions


int main()
{
// create the graph given in above fugure
int V = 5;
struct Graph* graph = createGraph(V);
addEdge(graph, 0, 1);
addEdge(graph, 0, 4);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 3);
addEdge(graph, 3, 4);

// print the adjacency list representation of the above graph


printGraph(graph);

return 0;
}

Output:
Adjacency list of vertex 0
head -> 1-> 4
Adjacency list of vertex 1
head -> 0-> 2-> 3-> 4
Adjacency list of vertex 2
head -> 1-> 3
Adjacency list of vertex 3
head -> 1-> 2-> 4
Adjacency list of vertex 4
head -> 0-> 1-> 3

3. Write the programs using “C” for Graph representation using Adjacency Matrix.
C Program:
#include <stdio.h>

// N vertices and M Edges


int N, M;

// Function to create Adjacency Matrix


void createAdjMatrix(int Adj[][N + 1],
int arr[][2])
{

// Initialise all value to this


// Adjacency list to zero
for (int i = 0; i < N + 1; i++) {

for (int j = 0; j < N + 1; j++) {


Adj[i][j] = 0;
}
}
// Traverse the array of Edges
for (int i = 0; i < M; i++) {

// Find X and Y of Edges


int x = arr[i][0];
int y = arr[i][1];

// Update value to 1
Adj[x][y] = 1;
Adj[y][x] = 1;
}
}

// Function to print the created


// Adjacency Matrix
void printAdjMatrix(int Adj[][N + 1])
{

// Traverse the Adj[][]


for (int i = 1; i < N + 1; i++) {
for (int j = 1; j < N + 1; j++) {

// Print the value at Adj[i][j]


printf("%d ", Adj[i][j]);
}
printf("\n");
}
}

// Driver Code
int main()
{

// Number of vertices
N = 5;

// Given Edges
int arr[][2]
= { { 1, 2 }, { 2, 3 },
{ 4, 5 }, { 1, 5 } };

// Number of Edges
M = sizeof(arr) / sizeof(arr[0]);

// For Adjacency Matrix


int Adj[N + 1][N + 1];
// Function call to create
// Adjacency Matrix
createAdjMatrix(Adj, arr);

// Print Adjacency Matrix


printAdjMatrix(Adj);

return 0;
}

Output:
01001
10100
01000
00001
10010

4. Write the programs using “C” for String Matching using finite state machine.
C Program:
// C program for Finite Automata Pattern searching Algorithm
#include<stdio.h>
#include<string.h>
#define NO_OF_CHARS 256

int getNextState(char *pat, int M, int state, int x)


{
// If the character c is same as next character
// in pattern,then simply increment state
if (state < M && x == pat[state])
return state+1;

// ns stores the result which is next state


int ns, i;

// ns finally contains the longest prefix


// which is also suffix in "pat[0..state-1]c"

// Start from the largest possible value


// and stop when you find a prefix which
// is also suffix
for (ns = state; ns > 0; ns--)
{
if (pat[ns-1] == x)
{
for (i = 0; i < ns-1; i++)
if (pat[i] != pat[state-ns+1+i])
break;
if (i == ns-1)
return ns;
}
}

return 0;
}

/* This function builds the TF table which represents4


Finite Automata for a given pattern */
void computeTF(char *pat, int M, int TF[][NO_OF_CHARS])
{
int state, x;
for (state = 0; state <= M; ++state)
for (x = 0; x < NO_OF_CHARS; ++x)
TF[state][x] = getNextState(pat, M, state, x);
}

/* Prints all occurrences of pat in txt */


void search(char *pat, char *txt)
{
int M = strlen(pat);
int N = strlen(txt);

int TF[M+1][NO_OF_CHARS];

computeTF(pat, M, TF);

// Process txt over FA.


int i, state=0;
for (i = 0; i < N; i++)
{
state = TF[state][txt[i]];
if (state == M)
printf ("\n Pattern found at index %d",
i-M+1);
}
}
// Driver program to test above function
int main()
{
char *txt = "AABAACAADAABAAABAA";
char *pat = "AABA";
search(pat, txt);
return 0;
}

Output:
Pattern found at index 0
Pattern found at index 9
Pattern found at index 13

7. Write the programs using “C” to find the power set for a given set.
#include <stdio.h>
#include <math.h>

void printPowerSet(char *set, int set_size)


{
/*set_size of power set of a set with set_size
n is (2**n -1)*/
unsigned int pow_set_size = pow(2, set_size);
int counter, j;

/*Run from counter 000..0 to 111..1*/


for(counter = 0; counter < pow_set_size; counter++)
{
for(j = 0; j < set_size; j++)
{
/* Check if jth bit in the counter is set
If set then print jth element from set */
if(counter & (1<<j))
printf("%c", set[j]);
}
printf("\n");
}
}

/*Driver program to test printPowerSet*/


int main()
{
char set[] = {'a','b','c'};
printPowerSet(set, 3);
return 0;
}

8. Write the programs using “C” to find GCD of two numbers using recursion.
// C program to find GCD of two numbers
#include <stdio.h>

// Recursive function to return gcd of a and b


int gcd(int a, int b)
{
// Everything divides 0
if (a = = 0)
return b;
if (b = = 0)
return a;

// base case
if (a = = b)
return a;

// a is greater
if (a > b)
return gcd(a-b, b);
return gcd(a, b-a);
}

// Driver program to test above function


int main()
{
int a = 98, b = 56;
printf("GCD of %d and %d is %d ", a, b, gcd(a, b));
return 0;
}

9. Write the programs using “C” to find Binomial coefficients.


#include <stdio.h>

// Returns value of Binomial Coefficient C(n, k)


int binomialCoeff(int n, int k)
{
// Base Cases
if (k > n)
return 0;
if (k == 0 || k == n)
return 1;

// Recur
return binomialCoeff(n - 1, k - 1)
+ binomialCoeff(n - 1, k);
}

/* Driver program to test above function*/


int main()
{
int n = 5, k = 2;
printf("Value of C(%d, %d) is %d ", n, k,
binomialCoeff(n, k));
return 0;
}

Output:

Value of C(5, 2) is 10

10. Write the programs using “C” to find Permutation and Combination result for a given
pair of values n and r.
// CPP program To calculate The Value Of nCr
#include <bits/stdc++.h>
using namespace std;

int fact(int n);


int nCr(int n, int r)
{
return fact(n) / (fact(r) * fact(n - r));
}

// Returns factorial of n
int fact(int n)
{
int res = 1;
for (int i = 2; i <= n; i++)
res = res * i;
return res;
}

// Driver code
int main()
{
int n = 5, r = 3;
cout << nCr(n, r);
return 0;
}

11. Write the programs using “C” to check a number is prime or not.

#include <stdio.h>
int main() {
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);

for (i = 2; i <= n / 2; ++i) {


// condition for non-prime
if (n % i == 0) {
flag = 1;
break;
}
}

if (n == 1) {
printf("1 is neither prime nor composite.");
}
else {
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
}

return 0;
}

Output

Enter a positive integer: 29


29 is a prime number.

You might also like