Question Bank › Technical › Data Structures › Coding Questions
Write a C program to implement binary search on a sorted array. The array should be initialized with the values: 5, 12, 18, 25, 33, 47, 56, 68, 79. The program should search for the value 33 and print its position (1-based index) if found, or a message if not found. Also, print the array elements before searching.
#include <stdio.h>
int binarySearch(int arr[], int left, int right, int key) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key)
return mid + 1; // 1-based index
else if (arr[mid] < key)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
int main() {
int arr[] = {5, 12, 18, 25, 33, 47, 56, 68, 79};
int n = sizeof(arr) / sizeof(arr[0]);
int key = 33;
printf("Array elements: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\nSearching for %d\n", key);
int pos = binarySearch(arr, 0, n - 1, key);
if (pos == -1)
printf("Element not found\n");
else
printf("Element found at position %d\n", pos);
return 0;
}Write a C program that implements an optimized bubble sort to sort an array of integers in ascending order. The optimization should stop the passes early if no swaps occur in a pass. Print the sorted array.
#include <stdio.h>
void bubbleSort(int a[], int n) {
for (int pass = 0; pass < n - 1; pass++) {
int swapped = 0;
for (int i = 0; i < n - 1 - pass; i++) {
if (a[i] > a[i + 1]) {
int t = a[i];
a[i] = a[i + 1];
a[i + 1] = t;
swapped = 1;
}
}
if (!swapped) break; /* array already sorted */
}
}
int main() {
int a[] = {42, 17, 8, 33, 25, 4, 19};
int n = sizeof(a) / sizeof(a[0]);
bubbleSort(a, n);
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}Write a C program to implement an adjacency matrix representation of an undirected graph. The program should allow the user to input the number of vertices and edges, then input each edge as a pair of vertices. It should build the adjacency matrix and finally display the matrix. Use a 2D array for the matrix and ensure it is initialized to zero.
#include <stdio.h>
#define MAX_V 100
void initMatrix(int matrix[][MAX_V], int V) {
for (int i = 0; i < V; i++)
for (int j = 0; j < V; j++)
matrix[i][j] = 0;
}
void addEdge(int matrix[][MAX_V], int src, int dest) {
matrix[src][dest] = 1;
matrix[dest][src] = 1;
}
void printMatrix(int matrix[][MAX_V], int V) {
printf("Adjacency Matrix:\n");
for (int i = 0; i < V; i++) {
for (int j = 0; j < V; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
int main() {
int V, E;
printf("Enter number of vertices: ");
scanf("%d", &V);
printf("Enter number of edges: ");
scanf("%d", &E);
int matrix[MAX_V][MAX_V];
initMatrix(matrix, V);
printf("Enter edges (src dest):\n");
for (int i = 0; i < E; i++) {
int src, dest;
scanf("%d %d", &src, &dest);
addEdge(matrix, src, dest);
}
printMatrix(matrix, V);
return 0;
}Write a C program that demonstrates a simple hash table using the division method. Read the number of elements n and n integer keys from the user. For each key, compute its hash location as key % 10, store it in a hash array at that index, and print the location and the stored value in the format: location = arry1[<index>], value = <key>.
#include <stdio.h>
int main()
{
int arry[100], arry1[100], n, result = 0, i;
printf("Enter the size of an array : ");
scanf("%d", &n);
printf("\nEnter %d elements : \n", n);
for (i = 0; i < n; i++)
scanf("%d", &arry[i]);
for (i = 0; i < n; i++) {
result = arry[i] % 10;
arry1[result] = arry[i];
printf("\nlocation = arry1[%d], value = %d ", result, arry1[result]);
result = 0;
}
return 0;
}Write a C++ program that asks the user to enter their name and then prints the greeting "Namaste, [name]!" where [name] is the entered name.
#include <iostream>
#include <string>
using namespace std;
int main() {
string name;
cout << "Enter your name: ";
cin >> name;
cout << "Namaste, " << name << "!" << endl;
return 0;
}Write a C++ program that asks the user to enter two integers and then prints their sum.
#include <iostream>
using namespace std;
int main() {
int a, b;
cout << "Enter two integers: ";
cin >> a >> b;
cout << "Sum = " << a + b << endl;
return 0;
}Write a C++ program that asks the user to input an integer and then prints whether the number is even or odd.
#include <iostream>
using namespace std;
int main() {
int num;
cout << "Enter an integer: ";
cin >> num;
if (num % 2 == 0) {
cout << num << " is even." << endl;
} else {
cout << num << " is odd." << endl;
}
return 0;
}Write a C++ program that repeatedly asks the user to enter integers until the user enters 0. After 0 is entered, the program should print how many positive numbers and how many negative numbers were entered (do not count the 0).
#include <iostream>
using namespace std;
int main() {
int num, positiveCount = 0, negativeCount = 0;
cout << "Enter numbers (0 to stop): ";
while (cin >> num && num != 0) {
if (num > 0) {
positiveCount++;
} else {
negativeCount++;
}
}
cout << "Positive numbers: " << positiveCount << endl;
cout << "Negative numbers: " << negativeCount << endl;
return 0;
}Write a C++ program that asks the user to enter a word and then prints the reverse of that word.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string word;
cout << "Enter a word: ";
getline(cin, word);
reverse(word.begin(), word.end());
cout << "Reversed word: " << word << endl;
return 0;
}Write a C++ program that defines a class named `Mobile` with private member variables `brand` (string), `model` (string) and `price` (integer). Provide public member functions to set and get each of these variables. In `main`, create a `Mobile` object, set its brand to "Samsung", model to "Galaxy M14" and price to 15000, then print all three values in the format: Mobile Details: Samsung Galaxy M14 15000
#include <iostream>
#include <string>
using namespace std;
class Mobile {
private:
string brand;
string model;
int price;
public:
void setBrand(const string &b) { brand = b; }
void setModel(const string &m) { model = m; }
void setPrice(int p) { price = p; }
string getBrand() const { return brand; }
string getModel() const { return model; }
int getPrice() const { return price; }
};
int main() {
Mobile myMobile;
myMobile.setBrand("Samsung");
myMobile.setModel("Galaxy M14");
myMobile.setPrice(15000);
cout << "Mobile Details: " << myMobile.getBrand() << " " << myMobile.getModel() << " " << myMobile.getPrice() << endl;
return 0;
}Write a C program that shows how stack memory is used for function calls. Define a function square(int s) that returns s*s. Define a function sum(int x, int y) that computes z = x + y, then calls square(z) and returns the result. In main, set a = 7 and b = 5, call sum(a, b), and print the result in the format: Output is : <value>
#include <stdio.h>
int square(int s)
{
return s*s;
}
int sum(int x, int y)
{
int z = x + y;
int result = square(z);
return result;
}
int main()
{
int a = 7;
int b = 5;
int x = sum(a, b);
printf("Output is : %d", x);
return 0;
}Write a Java program that implements insertion of a word into a Trie. Each character of the word becomes a node on the path from the root; if a child node for the current character already exists, reuse it, otherwise create a new node and attach it. After processing all characters, mark the last node as the end of a word. Also demonstrate inserting a few Indian city names and print whether each was inserted successfully.
import java.util.HashMap;
import java.util.Map;
class TrieNode {
Map<Character, TrieNode> children = new HashMap<>();
boolean endOfWord = false;
}
public class TrieInsert {
private TrieNode root;
public TrieInsert() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = current.children.get(ch);
if (node == null) {
node = new TrieNode();
current.children.put(ch, node);
}
current = node;
}
current.endOfWord = true;
}
public static void main(String[] args) {
TrieInsert trie = new TrieInsert();
String[] cities = {"pune", "patna", "mumbai"};
for (String city : cities) {
trie.insert(city);
System.out.println(city + " inserted");
}
}
}Write a C++ program to implement a Binary Search Tree (BST) with insertion, deletion, and inorder traversal. The program should allow the user to insert nodes, delete a node, and display the inorder traversal. Use the following sequence of operations: insert 50, insert 30, insert 70, insert 20, insert 40, insert 60, insert 80, delete 20, and then perform inorder traversal. The inorder traversal should print the nodes in ascending order.
#include <iostream>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int val) : data(val), left(nullptr), right(nullptr) {}
};
Node* insert(Node* root, int val) {
if (root == nullptr) return new Node(val);
if (val < root->data)
root->left = insert(root->left, val);
else if (val > root->data)
root->right = insert(root->right, val);
return root;
}
Node* minValueNode(Node* node) {
Node* current = node;
while (current && current->left != nullptr)
current = current->left;
return current;
}
Node* deleteNode(Node* root, int key) {
if (root == nullptr) return root;
if (key < root->data)
root->left = deleteNode(root->left, key);
else if (key > root->data)
root->right = deleteNode(root->right, key);
else {
if (root->left == nullptr) {
Node* temp = root->right;
delete root;
return temp;
} else if (root->right == nullptr) {
Node* temp = root->left;
delete root;
return temp;
}
Node* temp = minValueNode(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}
void inorder(Node* root) {
if (root != nullptr) {
inorder(root->left);
cout << root->data << " ";
inorder(root->right);
}
}
int main() {
Node* root = nullptr;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 70);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 60);
root = insert(root, 80);
cout << "Inorder traversal before deletion: ";
inorder(root);
cout << endl;
root = deleteNode(root, 20);
cout << "Inorder traversal after deletion of 20: ";
inorder(root);
cout << endl;
return 0;
}Write a C program to implement a binary tree. The program should create nodes using a structure with data, left pointer, and right pointer. It should allow the user to input data for each node and recursively build the tree. The program should prompt the user to enter 0 to stop creating a node or 1 to create a new node, and then input the data for that node. After creating the tree, the program should display the tree using inorder traversal.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left, *right;
};
struct node* create() {
struct node *temp;
int data, choice;
printf("Press 0 to exit, 1 for new node: ");
scanf("%d", &choice);
if (choice == 0) {
return NULL;
} else {
temp = (struct node*)malloc(sizeof(struct node));
printf("Enter the data: ");
scanf("%d", &data);
temp->data = data;
printf("Enter left child of %d\n", data);
temp->left = create();
printf("Enter right child of %d\n", data);
temp->right = create();
return temp;
}
}
void inorder(struct node *root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
int main() {
struct node *root = NULL;
root = create();
printf("Inorder traversal: ");
inorder(root);
printf("\n");
return 0;
}Write a C program that implements bucket sort to sort an array of n non-negative integers. The program should first find the maximum element, create buckets accordingly, distribute the elements into buckets, sort each bucket (using insertion sort), and then concatenate the buckets to produce the sorted array. Print the sorted array.
#include <stdio.h>
#include <stdlib.h>
void insertionSort(int b[], int m) {
for (int i = 1; i < m; i++) {
int key = b[i];
int j = i - 1;
while (j >= 0 && b[j] > key) {
b[j + 1] = b[j];
j--;
}
b[j + 1] = key;
}
}
void bucketSort(int a[], int n) {
int max = a[0];
for (int i = 1; i < n; i++)
if (a[i] > max) max = a[i];
int nb = max / 10 + 1; /* number of buckets */
int **buckets = (int **)malloc(nb * sizeof(int *));
int *sizes = (int *)calloc(nb, sizeof(int));
for (int i = 0; i < nb; i++)
buckets[i] = (int *)malloc(n * sizeof(int));
for (int i = 0; i < n; i++) {
int idx = a[i] / 10;
buckets[idx][sizes[idx]++] = a[i];
}
int k = 0;
for (int i = 0; i < nb; i++) {
insertionSort(buckets[i], sizes[i]);
for (int j = 0; j < sizes[i]; j++)
a[k++] = buckets[i][j];
}
for (int i = 0; i < nb; i++) free(buckets[i]);
free(buckets);
free(sizes);
}
int main() {
int a[] = {29, 5, 12, 34, 8, 21, 17, 3};
int n = sizeof(a) / sizeof(a[0]);
bucketSort(a, n);
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}Write a C program to find the length of the longest substring of a given string that does not contain any repeating characters. The given string is "abacbdb". It may contain English letters, digits, symbols and spaces.
#include <stdio.h>
#include <string.h>
static int longestUniqueSubstring(char *s) {
int lastPos[128];
int i;
for (i = 0; i < 128; i++)
lastPos[i] = -1;
int maxLen = 0;
int start = 0;
int idx;
for (idx = 0; s[idx] != '\0'; idx++) {
char c = s[idx];
if (lastPos[(int)c] >= start)
start = lastPos[(int)c] + 1;
lastPos[(int)c] = idx;
int curLen = idx - start + 1;
if (curLen > maxLen)
maxLen = curLen;
}
return maxLen;
}
int main(void) {
char str1[] = "abacbdb";
printf("Original String: %s\n", str1);
printf("Length of the longest substring without repeating characters: %d\n", longestUniqueSubstring(str1));
return 0;
}Write a C program that implements cocktail sort (bidirectional bubble sort) to sort an array of integers in ascending order. The program should sort the array {5, 1, 4, 2, 8, 0, 9} and print the sorted array.#include <stdio.h>
void cocktailSort(int arr[], int n) {
int swapped = 1;
int start = 0;
int end = n - 1;
int i, temp;
while (swapped) {
swapped = 0;
for (i = start; i < end; ++i) {
if (arr[i] > arr[i + 1]) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = 1;
}
}
if (!swapped)
break;
swapped = 0;
--end;
for (i = end - 1; i >= start; --i) {
if (arr[i] > arr[i + 1]) {
temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = 1;
}
}
++start;
}
}
int main(void) {
int arr[] = {5, 1, 4, 2, 8, 0, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int i;
cocktailSort(arr, n);
printf("Sorted array: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}Write a C program that implements Heapsort to sort an array of integers in ascending order. Your program should read the size n and n integers from the user, build a max-heap, perform heap sort, and print the sorted array.
#include <stdio.h>
void heapify(int a[], int n, int i)
{
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && a[left] > a[largest])
largest = left;
if (right < n && a[right] > a[largest])
largest = right;
if (largest != i) {
int temp = a[i];
a[i] = a[largest];
a[largest] = temp;
heapify(a, n, largest);
}
}
void heapSort(int a[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(a, n, i);
for (int i = n - 1; i > 0; i--) {
int temp = a[0];
a[0] = a[i];
a[i] = temp;
heapify(a, i, 0);
}
}
void printArr(int arr[], int n)
{
for (int i = 0; i < n; ++i)
printf("%d ", arr[i]);
printf("\n");
}
int main()
{
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
int a[n];
printf("Enter %d elements: ", n);
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
printf("Before sorting: ");
printArr(a, n);
heapSort(a, n);
printf("After sorting: ");
printArr(a, n);
return 0;
}Write a C program to demonstrate collision resolution using linear probing. The program should: - Read an integer n (number of elements) and then n integers. - Use a hash table of size 10, initially all -1. - For each element, compute its hash index as element % 10. - If the slot is empty (-1), insert the element there and print: "location = arry1[<index>], value = <element>" (note: use 'arry1' as the array name). - If the slot is occupied, probe linearly (index+1, wrapping around to 0 after 9) until an empty slot is found, insert there, and print the same format with the new index. - Assume the hash table will not become full (n <= 10). Example: Input: 5 101 103 104 105 201 Output: location = arry1[1], value = 101 location = arry1[3], value = 103 location = arry1[4], value = 104 location = arry1[5], value = 105 location = arry1[2], value = 201
#include <stdio.h>
int main() {
int arry[100], arry1[10];
int n, i, j, result;
printf("Enter the size of an array : ");
scanf("%d", &n);
printf("\nEnter %d elements : \n", n);
for (i = 0; i < n; i++) {
scanf("%d", &arry[i]);
}
for (i = 0; i < 10; i++) {
arry1[i] = -1;
}
for (i = 0; i < n; i++) {
result = arry[i] % 10;
if (arry1[result] == -1) {
arry1[result] = arry[i];
printf("\nlocation = arry1[%d], value = %d ", result, arry1[result]);
} else {
j = result + 1;
while (1) {
if (j > 9) j = 0;
if (arry1[j] == -1) {
arry1[j] = arry[i];
printf("\nlocation = arry1[%d], value = %d ", j, arry1[j]);
break;
}
j++;
}
}
}
return 0;
}Write a C++ program to convert a postfix expression to a prefix expression. The expression will contain single-letter operands (A-Z or a-z) and operators +, -, *, /. Read the postfix expression as a string and output the equivalent prefix expression.
#include <iostream>
#include <stack>
#include <string>
using namespace std;
bool isOperand(char c) {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
string postfixToPrefix(string postfix) {
stack<string> st;
for (char c : postfix) {
if (isOperand(c)) {
st.push(string(1, c));
} else {
string op2 = st.top(); st.pop();
string op1 = st.top(); st.pop();
string expr = c + op1 + op2;
st.push(expr);
}
}
return st.top();
}
int main() {
string postfix;
cout << "Enter postfix expression: ";
cin >> postfix;
cout << "Prefix expression: " << postfixToPrefix(postfix) << endl;
return 0;
}Write a C program to sort an array using the Quick Sort algorithm. The program should choose the first element as pivot, partition the array so that elements smaller than pivot come before it and larger elements come after it, then recursively sort the subarrays. Use the array: arr[] = {35, 10, 55, 20, 30, 45}.#include <stdio.h>
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
int partition(int arr[], int low, int high) {
int pivot = arr[low];
int i = low, j = high;
while (i < j) {
while (i < high && arr[i] <= pivot)
i++;
while (arr[j] > pivot)
j--;
if (i < j)
swap(&arr[i], &arr[j]);
}
swap(&arr[low], &arr[j]);
return j;
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main() {
int arr[] = {35, 10, 55, 20, 30, 45};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}Write a C program to sort an array using the Merge Sort algorithm. The program should divide the array into halves recursively until each subarray has one element, then merge them back in sorted order. Use the array: arr[] = {45, 25, 80, 60, 15, 90, 10, 55, 5}.#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int left, int mid, int right) {
int i, j, k;
int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[left + i];
for (j = 0; j < n2; j++)
R[j] = arr[mid + 1 + j];
i = 0; j = 0; k = left;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++; k++;
}
while (j < n2) {
arr[k] = R[j];
j++; k++;
}
}
void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;
mergeSort(arr, left, mid);
mergeSort(arr, mid + 1, right);
merge(arr, left, mid, right);
}
}
int main() {
int arr[] = {45, 25, 80, 60, 15, 90, 10, 55, 5};
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, n - 1);
printf("Sorted array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}Write a C program to implement merge sort. The program should sort an array of integers using the merge sort algorithm. Include functions for merging two sorted subarrays and for recursively dividing the array. The program should read the number of elements and the elements from the user, sort them, and then display the sorted array.
#include <stdio.h>
void merge(int a[], int beg, int mid, int end) {
int i, j, k;
int n1 = mid - beg + 1;
int n2 = end - mid;
int LeftArray[n1], RightArray[n2];
for (i = 0; i < n1; i++)
LeftArray[i] = a[beg + i];
for (j = 0; j < n2; j++)
RightArray[j] = a[mid + 1 + j];
i = 0;
j = 0;
k = beg;
while (i < n1 && j < n2) {
if (LeftArray[i] <= RightArray[j]) {
a[k] = LeftArray[i];
i++;
} else {
a[k] = RightArray[j];
j++;
}
k++;
}
while (i < n1) {
a[k] = LeftArray[i];
i++;
k++;
}
while (j < n2) {
a[k] = RightArray[j];
j++;
k++;
}
}
void mergeSort(int a[], int beg, int end) {
if (beg < end) {
int mid = (beg + end) / 2;
mergeSort(a, beg, mid);
mergeSort(a, mid + 1, end);
merge(a, beg, mid, end);
}
}
int main() {
int n, i;
printf("Enter the number of elements: ");
scanf("%d", &n);
int a[n];
printf("Enter the elements: ");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
mergeSort(a, 0, n - 1);
printf("Sorted array: ");
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}Write a C program to implement an adjacency list representation of an undirected graph. The program should allow the user to input the number of vertices and edges, then input each edge as a pair of vertices. It should build the adjacency list and finally display the adjacency list for each vertex. Use dynamic memory allocation for the adjacency list nodes.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int dest;
struct Node* next;
};
struct Graph {
int V;
struct Node** adjList;
};
struct Node* createNode(int dest) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}
struct Graph* createGraph(int V) {
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->V = V;
graph->adjList = (struct Node**)malloc(V * sizeof(struct Node*));
for (int i = 0; i < V; i++)
graph->adjList[i] = NULL;
return graph;
}
void addEdge(struct Graph* graph, int src, int dest) {
struct Node* newNode = createNode(dest);
newNode->next = graph->adjList[src];
graph->adjList[src] = newNode;
newNode = createNode(src);
newNode->next = graph->adjList[dest];
graph->adjList[dest] = newNode;
}
void printGraph(struct Graph* graph) {
for (int v = 0; v < graph->V; v++) {
struct Node* temp = graph->adjList[v];
printf("Vertex %d: ", v);
while (temp) {
printf("-> %d ", temp->dest);
temp = temp->next;
}
printf("\n");
}
}
int main() {
int V, E;
printf("Enter number of vertices: ");
scanf("%d", &V);
printf("Enter number of edges: ");
scanf("%d", &E);
struct Graph* graph = createGraph(V);
printf("Enter edges (src dest):\n");
for (int i = 0; i < E; i++) {
int src, dest;
scanf("%d %d", &src, &dest);
addEdge(graph, src, dest);
}
printf("Adjacency List:\n");
printGraph(graph);
return 0;
}Write a C program to implement a queue using two stacks. The program should support enqueue and dequeue operations. Use the following sequence of operations: enqueue(10), enqueue(20), enqueue(30), dequeue(), enqueue(40), dequeue(), dequeue(), dequeue(). After each dequeue, print the dequeued element. If the queue is empty, print 'Queue is empty'. Assume the stack size is 5.
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
int stack1[MAX], stack2[MAX];
int top1 = -1, top2 = -1;
void push1(int data) {
if (top1 == MAX - 1) {
printf("Stack1 overflow\n");
return;
}
stack1[++top1] = data;
}
int pop1() {
if (top1 == -1) {
printf("Stack1 underflow\n");
return -1;
}
return stack1[top1--];
}
void push2(int data) {
if (top2 == MAX - 1) {
printf("Stack2 overflow\n");
return;
}
stack2[++top2] = data;
}
int pop2() {
if (top2 == -1) {
printf("Stack2 underflow\n");
return -1;
}
return stack2[top2--];
}
void enqueue(int data) {
push1(data);
}
int dequeue() {
if (top1 == -1 && top2 == -1) {
printf("Queue is empty\n");
return -1;
}
if (top2 == -1) {
while (top1 != -1) {
push2(pop1());
}
}
return pop2();
}
int main() {
enqueue(10);
enqueue(20);
enqueue(30);
printf("Dequeued: %d\n", dequeue());
enqueue(40);
printf("Dequeued: %d\n", dequeue());
printf("Dequeued: %d\n", dequeue());
printf("Dequeued: %d\n", dequeue());
return 0;
}Write a C program to implement inorder traversal of a binary tree. The program should create a binary tree with the following structure: root node with value 50, left child 30, right child 70. Node 30 has left child 20 and right child 40. Node 20 has left child 10 and right child 25. Node 70 has left child 60 and right child 80. Node 80 has left child 75 and right child 90. After building the tree, perform an inorder traversal and print the node values separated by spaces.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* left;
struct node* right;
};
struct node* createNode(int val) {
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = val;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void inorderTraversal(struct node* root) {
if (root == NULL)
return;
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
int main() {
struct node* root = createNode(50);
root->left = createNode(30);
root->right = createNode(70);
root->left->left = createNode(20);
root->left->right = createNode(40);
root->left->left->left = createNode(10);
root->left->left->right = createNode(25);
root->right->left = createNode(60);
root->right->right = createNode(80);
root->right->right->left = createNode(75);
root->right->right->right = createNode(90);
printf("Inorder traversal of the binary tree: ");
inorderTraversal(root);
printf("\n");
return 0;
}Write a C program that builds a small binary tree of integers and prints its inorder, preorder and postorder traversals. Use the tree: root = 50, left child of root = 30, right child of root = 70, left child of 30 = 20, right child of 30 = 40, left child of 70 = 60, right child of 70 = 80. The program should print each traversal on its own line with values separated by spaces.
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *left;
struct node *right;
};
struct node* createNode(int value) {
struct node *n = (struct node*)malloc(sizeof(struct node));
n->data = value;
n->left = NULL;
n->right = NULL;
return n;
}
void inorder(struct node *root) {
if (root == NULL) return;
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
void preorder(struct node *root) {
if (root == NULL) return;
printf("%d ", root->data);
preorder(root->left);
preorder(root->right);
}
void postorder(struct node *root) {
if (root == NULL) return;
postorder(root->left);
postorder(root->right);
printf("%d ", root->data);
}
int main() {
struct node *root = createNode(50);
root->left = createNode(30);
root->right = createNode(70);
root->left->left = createNode(20);
root->left->right = createNode(40);
root->right->left = createNode(60);
root->right->right = createNode(80);
printf("Inorder: ");
inorder(root);
printf("\nPreorder: ");
preorder(root);
printf("\nPostorder: ");
postorder(root);
printf("\n");
return 0;
}
Write a C program that implements insertion sort to sort an array of integers in ascending order. The program should read n integers, sort them using insertion sort, and print the sorted array.
#include <stdio.h>
void insert(int a[], int n) {
int i, j, temp;
for (i = 1; i < n; i++) {
temp = a[i];
j = i - 1;
while (j >= 0 && temp < a[j]) {
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = temp;
}
}
int main() {
int a[100], n, i;
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d integers: ", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
insert(a, n);
printf("Sorted array: ");
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}Write a C++ program that implements a class `IntList` (a simple growable array of integers using a raw array with a capacity that doubles when full) and then a class `IntStack` built on top of `IntList` that supports `push(int)`, `pop()` and `peek()`. The `pop` and `peek` methods must handle the empty-stack case safely (print an error message instead of crashing). In `main`, push 7 and 14, print the top element, pop one element, then print the new top element.
#include <iostream>
using namespace std;
class IntList {
private:
int* data;
int cap;
int count;
public:
IntList() : cap(2), count(0) { data = new int[cap]; }
~IntList() { delete[] data; }
void add(int value) {
if (count == cap) {
cap *= 2;
int* bigger = new int[cap];
for (int i = 0; i < count; i++) bigger[i] = data[i];
delete[] data;
data = bigger;
}
data[count++] = value;
}
int get(int index) { return data[index]; }
void removeLast() { if (count > 0) count--; }
int size() { return count; }
};
class IntStack {
private:
IntList list;
public:
void push(int value) { list.add(value); }
int pop() {
if (list.size() == 0) { cout << "Stack is empty" << endl; return -1; }
int value = list.get(list.size() - 1);
list.removeLast();
return value;
}
int peek() {
if (list.size() == 0) { cout << "Stack is empty" << endl; return -1; }
return list.get(list.size() - 1);
}
bool isEmpty() { return list.size() == 0; }
};
int main() {
IntStack st;
st.push(7);
st.push(14);
cout << "Top element: " << st.peek() << endl;
cout << "Popped element: " << st.pop() << endl;
cout << "New top element: " << st.peek() << endl;
return 0;
}Write a C++ program that implements a class `BstStore` representing a basic binary search tree of integers. The class must provide a method `add(int value)` to insert a value and a method `has(int value)` that returns true if the value exists in the tree. In `main`, insert the values 25, 12, 40, 8 and 30, then print whether 40 and 17 are present in the tree.
#include <iostream>
using namespace std;
class Node {
public:
int value;
Node *left, *right;
Node(int v) : value(v), left(nullptr), right(nullptr) {}
};
class BstStore {
private:
Node* root;
Node* addRec(Node* node, int value) {
if (node == nullptr) return new Node(value);
if (value < node->value)
node->left = addRec(node->left, value);
else
node->right = addRec(node->right, value);
return node;
}
bool hasRec(Node* node, int value) {
if (node == nullptr) return false;
if (node->value == value) return true;
return value < node->value ? hasRec(node->left, value) : hasRec(node->right, value);
}
public:
BstStore() : root(nullptr) {}
void add(int value) { root = addRec(root, value); }
bool has(int value) { return hasRec(root, value); }
};
int main() {
BstStore tree;
tree.add(25);
tree.add(12);
tree.add(40);
tree.add(8);
tree.add(30);
cout << "Is 40 present? " << (tree.has(40) ? "Yes" : "No") << endl;
cout << "Is 17 present? " << (tree.has(17) ? "Yes" : "No") << endl;
return 0;
}Write a C++ program: Implement a graph using an adjacency list and perform a depth-first search (DFS) starting from a given node. The graph has 5 vertices (0 to 4) and the following directed edges: 0→1, 0→2, 1→3, 2→4, 3→0, 4→1. Write a function `DFS(int start)` that prints the nodes visited in DFS order. In `main`, call `DFS(1)` and print the result.
#include <iostream>
#include <list>
#include <vector>
using namespace std;
class Graph {
private:
int numVertices;
list<int>* adjLists;
vector<bool> visited;
void DFSUtil(int v) {
visited[v] = true;
cout << v << " ";
for (int adj : adjLists[v]) {
if (!visited[adj]) {
DFSUtil(adj);
}
}
}
public:
Graph(int vertices) : numVertices(vertices), adjLists(new list<int>[vertices]), visited(vertices, false) {}
void addEdge(int src, int dest) {
adjLists[src].push_back(dest);
}
void DFS(int start) {
fill(visited.begin(), visited.end(), false);
DFSUtil(start);
}
};
int main() {
Graph g(5);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(2, 4);
g.addEdge(3, 0);
g.addEdge(4, 1);
cout << "Depth First Traversal starting from vertex 1:" << endl;
g.DFS(1);
return 0;
}Write a C++ program: Implement a template class `RefPtr` that mimics a smart pointer with reference counting. The class should hold a pointer of any type and automatically delete the managed object when the last `RefPtr` referring to it is destroyed. Provide a copy constructor, copy assignment operator, and a dereference operator. In `main`, create a `RefPtr` to an `int` initialized to 25, make a copy, and print the value using the copy.
#include <iostream>
using namespace std;
template <typename T>
class RefPtr {
private:
T* ptr;
unsigned* count;
public:
RefPtr(T* p = nullptr) : ptr(p), count(new unsigned(1)) {}
RefPtr(const RefPtr<T>& other) : ptr(other.ptr), count(other.count) {
++(*count);
}
RefPtr<T>& operator=(const RefPtr<T>& other) {
if (this != &other) {
if (--(*count) == 0) {
delete ptr;
delete count;
}
ptr = other.ptr;
count = other.count;
++(*count);
}
return *this;
}
~RefPtr() {
if (--(*count) == 0) {
delete ptr;
delete count;
}
}
T& operator*() {
return *ptr;
}
};
int main() {
RefPtr<int> p1(new int(25));
RefPtr<int> p2 = p1;
cout << "Value: " << *p2 << endl;
return 0;
}Write a C++ program that defines a template class `RawAllocator<T>` which allocates raw memory for an array of n elements of type T without constructing the objects, and frees it later. Provide a method `allocate(size_t n)` returning a T* and a method `deallocate()` freeing the memory. In `main`, allocate space for 4 ints, construct them with placement new using the values 7, 14, 21, 28, print them, then destroy and deallocate.
#include <iostream>
#include <new>
using namespace std;
template <typename T>
class RawAllocator {
private:
T* ptr;
public:
RawAllocator() : ptr(nullptr) {}
T* allocate(size_t n) {
ptr = static_cast<T*>(::operator new(n * sizeof(T)));
return ptr;
}
void deallocate() {
::operator delete(ptr);
ptr = nullptr;
}
};
int main() {
RawAllocator<int> alloc;
int* arr = alloc.allocate(4);
int values[4] = {7, 14, 21, 28};
for (int i = 0; i < 4; ++i) {
new (&arr[i]) int(values[i]);
}
for (int i = 0; i < 4; ++i) {
cout << arr[i] << " ";
}
cout << endl;
for (int i = 0; i < 4; ++i) {
arr[i].~int();
}
alloc.deallocate();
return 0;
}Write a C++ program that implements a thread-safe queue class named `SafeQueue` using a mutex and a condition variable. The class must provide a `push` method to add an integer and a `pop` method to remove and return an integer, both safe to call from multiple threads. In `main`, demonstrate usage by pushing the values 25 and 40 from one thread and popping them in another thread, printing each popped value.
#include <iostream>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <thread>
using namespace std;
class SafeQueue {
private:
queue<int> q;
mutex mtx;
condition_variable cv;
public:
void push(int value) {
lock_guard<mutex> lock(mtx);
q.push(value);
cv.notify_one();
}
int pop() {
unique_lock<mutex> lock(mtx);
cv.wait(lock, [this] { return !q.empty(); });
int value = q.front();
q.pop();
return value;
}
};
int main() {
SafeQueue sq;
thread producer([&sq]() {
sq.push(25);
sq.push(40);
});
thread consumer([&sq]() {
cout << sq.pop() << endl;
cout << sq.pop() << endl;
});
producer.join();
consumer.join();
return 0;
}Write a C++17 program that defines a function `showValue` taking a `std::variant<int, double, std::string>` and uses `std::visit` with a generic lambda to print the stored value regardless of its type. In main, call it with an int, a double, and a string.
#include <iostream>
#include <variant>
#include <string>
using Value = std::variant<int, double, std::string>;
void showValue(const Value& v) {
std::visit([](const auto& x) { std::cout << x << std::endl; }, v);
}
int main() {
Value v1 = 42;
Value v2 = 2.75;
Value v3 = std::string("Namaste C++17");
showValue(v1);
showValue(v2);
showValue(v3);
return 0;
}Write a C++ program that asks the user to enter a word. Reverse the word, write the reversed word to a file named "result.txt", then read the word back from that file and print it to the console.
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string word;
cout << "Enter a word: ";
getline(cin, word);
reverse(word.begin(), word.end());
ofstream outFile("result.txt");
outFile << word;
outFile.close();
string fileContent;
ifstream inFile("result.txt");
getline(inFile, fileContent);
cout << "Word from file: " << fileContent << endl;
inFile.close();
return 0;
}Write a C++ program that defines a base class `Vehicle` with private member variables `make` (string), `model` (string) and `year` (int), plus public setter and getter functions for them. Then create a derived class `Bike` that inherits publicly from `Vehicle` and adds a private integer member `engineCC` with public setter and getter. Finally, write a function `printVehicleDetails(const Vehicle &v)` that prints the make, model and year of the vehicle passed to it, and in `main` create a `Bike` object, set make to "Hero", model to "Splendor", year to 2021 and engineCC to 100, then call `printVehicleDetails` on it.
#include <iostream>
#include <string>
using namespace std;
class Vehicle {
private:
string make;
string model;
int year;
public:
void setMake(const string &m) { make = m; }
void setModel(const string &m) { model = m; }
void setYear(int y) { year = y; }
string getMake() const { return make; }
string getModel() const { return model; }
int getYear() const { return year; }
};
class Bike : public Vehicle {
private:
int engineCC;
public:
void setEngineCC(int cc) { engineCC = cc; }
int getEngineCC() const { return engineCC; }
};
void printVehicleDetails(const Vehicle &v) {
cout << "Vehicle Details: " << v.getMake() << " " << v.getModel() << " " << v.getYear() << endl;
}
int main() {
Bike myBike;
myBike.setMake("Hero");
myBike.setModel("Splendor");
myBike.setYear(2021);
myBike.setEngineCC(100);
printVehicleDetails(myBike);
return 0;
}Write a C++ class `DynamicArray` that behaves like a resizable array. It should start with a capacity of 1 and double its capacity whenever it becomes full. Implement a method `add(int item)` to append an item and a method `get(int index)` to return the item at a given index. In main(), create a DynamicArray, add the values 7, 14 and 21, and print the elements at indices 0, 1 and 2.
#include <iostream>
#include <cassert>
using namespace std;
class DynamicArray {
private:
int* data;
int size;
int capacity;
void resize() {
capacity *= 2;
int* newData = new int[capacity];
for (int i = 0; i < size; i++) {
newData[i] = data[i];
}
delete[] data;
data = newData;
}
public:
DynamicArray() : data(new int[1]), size(0), capacity(1) {}
~DynamicArray() {
delete[] data;
}
void add(int item) {
if (size == capacity) {
resize();
}
data[size++] = item;
}
int get(int index) {
assert(index >= 0 && index < size);
return data[index];
}
};
int main() {
DynamicArray arr;
arr.add(7);
arr.add(14);
arr.add(21);
cout << "Element at index 0: " << arr.get(0) << endl;
cout << "Element at index 1: " << arr.get(1) << endl;
cout << "Element at index 2: " << arr.get(2) << endl;
return 0;
}Write a C program to implement a linear queue using an array. The program should provide a menu with options to insert an element, delete an element, peek at the front element, display the queue, and exit. The queue should have a maximum capacity of 10 elements. Handle overflow and underflow conditions appropriately.
#include <stdio.h>
#define MAX 10
int queue[MAX];
int front = -1, rear = -1;
void insert() {
int num;
if (rear == MAX - 1) {
printf("\nOVERFLOW");
return;
}
printf("\nEnter the element to insert: ");
scanf("%d", &num);
if (front == -1 && rear == -1) {
front = rear = 0;
} else {
rear++;
}
queue[rear] = num;
}
int delete_element() {
int val;
if (front == -1 || front > rear) {
printf("\nUNDERFLOW");
return -1;
}
val = queue[front];
front++;
if (front > rear) {
front = rear = -1;
}
return val;
}
int peek() {
if (front == -1 || front > rear) {
printf("\nQUEUE IS EMPTY");
return -1;
}
return queue[front];
}
void display() {
int i;
printf("\n");
if (front == -1 || front > rear) {
printf("QUEUE IS EMPTY");
} else {
for (i = front; i <= rear; i++) {
printf("%d ", queue[i]);
}
}
}
int main() {
int choice, val;
do {
printf("\n1. Insert an element into a queue");
printf("\n2. Delete an element from a queue");
printf("\n3. Peek an element from a queue");
printf("\n4. Display the queue");
printf("\n5. EXIT");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
insert();
break;
case 2:
val = delete_element();
if (val != -1)
printf("\nThe number deleted is: %d", val);
break;
case 3:
val = peek();
if (val != -1)
printf("\nThe first value in queue is: %d", val);
break;
case 4:
display();
break;
}
} while (choice != 5);
return 0;
}Write a C program to implement quicksort. The program should sort an array of integers in ascending order using the quicksort algorithm with the last element as pivot. Include a function to print the array before and after sorting.
#include <stdio.h>
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
int main() {
int n;
printf("Enter number of elements: ");
scanf("%d", &n);
int arr[n];
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Original array: ");
printArray(arr, n);
quickSort(arr, 0, n - 1);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}Write a C program to store a sparse matrix using the array representation. The program should read a 3x4 matrix (3 rows, 4 columns) from the user, count the non-zero elements, and then display the non-zero elements in a tabular form with three columns: row index, column index, and value. Use 0-based indexing for rows and columns.
#include <stdio.h>
int main() {
int mat[3][4];
int i, j, count = 0;
printf("Enter elements of 3x4 matrix:\n");
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++) {
scanf("%d", &mat[i][j]);
if (mat[i][j] != 0)
count++;
}
}
if (count == 0) {
printf("Matrix has no non-zero elements.\n");
return 0;
}
int sparse[3][count];
int k = 0;
for (i = 0; i < 3; i++) {
for (j = 0; j < 4; j++) {
if (mat[i][j] != 0) {
sparse[0][k] = i;
sparse[1][k] = j;
sparse[2][k] = mat[i][j];
k++;
}
}
}
printf("Row\tColumn\tValue\n");
for (i = 0; i < count; i++) {
printf("%d\t%d\t%d\n", sparse[0][i], sparse[1][i], sparse[2][i]);
}
return 0;
}Write a Java program that stores a sparse matrix using a linked list. Use the 4x4 matrix: row0 = {0,0,3,0}, row1 = {0,5,0,0}, row2 = {7,0,0,2}, row3 = {0,0,0,6}. Create a Node class with row, col, value and next fields. Traverse the matrix row by row, and for every non-zero element append a node to the linked list. Finally, print each node as 'row col value' on its own line.class Node {
int row;
int col;
int value;
Node next;
Node(int r, int c, int val) { row = r; col = c; this.value = val; }
}
public class Sparse {
public static void main(String[] args) {
int sparseMatrix[][] = {
{0, 0, 3, 0},
{0, 5, 0, 0},
{7, 0, 0, 2},
{0, 0, 0, 6}
};
Node start = null;
Node tail = null;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 4; j++) {
if (sparseMatrix[i][j] != 0) {
Node temp = new Node(i, j, sparseMatrix[i][j]);
temp.next = null;
if (start == null) {
start = temp;
tail = temp;
} else {
tail.next = temp;
tail = tail.next;
}
}
}
Node itr = start;
while (itr != null) {
System.out.println(itr.row + " " + itr.col + " " + itr.value);
itr = itr.next;
}
}
}Write a Java program that implements a Trie supporting insertion and search. The search operation should return true only if the given word exists as a complete word in the Trie (not merely as a prefix). Implement a helper that walks down the Trie following the characters of the word and returns the final node (or null if the path breaks), then use it in the search method.
import java.util.HashMap;
import java.util.Map;
class TrieNode {
Map<Character, TrieNode> children = new HashMap<>();
boolean endOfWord = false;
}
public class TrieSearch {
private TrieNode root;
public TrieSearch() {
root = new TrieNode();
}
public void insert(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
TrieNode node = current.children.get(ch);
if (node == null) {
node = new TrieNode();
current.children.put(ch, node);
}
current = node;
}
current.endOfWord = true;
}
private TrieNode walkDown(String word) {
TrieNode current = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (current.children.containsKey(ch)) {
current = current.children.get(ch);
} else {
return null;
}
}
return current;
}
public boolean search(String word) {
TrieNode node = walkDown(word);
return node != null && node.endOfWord;
}
public static void main(String[] args) {
TrieSearch trie = new TrieSearch();
trie.insert("mango");
trie.insert("man");
trie.insert("chennai");
System.out.println(trie.search("man"));
System.out.println(trie.search("mango"));
System.out.println(trie.search("ma"));
System.out.println(trie.search("delhi"));
}
}Write a C program that implements a Trie data structure to insert and search for words. The program should include functions to insert a word and to search for a word, and a main function to demonstrate with the words 'cat', 'car', and 'dog'.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ALPHABET_SIZE 26
typedef struct TrieNode {
struct TrieNode* children[ALPHABET_SIZE];
int isEndOfWord;
} TrieNode;
TrieNode* createNode() {
TrieNode* node = (TrieNode*)malloc(sizeof(TrieNode));
node->isEndOfWord = 0;
for (int i = 0; i < ALPHABET_SIZE; i++)
node->children[i] = NULL;
return node;
}
void insert(TrieNode* root, const char* word) {
TrieNode* current = root;
while (*word) {
int index = *word - 'a';
if (!current->children[index])
current->children[index] = createNode();
current = current->children[index];
word++;
}
current->isEndOfWord = 1;
}
int search(TrieNode* root, const char* word) {
TrieNode* current = root;
while (*word) {
int index = *word - 'a';
if (!current->children[index])
return 0;
current = current->children[index];
word++;
}
return current->isEndOfWord;
}
int main() {
TrieNode* root = createNode();
insert(root, "cat");
insert(root, "car");
insert(root, "dog");
printf("Search 'cat': %s\n", search(root, "cat") ? "Found" : "Not Found");
printf("Search 'car': %s\n", search(root, "car") ? "Found" : "Not Found");
printf("Search 'dog': %s\n", search(root, "dog") ? "Found" : "Not Found");
printf("Search 'cow': %s\n", search(root, "cow") ? "Found" : "Not Found");
return 0;
}Write a C program to implement bitonic sort. The program should work only when the size of the input array is a power of 2. The program should sort the array in ascending order.
#include <stdio.h>
void exchange(int a[], int i, int j, int d) {
int temp;
if (d == (a[i] > a[j])) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
void merge(int a[], int beg, int c, int d) {
int k, i;
if (c > 1) {
k = c / 2;
for (i = beg; i < beg + k; i++)
exchange(a, i, i + k, d);
merge(a, beg, k, d);
merge(a, beg + k, k, d);
}
}
void bitonicSort(int a[], int beg, int c, int d) {
int k;
if (c > 1) {
k = c / 2;
bitonicSort(a, beg, k, 1);
bitonicSort(a, beg + k, k, 0);
merge(a, beg, c, d);
}
}
int main() {
int n, i;
printf("Enter number of elements (power of 2): ");
scanf("%d", &n);
int a[n];
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
bitonicSort(a, 0, n, 1);
printf("Sorted array:\n");
for (i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}Write a C++ program that implements a simple thread pool. Create a class `TaskPool` that manages a fixed number of worker threads. The class should have a method `addTask` to enqueue function objects (tasks) and a method `stop` to shut down the pool gracefully. In `main`, create a `TaskPool` with 3 threads, add a few tasks that print messages, and then stop the pool.
#include <iostream>
#include <vector>
#include <thread>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <queue>
class TaskPool {
public:
TaskPool(size_t numThreads) : stopping(false) {
for (size_t i = 0; i < numThreads; ++i) {
workers.emplace_back([this] {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(mtx);
cv.wait(lock, [this] { return stopping || !tasks.empty(); });
if (stopping && tasks.empty())
return;
task = std::move(tasks.front());
tasks.pop();
}
task();
}
});
}
}
void addTask(std::function<void()> task) {
{
std::lock_guard<std::mutex> lock(mtx);
tasks.push(std::move(task));
}
cv.notify_one();
}
void stop() {
{
std::lock_guard<std::mutex> lock(mtx);
stopping = true;
}
cv.notify_all();
for (std::thread &worker : workers) {
if (worker.joinable())
worker.join();
}
}
~TaskPool() {
if (!stopping)
stop();
}
private:
std::vector<std::thread> workers;
std::queue<std::function<void()>> tasks;
std::mutex mtx;
std::condition_variable cv;
bool stopping;
};
int main() {
TaskPool pool(3);
pool.addTask([] { std::cout << "Task 1 executed" << std::endl; });
pool.addTask([] { std::cout << "Task 2 executed" << std::endl; });
pool.addTask([] { std::cout << "Task 3 executed" << std::endl; });
pool.stop();
return 0;
}Write a C++ template metaprogram `Power` that computes the power of a compile-time constant integer base raised to a compile-time constant exponent. Use template specialization to achieve this. The program should output the result for base 3 and exponent 4.
#include <iostream>
template <unsigned int Base, unsigned int Exp>
struct Power {
static const unsigned long long value = Base * Power<Base, Exp - 1>::value;
};
template <unsigned int Base>
struct Power<Base, 0> {
static const unsigned long long value = 1;
};
int main() {
std::cout << Power<3, 4>::value << std::endl;
return 0;
}Write a C++ program that implements a memory-efficient doubly linked list using a single pointer per node (an XOR linked list). The program should insert values at the beginning of the list using an insert() function, and a getList() function should print the list in both forward and backward directions. For example, if the values 40, 30, 20, 10 are inserted one after another at the beginning, the forward traversal prints "40 30 20 10" and the backward traversal prints "10 20 30 40". Similarly, inserting 5, 4, 3, 2, 1 gives forward "5 4 3 2 1" and backward "1 2 3 4 5".
#include <iostream>
#include <cstdint>
using namespace std;
class Node {
public:
int data;
Node* npx; // XOR of prev and next pointers
Node(int x) {
data = x;
npx = nullptr;
}
};
class XORList {
private:
Node* head;
Node* tail;
Node* XOR(Node* a, Node* b) {
return (Node*)((uintptr_t)a ^ (uintptr_t)b);
}
public:
XORList() {
head = nullptr;
tail = nullptr;
}
void insert(int data) {
Node* newNode = new Node(data);
if (head == nullptr) {
head = newNode;
tail = newNode;
} else {
newNode->npx = XOR(nullptr, head);
head->npx = XOR(newNode, head->npx);
head = newNode;
}
}
void getList() {
// Forward traversal
Node* curr = head;
Node* prev = nullptr;
Node* next;
while (curr != nullptr) {
cout << curr->data << " ";
next = XOR(prev, curr->npx);
prev = curr;
curr = next;
}
cout << endl;
// Backward traversal
curr = tail;
Node* nxt = nullptr;
Node* prv;
while (curr != nullptr) {
cout << curr->data << " ";
prv = XOR(nxt, curr->npx);
nxt = curr;
curr = prv;
}
cout << endl;
}
};
int main() {
XORList list;
list.insert(10);
list.insert(20);
list.insert(30);
list.insert(40);
list.getList();
return 0;
}Write a C program that builds the suffix array of the string "banana" using a simple (non-linear) approach: generate all suffixes, sort them lexicographically, and print the starting indices of the sorted suffixes in order. The program should print the suffix array as space-separated indices.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct suffix {
int index;
char *suff;
};
int cmp(const void *a, const void *b) {
struct suffix *s1 = (struct suffix*)a;
struct suffix *s2 = (struct suffix*)b;
return strcmp(s1->suff, s2->suff);
}
int main() {
char text[] = "banana";
int n = strlen(text);
struct suffix suffixes[6];
int i;
for (i = 0; i < n; i++) {
suffixes[i].index = i;
suffixes[i].suff = (text + i);
}
qsort(suffixes, n, sizeof(struct suffix), cmp);
printf("Suffix array: ");
for (i = 0; i < n; i++)
printf("%d ", suffixes[i].index);
printf("\n");
return 0;
}
INTMAT EDTECH (OPC) PRIVATE LIMITED
No - 16, Javaraiahna Doddi, Mysore Road,
Bengaluru Urban, BENGALURU,
Karnataka 560098, India
contact@intmatedtech.com