Lab Manual
Lab Manual
#include <stdio.h>
// Recursive function to find the smallest divisor
int findSmallestDivisor(int n, int divisor) {
// Base case: if divisor divides n, return the divisor
if (n % divisor == 0) {
return divisor;
}
// Recursive case: check the next divisor
return findSmallestDivisor(n, divisor + 1);
}
int main() {
int n;
// Input the integer
printf("Enter a positive integer: ");
scanf("%d", &n);
// Edge case: smallest divisor of 1 is 1
if (n == 1) {
printf("The smallest divisor of 1 is 1.\n");
} else {
// Call the recursive function starting with divisor 2
int smallestDivisor = findSmallestDivisor(n, 2);
printf("The smallest divisor of %d is %d.\n", n, smallestDivisor);
}
return 0;
}
2. For a given value of n, generate prime numbers <= n (more than one algorithms
are possible)
#include<stdio.h>
void main(){
int i, num, n, count;
printf("Enter the range: ");
scanf("%d", &n);
printf("The prime numbers in between the range 1 to %d:",n);
for(num = 1;num<=n;num++){
count = 0;
for(i=2;i<=num/2;i++){
if(num%i==0){
count++;
break;
}
}
if(count==0 && num!= 1)
printf("%d ",num);
}
}
#include <stdio.h>
#include <stdbool.h>
// Helper function to check if a number is prime (Recursive)
bool is_prime_recursive(int num, int divisor) {
if (num < 2) return false;
if (divisor * divisor > num) return true;
if (num % divisor == 0) return false;
return is_prime_recursive(num, divisor + 1);
}
// Function to print primes using recursion
void generate_primes_recursive(int n, int current) {
if (current > n) return;
if (is_prime_recursive(current, 2)) {
printf("%d ", current);
}
generate_primes_recursive(n, current + 1);
}
// Main function
int main() {
int n;
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Prime numbers <= %d (Recursive): ", n);
generate_primes_recursive(n, 2);
return 0;
}
3. Determine product of 2 integers (a * b) as repeated sums. Iterative and recursive algorithms are
possible.
#include <stdio.h>
int main() {
int a, b, result = 0;
// Input two integers
printf("Enter two integers:\n");
scanf("%d %d", &a, &b);
// Iterative approach: Calculate product using repeated sums
for (int i = 0; i < b; i++) {
result += a; // Add `a` repeatedly `b` times
}
printf("Product of %d and %d using iterative method is: %d\n", a, b, result);
return 0;
}
#include <stdio.h>
int main() {
int a, b;
// Input two integers
printf("Enter two integers:\n");
scanf("%d %d", &a, &b);
// Recursive function to calculate product
int product(int x, int y) {
// Base case
if (y == 0) {
return 0; // Product is 0 if any one number is 0
}
// Recursive case: add x and call recursively with (x, y - 1)
return x + product(x, y - 1);
}
// Calculate product using recursive function
int result = product(a, b);
printf("Product of %d and %d using recursive method is: %d\n", a, b, result);
return 0;
}
#include <stdio.h>
int main() {
int n;
// Input an integer
printf("Enter a positive integer: ");
scanf("%d", &n);
// Recursive function to calculate factorial
long factorial(int x) {
// Base case
if (x == 0 || x == 1) {
return 1; // Factorial of 0 or 1 is 1
}
// Recursive case: x * factorial of (x - 1)
return x * factorial(x - 1);
}
// Calculate factorial using recursive function
long result = factorial(n);
printf("Factorial of %d using recursive method is: %ld\n", n, result);
return 0;
}
5. Generate Fibonacci series up to n terms Iterative and recursive algorithms are possible.
#include <stdio.h>
int main() {
int n;
// Input number of terms
printf("Enter the number of terms for Fibonacci series: ");
scanf("%d", &n);
// Declare variables for Fibonacci
int a = 0, b = 1, next;
// Print Fibonacci series
printf("Fibonacci series up to %d terms: \n", n);
for (int i = 1; i <= n; i++) {
printf("%d ", a);
next = a + b; // Calculate next term
a = b; // Update a
b = next; // Update b
}
printf("\n");
return 0;
}
#include <stdio.h>
int main() {
int n;
// Input number of terms
printf("Enter the number of terms for Fibonacci series: ");
scanf("%d", &n);
// Recursive function to print Fibonacci series
void fibo(int x, int a, int b) {
// Base case
if (x == 0) {
return; // No more terms to print
}
// Print the current Fibonacci term
printf("%d ", a);
// Recursive call with updated values
fibo(x - 1, b, a + b);
}
// Print Fibonacci series using recursive function
printf("Fibonacci series up to %d terms: \n", n);
fibo(n, 0, 1); // Start with 0 and 1
printf("\n");
return 0;
}
6. Program for finding maximum and minimum number using Divide and conquer.
#include <stdio.h>
void findMinMax(int arr[], int low, int high, int *min, int *max) {
if (low == high) {
if (arr[low] > *max) *max = arr[low];
if (arr[low] < *min) *min = arr[low];
return;
}
if (high == low + 1) {
if (arr[low] > arr[high]) {
if (arr[low] > *max) *max = arr[low];
if (arr[high] < *min) *min = arr[high];
} else {
if (arr[high] > *max) *max = arr[high];
if (arr[low] < *min) *min = arr[low];
}
return;
}
int mid = (low + high) / 2;
findMinMax(arr, low, mid, min, max);
findMinMax(arr, mid + 1, high, min, max);
}
int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements:\n");
for(int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int min = arr[0];
int max = arr[0];
findMinMax(arr, 0, n - 1, &min, &max);
printf("Minimum element is %d\n", min);
printf("Maximum element is %d\n", max);
return 0;
}
#include <stdio.h>
// Function to find the minimum and maximum using divide and conquer
void findMinMax(int arr[], int low, int high, int *min, int *max) {
int mid;
int min1, max1; // Variables to store the results of the other half
// Base case: If there's only one element
if (low == high) {
*min = *max = arr[low];
return;
}
// If there are two elements, compare them directly
if (high == low + 1) {
if (arr[low] > arr[high]) {
*max = arr[low];
*min = arr[high];
} else {
*max = arr[high];
*min = arr[low];
}
return;
}
// Recursively divide the array into two halves
mid = (low + high) / 2;
findMinMax(arr, low, mid, min, max); // Find min, max for left half
findMinMax(arr, mid + 1, high, &min1, &max1); // Find min, max for right half
// Compare the results of both halves
if (*min > min1) *min = min1;
if (*max < max1) *max = max1;
}
int main() {
int arr[] = {12, 3, 5, 7, 19, 23, 8, 10};
int n = sizeof(arr) / sizeof(arr[0]);
int min, max;
// Call the recursive function
findMinMax(arr, 0, n - 1, &min, &max);
// Print the result
printf("Minimum element: %d\n", min);
printf("Maximum element: %d\n", max);
return 0;
}
int main() {
int n, data;
struct Node* root = nodes[0]; // Let's assume the first node as root
for (int i = 0; i < n; i++) {
int leftIndex = 2 * i + 1;
int rightIndex = 2 * i + 2;
if (leftIndex < n) {
nodes[i]->left = nodes[leftIndex];
}
if (rightIndex < n) {
nodes[i]->right = nodes[rightIndex];
}
}
printf("Level Order traversal of binary tree is: ");
printLevelOrder(root);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
// Structure for a node in the binary tree
struct Node {
int data;
struct Node *left, *right;
};
// Function to create a new node
struct Node* newNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}
// Function to find the height of the tree
int height(struct Node* root) {
if (root == NULL)
return 0;
else {
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return (leftHeight > rightHeight) ? (leftHeight + 1) : (rightHeight + 1);
}
}
// Function to print all nodes at a given level
void printCurrentLevel(struct Node* root, int level) {
if (root == NULL)
return;
if (level == 1)
printf("%d ", root->data);
else if (level > 1) {
printCurrentLevel(root->left, level - 1);
printCurrentLevel(root->right, level - 1);
}
}
int h = height(root);
for (int i = 1; i <= h; i++) {
printCurrentLevel(root, i);
}
}
// Function to insert nodes in a binary tree
struct Node* insertNode() {
int data;
printf("Enter data (-1 for no node): ");
scanf("%d", &data);
if (data == -1) {
return NULL; // No node to insert
}
struct Node* newNodePtr = newNode(data); // Create a new node
printf("Enter left child of %d:\n", data);
newNodePtr->left = insertNode(); // Recursively insert the left child
printf("Enter right child of %d:\n", data);
newNodePtr->right = insertNode(); // Recursively insert the right child
return newNodePtr;
}
int main() {
printf("Create the binary tree:\n");
struct Node* root = insertNode(); // Create binary tree from user input
printf("\nBreadth-First Search (Level Order Traversal) of binary tree is: \n");
BFS(root); // Perform BFS
return 0;
}
#include <stdio.h>
#include <stdlib.h>
// Structure for a node in the binary tree
struct Node {
int data;
struct Node *left, *right;
};
9. Binary Search of an ordered array. Iterative and Recursive algorithms are possible.
#include <stdio.h>
int main() {
int n, target;
printf("Enter number of elements:");
scanf("%d", &n);
int arr[n];
printf("Enter %d sorted elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf("Enter target element to search:");
scanf("%d", &target);
int low = 0;
int high = n - 1;
int foundIndex = -1; // Variable to store the result
// Perform binary search
while (low <= high) {
int mid = low + (high - low) / 2; // Prevent potential overflow
// Check if target is present at mid
if (arr[mid] == target) {
foundIndex = mid; // Target found
break; // Exit the loop as we found the target
}
// If target is greater, ignore the left half
else if (arr[mid] < target) {
low = mid + 1;
}
// If target is smaller, ignore the right half
else {
high = mid - 1;
}
}
// Output result
if (foundIndex != -1) {
printf("Element found at index: %d\n", foundIndex);
} else {
printf("Element not found\n");
}
return 0;
}
#include <stdio.h>
// Function to perform recursive binary search
int binarySearchRecursive(int arr[], int low, int high, int target) {
// Base case: If the search space is empty
if (low > high) {
return -1; // Target not found
}
int mid = low + (high - low) / 2; // Prevent potential overflow
// Check if target is present at mid
if (arr[mid] == target) {
return mid; // Target found
}
// If target is smaller than mid, search the left half
if (arr[mid] > target) {
return binarySearchRecursive(arr, low, mid - 1, target);
}
// If target is larger than mid, search the right half
else {
return binarySearchRecursive(arr, mid + 1, high, target);
}
}
int main() {
int n, target;
// Input number of elements
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
// Input elements (assuming array is sorted)
printf("Enter %d sorted elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Input target element to search
printf("Enter target element to search:");
scanf("%d", &target);
// Perform binary search
int result = binarySearchRecursive(arr, 0, n - 1, target);
if (result != -1) {
printf("Element found at index:%d\n", result);
} else {
printf("Element not found\n");
}
return 0;
}
int arr[n];
printf("Enter the elements:\n");
#include <stdio.h>
// Function to perform one pass of bubble sort
void bubbleSortRecursive(int arr[], int n) {
// Base case: If there is only one element, no need to sort
if (n == 1) {
return;
}
// Perform one pass of bubble sort
for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {
// Swap arr[i] and arr[i + 1] if they are in the wrong order
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
// Recursively call the function for the remaining unsorted part of the array
bubbleSortRecursive(arr, n - 1);
}
int main() {
int n;
// Input number of elements
int main() {
// Static array of numbers
int arr[] = {38, 27, 43, 3, 9, 82, 10};
int n = sizeof(arr)
// Merge function to merge two halves
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1; // Size of the left half
int n2 = right - mid; // Size of the right half
// Create temporary arrays
int L[n1], R[n2];
// Copy data to temporary arrays L[] and R[]
for (i = 0; i < n1; i++) {
L[i] = arr[left + i];
}
for (j = 0; j < n2; j++) {
R[j] = arr[mid + 1 + j];
}
// Merge the temporary arrays back into arr[left..right]
i = 0; // Initial index of the first sub-array
j = 0; // Initial index of the second sub-array
k = left; // Initial index of merged sub-array
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
// Copy the remaining elements of L[], if there are any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
#include <stdio.h>
int main() {
// Static array of numbers
int arr[] = {38, 27, 43, 3, 9, 82, 10};
int n = sizeof(arr) / sizeof(arr[0]);
return 0;
}
#include <stdio.h>
// Recursive function to find maximum revenue and print lengths
void rodCuttingRecursive(int prices[], int length, int *maxRevenue) {
// Base case: if length is 0, no revenue can be obtained
if (length <= 0) {
return;
}
int localMax = 0;
int bestCut = 0;
// Try cutting the rod at different lengths
for (int i = 1; i <= length; i++) {
if (i <= length) {
// Compare and update max revenue
int currentRevenue = prices[i] + *maxRevenue;
if (currentRevenue > localMax) {
localMax = currentRevenue;
bestCut = i;
}
}
}
*maxRevenue = localMax; // Update maximum revenue
// Print the best cut
if (bestCut > 0) {
printf("Cut: %d\n", bestCut);
rodCuttingRecursive(prices, length - bestCut, maxRevenue);
}
}
int main() {
int n;
// Input length of the rod
printf("Enter the length of the rod: ");
scanf("%d", &n);
// Input prices for each length
int prices[n + 1]; // prices[0] is unused
printf("Enter the prices for lengths 1 to %d:\n", n);
for (int i = 1; i <= n; i++) {
scanf("%d", &prices[i]);
}
int maxRevenue = 0;
rodCuttingRecursive(prices, n, &maxRevenue);
printf("Maximum revenue (recursive): %d\n", maxRevenue);
return 0;
}
13. Prim's algorithm to find minimum cost tree (shortest path in a tree).
#include <stdio.h>
#include <limits.h>
#define V 5 // Number of vertices in the graph
// Function to find the vertex with the minimum key value
int minKey(int key[], int mstSet[]) {
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++) {
if (mstSet[v] == 0 && key[v] < min) {
min = key[v];
min_index = v;
}
}
return min_index;
}
// Function to implement Prim's algorithm
void primMST(int graph[V][V]) {
int parent[V]; // Array to store the constructed MST
int key[V]; // Key values to pick minimum weight edge in cut
int mstSet[V]; // To represent the set of vertices included in MST
// Initialize all keys as INFINITE
for (int i = 0; i < V; i++) {
key[i] = INT_MAX;
mstSet[i] = 0; // Not included in MST yet
}
// Always include the first vertex in MST
key[0] = 0; // Make key 0 so that this vertex is picked as the first vertex
parent[0] = -1; // First node is always the root of the MST
// The MST will have V vertices
for (int count = 0; count < V - 1; count++) {
// Pick the minimum key vertex from the set of vertices not yet included in MST
int u = minKey(key, mstSet);
// Add the picked vertex to the MST Set
mstSet[u] = 1;
// Update the key value and parent index of the adjacent vertices
for (int v = 0; v < V; v++) {
// Update key only if graph[u][v] is smaller than key[v]
if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
}
// Print the constructed MST
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++) {
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}
}
int main() {
// Create the graph as an adjacency matrix
int graph[V][V] = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};
primMST(graph);
return 0;
}
#include <stdio.h>
#include <limits.h>
#define V 5 // Number of vertices in the graph
// Function to find the vertex with the minimum key value
int minKey(int key[], int mstSet[]) {
int min = INT_MAX, min_index = -1; // Initialize min_index to -1
for (int v = 0; v < V; v++) {
if (mstSet[v] == 0 && key[v] < min) {
min = key[v];
min_index = v;
}
}
return min_index;
}
// Recursive function to add edges to the MST
void addEdgeToMST(int graph[V][V], int key[], int mstSet[], int parent[], int count) {
// Base case: when we have V-1 edges
if (count == V - 1) {
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++) {
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}
return;
}
// Pick the minimum key vertex from the set of vertices not yet included in MST
int u = minKey(key, mstSet);
mstSet[u] = 1; // Add the picked vertex to the MST set
// Update the key value and parent index of the adjacent vertices
for (int v = 0; v < V; v++) {
if (graph[u][v] && mstSet[v] == 0 && graph[u][v] < key[v]) {
parent[v] = u;
key[v] = graph[u][v];
}
}
// Recursive call for the next edge
addEdgeToMST(graph, key, mstSet, parent, count + 1);
}
// Function to implement Prim's algorithm
void primMST(int graph[V][V]) {
int parent[V]; // Array to store the constructed MST
int key[V]; // Key values to pick minimum weight edge in cut
int mstSet[V]; // To represent the set of vertices included in MST
// Initialize all keys as INFINITE
for (int i = 0; i < V; i++) {
key[i] = INT_MAX;
mstSet[i] = 0; // Not included in MST yet
}
// Always include the first vertex in MST
key[0] = 0; // Make key 0 so that this vertex is picked as the first vertex
parent[0] = -1; // First node is always the root of the MST
// Start the recursive edge addition
addEdgeToMST(graph, key, mstSet, parent, 0);
}
int main() {
// Create the graph as an adjacency matrix
int graph[V][V] = {
{0, 2, 0, 6, 0},
{2, 0, 3, 8, 5},
{0, 3, 0, 0, 7},
{6, 8, 0, 0, 9},
{0, 5, 7, 9, 0}
};
primMST(graph);
return 0;
}
14. Kruskal's algorithm to find minimum cost tree (shortest path in a tree).
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
// Structure to represent an edge
typedef struct {
int u, v, weight;
} Edge;
// Function to compare edges based on weight
int compare(const void *a, const void *b) {
return ((Edge *)a)->weight - ((Edge *)b)->weight;
}
// Find function using path compression
int find(int parent[], int i) {
if (parent[i] != i)
parent[i] = find(parent, parent[i]);
return parent[i];
}
// Union function
void unionSets(int parent[], int rank[], int x, int y) {
if (rank[x] > rank[y]) {
parent[y] = x;
} else if (rank[x] < rank[y]) {
parent[x] = y;
} else {
parent[y] = x;
rank[x]++;
}
}
// Kruskal's algorithm to find the MST (Iterative)
void kruskalIterative(Edge edges[], int numEdges, int numVertices) {
qsort(edges, numEdges, sizeof(edges[0]), compare);
int parent[MAX], rank[MAX];
for (int i = 0; i < numVertices; i++) {
parent[i] = i;
rank[i] = 0;
}
printf("Edges in the Minimum Spanning Tree:\n");
for (int i = 0; i < numEdges; i++) {
int x = find(parent, edges[i].u);
int y = find(parent, edges[i].v);
if (x != y) {
printf("%d - %d: %d\n", edges[i].u, edges[i].v, edges[i].weight);
unionSets(parent, rank, x, y);
}
}
}
int main() {
Edge edges[] = {
{0, 1, 10},
{0, 2, 6},
{0, 3, 5},
{1, 3, 15},
{2, 3, 4}
};
int numEdges = sizeof(edges) / sizeof(edges[0]);
int numVertices = 4;
kruskalIterative(edges, numEdges, numVertices);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
// Structure to represent an edge
typedef struct {
int u, v, weight;
} Edge;
#include <stdio.h>
#include <limits.h>
#define V 5 // Number of vertices
#define E 8 // Number of edges
// Structure to represent an edge
typedef struct {
int u, v, weight;
} Edge;
// Recursive function to relax edges
void relaxEdges(Edge edges[], int distance[], int edgesCount, int iterations) {
if (iterations <= 0) return; // Base case
for (int j = 0; j < edgesCount; j++) {
if (distance[edges[j].u] != INT_MAX &&
distance[edges[j].u] + edges[j].weight < distance[edges[j].v]) {
distance[edges[j].v] = distance[edges[j].u] + edges[j].weight;
}
}
// Recursive call for the next iteration
relaxEdges(edges, distance, edgesCount, iterations - 1);
}
// Function to implement Bellman-Ford algorithm (Recursive)
void bellmanFordRecursive(Edge edges[], int source) {
int distance[V];
// Step 1: Initialize distances
for (int i = 0; i < V; i++) {
distance[i] = INT_MAX;
}
distance[source] = 0;
// Step 2: Relax edges V - 1 times
relaxEdges(edges, distance, E, V - 1);
// Step 3: Print the shortest distances
printf("Vertex Distance from Source:\n");
for (int i = 0; i < V; i++) {
printf("%d \t\t %d\n", i, distance[i]);
}
}
int main() {
// Define edges of the graph
Edge edges[E] = {
{0, 1, -1},
{0, 2, 4},
{1, 2, 3},
{1, 3, 2},
{1, 4, 2},
{3, 2, 5},
{3, 1, 1},
{4, 3, -3}
};
int source = 0; // Starting vertex
bellmanFordRecursive(edges, source);
return 0;
}