0% found this document useful (0 votes)
29 views

DSAlab

The document contains 19 questions about C programming concepts and solutions. Each question provides a full code sample to solve a programming task like adding elements from an array, sorting arrays, calculating sums and averages, using structures, and more. The questions cover a wide range of basic to intermediate C programming skills.

Uploaded by

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

DSAlab

The document contains 19 questions about C programming concepts and solutions. Each question provides a full code sample to solve a programming task like adding elements from an array, sorting arrays, calculating sums and averages, using structures, and more. The questions cover a wide range of basic to intermediate C programming skills.

Uploaded by

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

Q-1) Write a c program to add elements from array in odd position.

#include <stdio.h>
int main(){
int s = 0;
int arr[11]={0,1,2,3,4,5,6,7,8,9,10};
for (int i=1;i<11;i=i+2){
printf("%d\n"
,arr[i]);
s= s+arr[i];
}
printf("The sum is : %d"
,s);
}
Q-2)Write a c program to add elements from array in even position.
#include <stdio.h>
int main(){
int s = 0;
int arr[11]={0,1,2,3,4,5,6,7,8,9,10};
for (int i=0;i<11;i=i+2){
printf("%d\n"
,arr[i]);
s= s+arr[i];
}
printf("The sum is : %d"
,s);
}
Q-3) Write a c program to print array in reverse order.
#include <stdio.h>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
printf("Original Array: ");
for (int i = 0; i < size; i++) {printf("%d "
, arr[i]);
}
printf("\n");
printf("Reversed Array: ");
for (int i = size - 1; i >= 0; i--) {
printf("%d "
, arr[i]);
}
return 0;
}
Q-4) Write a c program to square the elements of array and print the sum.
#include <stdio.h>
int main() {
int s =0;
int arr[11]={1,2,3,4,5,6,7,8,9,10,11};
for (int i=0;i<11;i++){
s = s+(arr[i]*arr[i]);
}printf("%d\n"
,s);
return 0;
}
Q-5) Write a c program to print the factorial of a given number
#include <stdio.h>
int main() {
int number, factorial = 1;
printf("Enter a non-negative integer: ");
scanf("%d"
, &number);
if (number < 0) {
printf("Factorial is not defined for negative numbers.\n");
} else {
for (int i = 1; i <= number; ++i) {
factorial *= i;
}
printf("Factorial of %d = %d\n"
, number, factorial);
}return 0;
}
Q-6) Write a c program to print Fibonacci series up to a given number
#include <stdio.h>
int main() {
int n, first = 0, second = 1, next;
printf("Enter the number of iterations for the Fibonacci series: ");
scanf("%d"
, &n);
printf("Fibonacci Series up to %d iterations:\n"
, n);
for (int i = 0; i < n; i++) {
if (i <= 1) {
next = i;
} else {
next = first + second;
first = second;
second = next;
}
printf("%d "
, next);
}
printf("\n");
return 0;
}
Q-7) Write a c program to print numbers in ascending order
#include <stdio.h>
void sortAscending(int arr[], int n) {
int temp;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}}
}
}
int main() {
int n;
printf("Enter the size of the array: ");
scanf("%d"
, &n);
int arr[n];
printf("Enter %d elements:\n"
, n);
for (int i = 0; i < n; i++)
scanf("%d"
, &arr[i]);
sortAscending(arr, n);
printf("Numbers in ascending order: ");
for (int i = 0; i < n; i++)
printf("%d "
, arr[i]);
return 0;
}
Q-8)Write a c program to print numbers in descending order.
#include <stdio.h>
void sortDescending(int arr[], int n) {
int temp;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}
int main() {
int n;
printf("Enter the size of the array: ");
scanf("%d"
, &n);
int arr[n];
printf("Enter %d elements:\n"
, n);
for (int i = 0; i < n; i++)
scanf("%d"
, &arr[i]);
sortDescending(arr, n);
printf("Numbers in descending order: ");
for (int i = 0; i < n; i++)printf("%d "
, arr[i]);
return 0;
}
Q-9) Write a c program to print the elements from odd position
#include <stdio.h>
int main(){
int arr[11]={0,1,2,3,4,5,6,7,8,9,10};
for (int i=1;i<11;i=i+2){
printf("%d\n"
,arr[i]);
}
}
Q-10) Write a c program to print the elements from even position
#include <stdio.h>
int main(){
int arr[11]={0,1,2,3,4,5,6,7,8,9,10};
for (int i=0;i<11;i=i+2){
printf("%d\n"
,arr[i]);
}
}
Q-11)Write a c Program to read the information about book and print.
#include <stdio.h>struct Book {
char title[100];
char author[100];
int year;
float price;
};
int main() {
struct Book book;
printf("Enter information about the book:\n");
printf("Title: ");
scanf(" %[^\n]", book.title);
printf("Author: ");
scanf(" %[^\n]", book.author);
printf("Year of publication: ");
scanf("%d"
, &book.year);
printf("Price: ");
scanf("%f"
, &book.price);
printf("\nBook Information:\n");
printf("Title: %s\n"
, book.title);
printf("Author: %s\n"
, book.author);
printf("Year of publication: %d\n"
, book.year);
printf("Price: $%.2f\n"
, book.price);
return 0;
}
Q-12) write a c program to read the information about 10 books.
#include <stdio.h>
struct Book {
char title[100];
char author[100];
int year;
float price;
};
int main() {
struct Book books[10];
printf("Enter information about 10 books:\n");for (int i = 0; i < 10; i++) {
printf("\nBook %d:\n", i + 1);
printf("Title: ");
scanf(" %[^\n]", books[i].title);
printf("Author: ");
scanf(" %[^\n]", books[i].author);
printf("Year of publication: ");
scanf("%d"
, &books[i].year);
printf("Price: ");
scanf("%f"
, &books[i].price);
}
printf("\nBook Information:\n");
for (int i = 0; i < 10; i++) {
printf("\nBook %d:\n", i + 1);
printf("Title: %s\n"
, books[i].title);
printf("Author: %s\n"
, books[i].author);
printf("Year of publication: %d\n"
, books[i].year);
printf("Price: $%.2f\n"
, books[i].price);
}
return 0;
}
Q-13)write a c program to read array of 10 integer and print the sum
using pointer variable
#include <stdio.h>
int main() {
int arr[10];
int *ptr = arr;
int sum = 0;
printf("Enter 10 integers:\n");
for (int i = 0; i < 10; i++) {
scanf("%d", ptr + i);
}
for (int i = 0; i < 10; i++) {
sum += *(ptr + i);
}
printf("Sum of the elements: %d\n", sum);
return 0;
}
Q-14) Write a c program to calculate the Net Salary of an employee
using structures Basic-5000, DA-50%, HRA-12%
#include <stdio.h>
struct Employee {
char name[50];
int basicSalary;
};
float calculateNetSalary(struct Employee emp) {
float DA_percentage = 0.5;
float HRA_percentage = 0.12;
float DA = emp.basicSalary * DA_percentage;
float HRA = emp.basicSalary * HRA_percentage;
float netSalary = emp.basicSalary + DA + HRA;
return netSalary;
}
int main() {
struct Employee emp;
printf("Enter employee name: ");
scanf(" %[^\n]", emp.name);
printf("Enter basic salary: ");
scanf("%d"
, &emp.basicSalary);
float netSalary = calculateNetSalary(emp);printf("\nEmployee Details:\n");
printf("Name: %s\n"
, emp.name);
printf("Basic Salary: %d\n"
, emp.basicSalary);
printf("Net Salary: %.2f\n", netSalary);
return 0;
}
Q-15) Write a c program to calculate the electricity bill for the customer
using structures
using meter reading.
Bill Amount = unites slab
If unites <100-0/-
Unites> 100 and <=200-2/-
Unites 200 and <=300-4/-
Unites >300-5/-
#include <stdio.h>
int main(){
struct bill{
int c_no;
int units;
int cost;
}b1;
b1.c_no = 1;
printf("Enter the number of units consumed: ");
scanf("%d"
,&b1.units);
if (b1.units<100){
b1.cost = 0 ;
}
else if (b1.units>=100 && b1.units<200){
b1.cost = b1.units*2;
}
else if(b1.units>=200 && b1.units<300){
b1.cost =200*2+(b1.units-200)*4;
}
else{b1.cost= (200*2)+(100*4)+(b1.units-300)*5;
}
printf("Customer number: %d\n"
,b1.c_no++);
printf("Total units consumed: %d\n"
,b1.units);
printf("The total b1.cost is: %d\n"
,b1.cost);
return 0;
}
Q-16)Write a c program to calculate net salary for 10 employees.
#include <stdio.h>
struct Employee {
char name[50];
int basicSalary;
};
float calculateNetSalary(struct Employee emp) {
float DA_percentage = 0.5;
float HRA_percentage = 0.12;
float DA = emp.basicSalary * DA_percentage;
float HRA = emp.basicSalary * HRA_percentage;
float netSalary = emp.basicSalary + DA + HRA;
return netSalary;
}
int main() {
struct Employee emp;
int n;
printf("Enter the number of employees: ");
scanf("%d"
,&n);
for(int i=0 ;i<n;i++){
printf("Enter employee name: ");
scanf(" %[^\n]", emp.name);
printf("Enter basic salary: ");
scanf("%d"
, &emp.basicSalary);
float netSalary = calculateNetSalary(emp);
printf("\nEmployee Details:\n");
printf("Name: %s\n"
, emp.name);
printf("Basic Salary: %d\n"
, emp.basicSalary);
printf("Net Salary: %.2f\n\n", netSalary);
}
return 0;
}
Q-17) Write a c program to generate the electricity bill for 10 customers
#include <stdio.h>
int main(){
struct bill{int c_no;
int units;
int cost;
}b1;
b1.c_no = 1;
for (int i=0;i<10;i++){
printf("Enter the number of units consumed: ");
scanf("%d"
,&b1.units);
if (b1.units<100){
b1.cost = 0 ;
}
else if (b1.units>=100 && b1.units<200){
b1.cost = b1.units*2;
}
else if(b1.units>=200 && b1.units<300){
b1.cost =200*2+(b1.units-200)*4;
}
else{
b1.cost= (200*2)+(100*4)+(b1.units-300)*5;
}
printf("Customer number: %d\n"
,b1.c_no++);
printf("Total units consumed: %d\n"
,b1.units);
printf("The total b1.cost is: %d\n"
,b1.cost);
}
return 0;
}

Q-18) Write a c program to calculate the grade of a student using


structures in five subjects.
#include <stdio.h>
#include <string.h>
#define MAX_NAME_LENGTH 100
#define NUM_SUBJECTS 5
struct grades {
char name[MAX_NAME_LENGTH];
int marks;
char grade;
};
int main() {
struct grades student;for (int i = 0; i < NUM_SUBJECTS; i++) {
printf("Enter the name of the student: ");
fgets(student.name, sizeof(student.name), stdin);
student.name[strcspn(student.name,
"\n")] = '\0';
printf("Enter the marks: ");
scanf("%d"
, &student.marks);
if (student.marks > 90) {
student.grade = 'A';
} else if (student.marks > 80) {
student.grade = 'B';
} else if (student.marks > 70) {
student.grade = 'C';
} else if (student.marks > 60) {
student.grade = 'D';
} else {
student.grade = 'F';
}
printf("Grade: %c\n"
, student.grade);
while ((getchar()) != '\n');
}
return 0;
}
Q-19) Write a c program generate invoice and payment bill for ten
products in an online.
#include <stdio.h>
struct Product {
int productID;
char productName[50];
float price;
int quantity;
};
float calculateTotal(struct Product *product) {
return product->price * product->quantity;
}
int main() {
struct Product products[10];
printf("Enter information about 10 products:\n");
for (int i = 0; i < 10; i++) {
printf("\nProduct %d:\n"
, i + 1);
printf("Product ID: ");
scanf("%d"
, &products[i].productID);
printf("Product Name: ");
scanf(" %[^\n]", products[i].productName);
printf("Price: $");
scanf("%f"
, &products[i].price);
printf("Quantity: ");
scanf("%d"
, &products[i].quantity);
}
printf("\nInvoice:\n");
printf("%-15s %-25s %-10s %-10s %-15s\n"
, "Product ID", "Product Name",
"Price ($)", "Quantity", "Total Amount");
float totalAmount = 0.0;
for (int i = 0; i < 10; i++) {
float productTotal = calculateTotal(&products[i]);
totalAmount += productTotal;
printf("%-15d %-25s %-10.2f %-10d %-15.2f\n"
, products[i].productID,
products[i].productName,
products[i].price, products[i].quantity, productTotal);
}
printf("\nPayment Bill:\n");
printf("Total Amount: $%.2f\n", totalAmount);
return 0;
}
Q-20)Write a c program to calculate the Income Tax for an employee
based
on netsalary
for an annum as per the following slab.
If the net salary per annum <300000- Tax is NillFrom 300000 up to
600000 -5%
From 600000 up to 900000 -10%
From 900000 up to 1200000 -15%
From 1200000 up to 1500000 -20%
1500000-30%
#include <stdio.h>
float calculateIncomeTax(float netSalary) {
float tax = 0.0;
if (netSalary < 300000) {
tax = 0;
} else if (netSalary <= 600000) {
tax = 0.05 * (netSalary - 300000);
} else if (netSalary <= 900000) {
tax = 0.05 * (600000 - 300000) + 0.10 * (netSalary - 600000);
} else if (netSalary <= 1200000) {
tax = 0.05 * (600000 - 300000) + 0.10 * (900000 - 600000) + 0.15 * (netSalary
- 900000);
} else if (netSalary <= 1500000) {tax = 0.05 * (600000 - 300000) + 0.10 * (900000 - 600000) + 0.15 * (1200000
- 900000) + 0.20 * (netSalary - 1200000);
} else {
tax = 0.05 * (600000 - 300000) + 0.10 * (900000 - 600000) + 0.15 * (1200000
- 900000) + 0.20 * (1500000 - 1200000) + 0.30 * (netSalary - 1500000);
}
return tax;
}
int main() {
float netSalary;
printf("Enter net salary per annum: $");
scanf("%f"
, &netSalary);
float incomeTax = calculateIncomeTax(netSalary);
printf("\nIncome Tax Calculation:\n");
printf("Net Salary: $%.2f\n", netSalary);
printf("Income Tax: $%.2f\n", incomeTax);
return 0;
}
Q-21) Write a c program to calculate the tax in question 7 for 10
employees.
#include <stdio.h>
struct Employee {
char name[50];
float netSalary;
float incomeTax;
};
float calculateIncomeTax(float netSalary) {
float tax = 0.0;
if (netSalary < 300000) {
tax = 0;
} else if (netSalary <= 600000) {
tax = 0.05 * (netSalary - 300000);
} else if (netSalary <= 900000) {
tax = 0.05 * (600000 - 300000) + 0.10 * (netSalary - 600000);
} else if (netSalary <= 1200000) {
tax = 0.05 * (600000 - 300000) + 0.10 * (900000 - 600000) + 0.15 * (netSalary
- 900000);
} else if (netSalary <= 1500000) {
tax = 0.05 * (600000 - 300000) + 0.10 * (900000 - 600000) + 0.15 * (1200000
- 900000) + 0.20 * (netSalary - 1200000);
} else {
tax = 0.05 * (600000 - 300000) + 0.10 * (900000 - 600000) + 0.15 * (1200000- 900000) + 0.20 * (1500000 -
1200000) + 0.30 * (netSalary - 1500000);
}
return tax;
}
int main() {
struct Employee employees[10];
printf("Enter information about 10 employees:\n");
for (int i = 0; i < 10; i++) {
printf("\nEmployee %d:\n", i + 1);
printf("Name: ");
scanf(" %[^\n]", employees[i].name);
printf("Net Salary per annum: $");
scanf("%f"
, &employees[i].netSalary);
employees[i].incomeTax = calculateIncomeTax(employees[i].netSalary);
}
printf("\nIncome Tax for 10 Employees:\n");
printf("%-15s %-20s %-15s\n"
, "Employee ID", "Name", "Income Tax");
for (int i = 0; i < 10; i++) {
printf("%-15d %-20s $%.2f\n", i + 1, employees[i].name,
employees[i].incomeTax);
}
return 0;
}
Q-22) Write a c program to generate a balance sheet for the company
ZeeOn Tech.
#include <stdio.h>
struct BalanceSheet {
float assets;
float liabilities;
float equity;
};
float calculateEquity(float assets, float liabilities) {
return assets - liabilities;
}
int main() {
struct BalanceSheet zeeOnTechBalanceSheet;
printf("Enter Balance Sheet Information for ZeeOn Tech:\n");
printf("Total Assets: $");
scanf("%f"
, &zeeOnTechBalanceSheet.assets);
printf("Total Liabilities: $");
scanf("%f"
, &zeeOnTechBalanceSheet.liabilities);
zeeOnTechBalanceSheet.equity =
calculateEquity(zeeOnTechBalanceSheet.assets,
zeeOnTechBalanceSheet.liabilities);
printf("\nBalance Sheet for ZeeOn Tech:\n");
printf("Assets: $%.2f\n"
, zeeOnTechBalanceSheet.assets);
printf("Liabilities: $%.2f\n"
, zeeOnTechBalanceSheet.liabilities);
printf("Equity: $%.2f\n"
, zeeOnTechBalanceSheet.equity);return 0;
}
Q-23) Write a c program to generate the invoice for ten books and print
the payment slip.
#include <stdio.h>
struct Book {
char title[100];
char author[100];
float price;
int quantity;
};
float calculateTotal(struct Book *book) {
return book->price * book->quantity;
}
int main() {
struct Book books[10];
printf("Enter information about 10 books:\n");
for (int i = 0; i < 10; i++) {
printf("\nBook %d:\n", i + 1);
printf("Title: ");
scanf(" %[^\n]", books[i].title);
printf("Author: ");
scanf(" %[^\n]", books[i].author);
printf("Price: $");
scanf("%f"
, &books[i].price);
printf("Quantity: ");
scanf("%d"
, &books[i].quantity);
}
printf("\nInvoice:\n");
printf("%-25s %-25s %-10s %-10s %-15s\n"
, "Title", "Author", "Price ($)",
"Quantity", "Total Amount");
float totalAmount = 0.0;
for (int i = 0; i < 10; i++) {
float bookTotal = calculateTotal(&books[i]);
totalAmount += bookTotal;
printf("%-25s %-25s %-10.2f %-10d %-15.2f\n"
, books[i].title, books[i].author,
books[i].price, books[i].quantity, bookTotal);}
printf("\nPayment Slip:\n");
printf("Total Amount: $%.2f\n"
, totalAmount);
return 0;
}

1. Write a C Program to implement Stack using arrays.

#include <stdio.h>

#define MAX_SIZE 10

void initialize(int stack[], int *top) {


*top = -1;
}

int isEmpty(int top) {


return top == -1;
}

int isFull(int top) {


return top == MAX_SIZE - 1;
}

void push(int stack[], int *top, int value) {


if (isFull(*top)) {
printf("Stack overflow! Cannot push %d\n", value);
} else {
*top += 1;
stack[*top] = value;
printf("%d pushed onto the stack\n", value);
}
}

void pop(int stack[], int *top) {


if (isEmpty(*top)) {
printf("Stack underflow! Cannot pop from an empty stack\n");
} else {
printf("%d popped from the stack\n", stack[*top]);
*top -= 1;
}
}

void printStack(int stack[], int top) {


if (isEmpty(top)) {
printf("Stack is empty\n");
} else {
printf("Stack elements: ");
for (int i = 0; i <= top; i++) {
printf("%d ", stack[i]);
}
printf("\n");
}
}

int main() {
int stack[MAX_SIZE];
int top;
int choice;
int value;

initialize(stack, &top);

while (1) {
printf("\nStack Menu:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Print Stack\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &value);
push(stack, &top, value);
break;

case 2:
pop(stack, &top);
break;

case 3:
printStack(stack, top);
break;

case 4:
printf("Exiting program\n");
return 0;

default:
printf("Invalid choice. Please enter a valid option.\n");
}
}

return 0;
}
2. Write a C Program to implement Stack using linked
lists.
#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

struct Node* createNode(int value) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (newNode == NULL) {
printf("Memory allocation failed\n");
exit(EXIT_FAILURE);
}
newNode->data = value;
newNode->next = NULL;
return newNode;
}

void push(struct Node** top, int value) {


struct Node* newNode = createNode(value);
newNode->next = *top;
*top = newNode;
printf("%d pushed onto the stack\n", value);
}

void pop(struct Node** top) {


if (*top == NULL) {
printf("Stack underflow! Cannot pop from an empty stack\n");
} else {
struct Node* temp = *top;
*top = (*top)->next;
printf("%d popped from the stack\n", temp->data);
free(temp);
}
}

void printStack(struct Node* top) {


if (top == NULL) {
printf("Stack is empty\n");
} else {
printf("Stack elements: ");
while (top != NULL) {
printf("%d ", top->data);
top = top->next;
}
printf("\n");
}
}

int main() {
struct Node* top = NULL;
int choice;
int value;

while (1) {
printf("\nStack Menu:\n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Print Stack\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &value);
push(&top, value);
break;

case 2:
pop(&top);
break;

case 3:
printStack(top);
break;

case 4:
printf("Exiting program\n");
return 0;

default:
printf("Invalid choice. Please enter a valid option.\n");
}
}

return 0;
}
3. Write a C Program to implement Queue using arrays.
#include <stdio.h>

#define MAX_SIZE 10

int front = -1, rear = -1;


int queue[MAX_SIZE];

int isFull() {
return ((rear + 1) % MAX_SIZE == front);
}

int isEmpty() {
return (front == -1 && rear == -1);
}

void enqueue(int item) {


if (isFull()) {
printf("Queue overflow! Cannot enqueue %d\n", item);
return;
}
if (isEmpty()) {
front = rear = 0;
} else {
rear = (rear + 1) % MAX_SIZE;
}
queue[rear] = item;
printf("%d enqueued to the queue\n", item);
}

void dequeue() {
if (isEmpty()) {
printf("Queue underflow! Cannot dequeue from an empty queue\n");
return;
}
int item = queue[front];
if (front == rear) {
front = rear = -1;
} else {
front = (front + 1) % MAX_SIZE;
}
printf("%d dequeued from the queue\n", item);
}

void printQueue() {
if (isEmpty()) {
printf("Queue is empty\n");
return;
}
printf("Queue elements: ");
int i = front;
do {
printf("%d ", queue[i]);
i = (i + 1) % MAX_SIZE;
} while (i != (rear + 1) % MAX_SIZE);
printf("\n");
}

int main() {
int choice;
int item;

while (1) {
printf("\nQueue Menu:\n");
printf("1. Enqueue\n");
printf("2. Dequeue\n");
printf("3. Print Queue\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to enqueue: ");
scanf("%d", &item);
enqueue(item);
break;

case 2:
dequeue();
break;

case 3:
printQueue();
break;

case 4:
printf("Exiting program\n");
return 0;

default:
printf("Invalid choice. Please enter a valid option.\n");
}
}

return 0;
}
4. Write a C Program to implement Queue using linked
list.
#include <stdio.h>

typedef struct Node {


int data;
struct Node* next;
} Node;

Node* createNode(int data) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

Node* initializeQueue() {
return NULL;
}

int isEmpty(Node* front) {


return front == NULL;
}

Node* enqueue(Node* rear, int data) {


Node* newNode = createNode(data);

if (isEmpty(rear)) {
return newNode;
} else {
rear->next = newNode;
return newNode;
}
}

Node* dequeue(Node* front) {


if (isEmpty(front)) {
printf("Queue is empty. Cannot dequeue.\n");
return front;
}

Node* temp = front;


front = front->next;
free(temp);

return front;
}

void displayQueue(Node* front) {


if (isEmpty(front)) {
printf("Queue is empty.\n");
return;
}

printf("Queue: ");
while (front != NULL) {
printf("%d ", front->data);
front = front->next;
}
printf("\n");
}

int main() {
Node* front = initializeQueue();
Node* rear = front;

rear = enqueue(rear, 10);


rear = enqueue(rear, 20);
rear = enqueue(rear, 30);

displayQueue(front);

front = dequeue(front);

displayQueue(front);

return 0;
}

5. Write a C Program to create a linked list of 10


elements and do the following :
i. Insert new data element 10 at the beginning.
ii. Insert new data element 15 at the end.
iii. Delete node at the beginning.
iv. Delete node at the end.
v. Delete node at any given position.
#include <stdio.h>

typedef struct Node {


int data;
struct Node* next;
} Node;

Node* createNode(int data) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

Node* initializeList() {
return NULL;
}

Node* insertAtBeginning(Node* head, int data) {


Node* newNode = createNode(data);
newNode->next = head;
return newNode;
}

Node* insertAtEnd(Node* head, int data) {


Node* newNode = createNode(data);

if (head == NULL) {
return newNode;
}

Node* temp = head;


while (temp->next != NULL) {
temp = temp->next;
}

temp->next = newNode;

return head;
}

Node* deleteAtBeginning(Node* head) {


if (head == NULL) {
printf("List is empty. Cannot delete from the beginning.\n");
return head;
}

Node* temp = head;


head = head->next;
free(temp);

return head;
}
Node* deleteAtEnd(Node* head) {
if (head == NULL) {
printf("List is empty. Cannot delete from the end.\n");
return head;
}

if (head->next == NULL) {
free(head);
return NULL;
}

Node* temp = head;


while (temp->next->next != NULL) {
temp = temp->next;
}

free(temp->next);
temp->next = NULL;

return head;
}

Node* deleteAtPosition(Node* head, int position) {


if (head == NULL) {
printf("List is empty. Cannot delete from the specified position.\n");
return head;
}

if (position == 1) {
Node* temp = head;
head = head->next;
free(temp);
return head;
}

Node* temp = head;


for (int i = 1; i < position - 1 && temp != NULL; i++) {
temp = temp->next;
}

if (temp == NULL || temp->next == NULL) {


printf("Invalid position. Cannot delete from the specified position.\n");
return head;
}

Node* toDelete = temp->next;


temp->next = temp->next->next;
free(toDelete);

return head;
}
void displayList(Node* head) {
if (head == NULL) {
printf("List is empty.\n");
return;
}

printf("List: ");
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}

int main() {
Node* head = initializeList();

for (int i = 1; i <= 10; i++) {


head = insertAtEnd(head, i * 5);
}

displayList(head);

head = insertAtBeginning(head, 10);


displayList(head);

head = insertAtEnd(head, 15);


displayList(head);

head = deleteAtBeginning(head);
displayList(head);

head = deleteAtEnd(head);
displayList(head);

int positionToDelete = 3;
head = deleteAtPosition(head, positionToDelete);
displayList(head);

return 0;
}
6. Write a C Program to perform polynomial using
linked list for the following polunomials:
i. Y1=x^3+21x^2+10x+5
ii. Y1=x^4+3x^2=2x+5
#include <stdio.h>

typedef struct Node {


int coefficient;
int exponent;
struct Node* next;
} Node;

Node* createNode(int coefficient, int exponent) {


Node* newNode = (Node*)malloc(sizeof(Node));
newNode->coefficient = coefficient;
newNode->exponent = exponent;
newNode->next = NULL;
return newNode;
}

Node* insertTerm(Node* head, int coefficient, int exponent) {


Node* newNode = createNode(coefficient, exponent);

if (head == NULL || exponent > head->exponent) {


newNode->next = head;
return newNode;
}

Node* temp = head;


while (temp->next != NULL && temp->next->exponent > exponent) {
temp = temp->next;
}

newNode->next = temp->next;
temp->next = newNode;

return head;
}

Node* addPolynomials(Node* poly1, Node* poly2) {


Node* result = NULL;

while (poly1 != NULL || poly2 != NULL) {


int coeff1 = (poly1 != NULL) ? poly1->coefficient : 0;
int coeff2 = (poly2 != NULL) ? poly2->coefficient : 0;
int exp1 = (poly1 != NULL) ? poly1->exponent : INT_MIN;
int exp2 = (poly2 != NULL) ? poly2->exponent : INT_MIN;

int sumCoeff = coeff1 + coeff2;


result = insertTerm(result, sumCoeff, exp1);

if (exp1 == exp2) {
poly1 = poly1->next;
poly2 = poly2->next;
} else if (exp1 > exp2) {
poly1 = poly1->next;
} else {
poly2 = poly2->next;
}
}

return result;
}

Node* subtractPolynomials(Node* poly1, Node* poly2) {


Node* result = NULL;

while (poly1 != NULL || poly2 != NULL) {


int coeff1 = (poly1 != NULL) ? poly1->coefficient : 0;
int coeff2 = (poly2 != NULL) ? poly2->coefficient : 0;
int exp1 = (poly1 != NULL) ? poly1->exponent : INT_MIN;
int exp2 = (poly2 != NULL) ? poly2->exponent : INT_MIN;

int diffCoeff = coeff1 - coeff2;


result = insertTerm(result, diffCoeff, exp1);

if (exp1 == exp2) {
poly1 = poly1->next;
poly2 = poly2->next;
} else if (exp1 > exp2) {
poly1 = poly1->next;
} else {
poly2 = poly2->next;
}
}

return result;
}

Node* multiplyPolynomials(Node* poly1, Node* poly2) {


Node* result = NULL;

while (poly1 != NULL) {


Node* tempPoly2 = poly2;
while (tempPoly2 != NULL) {
int coeff = poly1->coefficient * tempPoly2->coefficient;
int exp = poly1->exponent + tempPoly2->exponent;
result = insertTerm(result, coeff, exp);
tempPoly2 = tempPoly2->next;
}

poly1 = poly1->next;
}

return result;
}

Node* dividePolynomials(Node* poly1, Node* poly2) {


Node* result = NULL;

while (poly1 != NULL && poly1->exponent >= poly2->exponent) {


int coeff = poly1->coefficient / poly2->coefficient;
int exp = poly1->exponent - poly2->exponent;
result = insertTerm(result, coeff, exp);

Node* tempPoly2 = poly2;


while (tempPoly2 != NULL) {
int termCoeff = coeff * tempPoly2->coefficient;
int termExp = exp + tempPoly2->exponent;
poly1 = subtractPolynomials(poly1, insertTerm(NULL, termCoeff, termExp));
tempPoly2 = tempPoly2->next;
}
}

return result;
}

void displayPolynomial(Node* head) {


if (head == NULL) {
printf("Polynomial is empty.\n");
return;
}

printf("Polynomial: ");
while (head != NULL) {
printf("%dx^%d ", head->coefficient, head->exponent);
if (head->next != NULL) {
printf("+ ");
}
head = head->next;
}
printf("\n");
}

int main() {
Node* poly1 = NULL;
Node* poly2 = NULL;
poly1 = insertTerm(poly1, 5, 3);
poly1 = insertTerm(poly1, 21, 2);
poly1 = insertTerm(poly1, 10, 1);
poly1 = insertTerm(poly1, 5, 0);

poly2 = insertTerm(poly2, 1, 4);


poly2 = insertTerm(poly2, 3, 2);
poly2 = insertTerm(poly2, -2, 1);
poly2 = insertTerm(poly2, 5, 0);

displayPolynomial(poly1);
displayPolynomial(poly2);

Node* sumResult = addPolynomials(poly1, poly2);


displayPolynomial(sumResult);

Node* diffResult = subtractPolynomials(poly1, poly2);


displayPolynomial(diffResult);

Node* productResult = multiplyPolynomials(poly1, poly2);


displayPolynomial(productResult);

Node* divideResult = dividePolynomials(poly1, poly2);


displayPolynomial(divideResult);

return 0;
}

7. Write a C Program to create doubly linked list with 5


nodes and perform the following :
i. Insert new node at the beginning .
ii. Insert new node at any given position.
iii. Delete new node at end of list .
iv. Delete node at any given position.
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {


int data;
struct Node* prev;
struct Node* next;
} Node;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}

Node* initializeList() {
return NULL;
}

Node* insertAtBeginning(Node* head, int data) {


Node* newNode = createNode(data);

if (head == NULL) {
return newNode;
}

newNode->next = head;
head->prev = newNode;

return newNode;
}

Node* insertAtPosition(Node* head, int data, int position) {


Node* newNode = createNode(data);

if (position <= 0) {
printf("Invalid position. Cannot insert at position %d.\n", position);
return head;
}

if (head == NULL && position != 1) {


printf("Invalid position. List is empty, cannot insert at position %d.\n", position);
return head;
}

if (position == 1) {
newNode->next = head;
head->prev = newNode;
return newNode;
}

Node* temp = head;


for (int i = 1; i < position - 1 && temp != NULL; i++) {
temp = temp->next;
}

if (temp == NULL) {
printf("Invalid position. Cannot insert at position %d.\n", position);
return head;
}

newNode->next = temp->next;
if (temp->next != NULL) {
temp->next->prev = newNode;
}
newNode->prev = temp;
temp->next = newNode;

return head;
}

Node* deleteAtEnd(Node* head) {


if (head == NULL) {
printf("List is empty. Cannot delete from the end.\n");
return head;
}

if (head->next == NULL) {
free(head);
return NULL;
}

Node* temp = head;


while (temp->next != NULL) {
temp = temp->next;
}

temp->prev->next = NULL;
free(temp);

return head;
}

Node* deleteAtPosition(Node* head, int position) {


if (head == NULL) {
printf("List is empty. Cannot delete from the specified position.\n");
return head;
}

if (position <= 0) {
printf("Invalid position. Cannot delete at position %d.\n", position);
return head;
}

if (position == 1) {
Node* temp = head;
head = head->next;
if (head != NULL) {
head->prev = NULL;
}
free(temp);
return head;
}

Node* temp = head;


for (int i = 1; i < position && temp != NULL; i++) {
temp = temp->next;
}

if (temp == NULL) {
printf("Invalid position. Cannot delete at position %d.\n", position);
return head;
}

temp->prev->next = temp->next;
if (temp->next != NULL) {
temp->next->prev = temp->prev;
}

free(temp);

return head;
}

void displayList(Node* head) {


if (head == NULL) {
printf("List is empty.\n");
return;
}

printf("Doubly Linked List: ");


while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}

int main() {
Node* head = initializeList();

for (int i = 5; i >= 1; i--) {


head = insertAtBeginning(head, i * 10);
}

displayList(head);

head = insertAtBeginning(head, 50);


displayList(head);
head = insertAtPosition(head, 30, 3);
displayList(head);

head = deleteAtEnd(head);
displayList(head);

head = deleteAtPosition(head, 2);


displayList(head);

return 0;
}

8. Write a C Program to perform Operation on Complex


number such as add, subtract ,divide ,multiply .
#include <stdio.h>

typedef struct Complex {


float real;
float imag;
} Complex;

Complex addComplex(Complex num1, Complex num2) {


Complex result;
result.real = num1.real + num2.real;
result.imag = num1.imag + num2.imag;
return result;
}

Complex subtractComplex(Complex num1, Complex num2) {


Complex result;
result.real = num1.real - num2.real;
result.imag = num1.imag - num2.imag;
return result;
}

Complex multiplyComplex(Complex num1, Complex num2) {


Complex result;
result.real = (num1.real * num2.real) - (num1.imag * num2.imag);
result.imag = (num1.real * num2.imag) + (num1.imag * num2.real);
return result;
}

Complex divideComplex(Complex num1, Complex num2) {


Complex result;
float denominator = (num2.real * num2.real) + (num2.imag * num2.imag);
if (denominator != 0) {
result.real = ((num1.real * num2.real) + (num1.imag * num2.imag)) / denominator;
result.imag = ((num1.imag * num2.real) - (num1.real * num2.imag)) / denominator;
} else {
printf("Division by zero is undefined.\n");
}

return result;
}

void displayComplex(Complex num) {


printf("%.2f + %.2fi\n", num.real, num.imag);
}

int main() {
Complex num1, num2, result;

printf("Enter real and imaginary parts for Complex Number 1:\n");


scanf("%f %f", &num1.real, &num1.imag);

printf("Enter real and imaginary parts for Complex Number 2:\n");


scanf("%f %f", &num2.real, &num2.imag);

result = addComplex(num1, num2);


printf("Addition: ");
displayComplex(result);

result = subtractComplex(num1, num2);


printf("Subtraction: ");
displayComplex(result);

result = multiplyComplex(num1, num2);


printf("Multiplication: ");
displayComplex(result);

result = divideComplex(num1, num2);


printf("Division: ");
displayComplex(result);

return 0;
}

1.write a c program to inplement binary tree a


display
the element of binary tree.
Input:
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* createNode(int data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct
TreeNode));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void displayInOrder(struct TreeNode* root) {
if (root != NULL) {
displayInOrder(root->left);
printf("%d ", root->data);
displayInOrder(root->right);
}
}
int main() {struct TreeNode* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
printf("Elements of binary tree (in-order traversal): ");
displayInOrder(root);
printf("\n");
free(root->left->left);
free(root->left->right);
free(root->right);
free(root->left);
free(root);
return 0;
}
2. write a c program to list the elements of binary
tree for
pre order,in order,post order.
Input:
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* createNode(int data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct
TreeNode));if (newNode == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
void displayPreOrder(struct TreeNode* root) {
if (root != NULL) {
printf("%d ", root->data);
displayPreOrder(root->left);
displayPreOrder(root->right);
}
}
void displayInOrder(struct TreeNode* root) {
if (root != NULL) {
displayInOrder(root->left);
printf("%d ", root->data);
displayInOrder(root->right);
}
}
void displayPostOrder(struct TreeNode* root) {
if (root != NULL) {
displayPostOrder(root->left);
displayPostOrder(root->right);
printf("%d ", root->data);
}}
int main() {
struct TreeNode* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
printf("Elements of binary tree (pre-order traversal): ");
displayPreOrder(root);
printf("\n");
#include <stdio.h>
#include
<stdlib.h>
printf("Elements of binary tree (in-order traversal): ");
displayInOrder(root);
printf("\n");
printf("Elements of binary tree (post-order traversal): ");
displayPostOrder(root);
printf("\n");
free(root->left->left);
free(root->left->right);
free(root->right);
free(root->left);
free(root);
return 0;
}
3. write a c program to convert an array of
elements into
binary search tree.
Input:
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* createNode(int data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct
TreeNode));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct TreeNode* insertNode(struct TreeNode* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {
root->left = insertNode(root->left, data);
} else if (data > root->data) {
root->right = insertNode(root->right, data);
}return root;
}
struct TreeNode* arrayToBST(int arr[], int start, int end) {
if (start > end) {
return NULL;
}
int mid = (start + end) / 2;
struct TreeNode* root = createNode(arr[mid]);
root->left = arrayToBST(arr, start, mid - 1);
root->right = arrayToBST(arr, mid + 1, end);
return root;
}
traversal
void displayInOrder(struct TreeNode* root) {
if (root != NULL) {
displayInOrder(root->left);
printf("%d ", root->data);
displayInOrder(root->right);
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = sizeof(arr) / sizeof(arr[0]);
struct TreeNode* root = arrayToBST(arr, 0, n - 1);
printf("Elements of binary search tree (in-order traversal): ");
displayInOrder(root);
printf("\n");
free(root);
return 0;}
4.write a c program to perform addition,deletion of
elements in binary search tree at different
position.
Input:
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* createNode(int data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct
TreeNode));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
struct TreeNode* insertNode(struct TreeNode* root, int data) {
if (root == NULL) {
return createNode(data);
}
if (data < root->data) {root->left = insertNode(root->left, data);
} else if (data > root->data) {
root->right = insertNode(root->right, data);
}
return root;
}
struct TreeNode* findMinNode(struct TreeNode* node) {
struct TreeNode* current = node;
while (current && current->left != NULL) {
current = current->left;
}
return current;
}
struct TreeNode* deleteNode(struct TreeNode* root, int data) {
if (root == NULL) {
return root;
}
if (data < root->data) {
root->left = deleteNode(root->left, data);
} else if (data > root->data) {
root->right = deleteNode(root->right, data);
} else {
if (root->left == NULL) {
struct TreeNode* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct TreeNode* temp = root->left;
free(root);return temp;
}
struct TreeNode* temp = findMinNode(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}
void displayInOrder(struct TreeNode* root) {
if (root != NULL) {
displayInOrder(root->left);
printf("%d ", root->data);
displayInOrder(root->right);
}
}
int main() {
struct TreeNode* root = NULL;
root = insertNode(root, 50);
root = insertNode(root, 30);
root = insertNode(root, 20);
root = insertNode(root, 40);
root = insertNode(root, 70);
root = insertNode(root, 60);
root = insertNode(root, 80);
printf("Elements of binary search tree (in-order traversal): ");
displayInOrder(root);
printf("\n");
root = deleteNode(root, 20); // Delete node with value 20
printf("After deleting 20: ");displayInOrder(root);
printf("\n");
root = deleteNode(root, 30); // Delete node with value 30
printf("After deleting 30: ");
displayInOrder(root);
printf("\n");
root = deleteNode(root, 50); // Delete node with value 50
printf("After deleting 50: ");
displayInOrder(root);
printf("\n");
free(root->left);
free(root->right);
free(root);
return 0;
}
5.write a c program to convert arithmetic
expression into
express tree.
Input:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
struct TreeNode {
char data;struct TreeNode* left;
struct TreeNode* right;
};
struct TreeNode* createNode(char data) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct
TreeNode));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
int isOperator(char c) {
return (c == '+' || c == '-' || c == '*' || c == '/');
}
struct TreeNode* constructExpressionTree(char expression[], int
start, int end) {
if (start > end)
return NULL;
struct TreeNode* root = NULL;
int currentPos = -1;
int priority = 0;
int bracketsCount = 0;
for (int i = start; i <= end; ++i) {
if (expression[i] == '(')
bracketsCount++;
else if (expression[i] == ')')
bracketsCount--;if (isOperator(expression[i]) && bracketsCount ==
0) {
int currentPriority = 3;
switch (expression[i]) {
case '+':
case '-':
currentPriority = 1;
break;
case '*':
case '/':
currentPriority = 2;
break;
}
if (currentPriority <= priority || currentPos == -1) {
priority = currentPriority;
currentPos = i;
}
}
}
if (currentPos == -1) {
if (expression[start] == '(' && expression[end] == ')')
return constructExpressionTree(expression, start + 1, end - 1);
else
return createNode(expression[start]);
}
root = createNode(expression[currentPos]);
root->left = constructExpressionTree(expression, start, currentPos -
1);
root->right = constructExpressionTree(expression, currentPos + 1,
end);
return root;
}void displayInfix(struct TreeNode* root) {
if (root != NULL) {
if (isOperator(root->data))
printf("(");
displayInfix(root->left);
printf("%c ", root->data);
displayInfix(root->right);
if (isOperator(root->data))
printf(")");
}
}
void displayPrefix(struct TreeNode* root) {
if (root != NULL) {
printf("%c ", root->data);
displayPrefix(root->left);
displayPrefix(root->right);
}
}
void displayPostfix(struct TreeNode* root) {
if (root != NULL) {
displayPostfix(root->left);
displayPostfix(root->right);
printf("%c ", root->data);
}
}
int main() {
char expression[100];
printf("Enter an arithmetic expression in infix notation: ");
fgets(expression, sizeof(expression),
stdin);expression[strcspn(expression, "\n")] = 0;
struct TreeNode* root = constructExpressionTree(expression, 0,
strlen(expression) - 1);
printf("Infix notation: ");
displayInfix(root);
printf("\n");
printf("Prefix notation: ");
displayPrefix(root);
printf("\n");
printf("Postfix notation: ");
displayPostfix(root);
printf("\n");
free(root);
return 0;
}

6.write a c program to search an element using


linear
search and binary search.
Input:
#include <stdio.h>
int linearSearch(int arr[], int n, int x) {
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
return i; // Return index if element found
}
}return -1; // Return -1 if element not found
}
int binarySearch(int arr[], int left, int right, int x) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == x) {
return mid; // Return index if element found
}
if (arr[mid] < x) {
left = mid + 1; // Search in the right half
} else {
right = mid - 1; // Search in the left half
}
}
return -1; // Return -1 if element not found
}
int main() {
int n;
printf("Enter the number of elements in the array: ");
scanf("%d", &n);
int arr[n];
printf("Enter the elements of the array in sorted order:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
int searchElement;
printf("Enter the element to search: ");
scanf("%d", &searchElement);
int linearIndex = linearSearch(arr, n, searchElement);if (linearIndex !
= -1) {
printf("Linear Search: Element %d found at index %d\n",
searchElement, linearIndex);
} else {
printf("Linear Search: Element %d not found\n", searchElement);
}
int binaryIndex = binarySearch(arr, 0, n - 1, searchElement);
if (binaryIndex != -1) {
printf("Binary Search: Element %d found at index %d\n",
searchElement, binaryIndex);
} else {
printf("Binary Search: Element %d not found\n", searchElement);
}
return 0;
}
7.write a c program to sort the given element using
seletion sort.
Input:
#include<stdio.h>
void swap(int *a,int *b){
int temp;
temp=*a;
*a=*b;
*b=temp;
}
int main(){
int n,i,j,min,arr[]={8,6,3,2,1,5,7};
n=sizeof(arr)/sizeof(arr[0]);
for(i=0;i<n-1;i++){
min=i;
for(j=i+1;j<n;j++){
if(arr[j]<arr[min]){
min=j;
}
}
if(min!=i)
swap(&arr[i],&arr[min]);
}
for(i=0;i<n;i++){
printf("%d ",arr[i]);
}
}

8.write a c program to sort the given element using


bubble sort.Input:
#include <stdio.h>
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] with arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {66,32,54,25,12};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Array before sorting: ");
printArray(arr, n);
bubbleSort(arr, n);
printf("Array after sorting: ");
printArray(arr, n);
return 0;}

9.write a c program to sort the given element using


insertion sort.
Input:
#include <stdio.h>
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {88,63,23,12,67};
int n = sizeof(arr) / sizeof(arr[0]);printf("Array before sorting: ");
printArray(arr, n);
insertionSort(arr, n);
printf("Array after sorting: ");
printArray(arr, n);
return 0;
}
10. write a c program to sort the given element
using
merge sort.
Input:
#include <stdio.h>
void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;
int L[n1], R[n2];
for (int i = 0; i < n1; i++) {
L[i] = arr[left + i];
}
for (int j = 0; j < n2; j++) {
R[j] = arr[mid + 1 + j];
}
int 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);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);}
printf("\n");
}
int main() {
int arr[] = {45,77,32,20,56};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Array before sorting: ");
printArray(arr, n);
mergeSort(arr, 0, n - 1);
printf("Array after sorting: ");
printArray(arr, n);
return 0;
}

Radix sort
#include <stdio.h>

// Function to find the maximum number in an array


int getMax(int arr[], int n) {
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max)
max = arr[i];
}
return max;
}

// Function to perform counting sort based on digit represented by exp


void countingSort(int arr[], int n, int exp) {
int output[n]; // Output array
int count[10] = {0}; // Count array to store count of digits
// Count the occurrences of digits
for (int i = 0; i < n; i++)
count[(arr[i] / exp) % 10]++;

// Change count[i] so that count[i] contains actual position of this digit in output[]
for (int i = 1; i < 10; i++)
count[i] += count[i - 1];

// Build the output array


for (int i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % 10] - 1] = arr[i];
count[(arr[i] / exp) % 10]--;
}

// Copy the output array to arr[], so that arr[] now contains sorted numbers
for (int i = 0; i < n; i++)
arr[i] = output[i];
}

// Function to implement Radix Sort


void radixSort(int arr[], int n) {
// Find the maximum number to know number of digits
int max = getMax(arr, n);

// Do counting sort for every digit. Note that instead of passing digit number, exp is passed. exp is 10^i where i is the
current digit number
for (int exp = 1; max / exp > 0; exp *= 10)
countingSort(arr, n, exp);
}

// Function to print an array


void printArray(int arr[], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Example usage
int main() {
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
printArray(arr, n);
radixSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
Quick sort

#include <stdio.h>

// Function to swap two elements in an array


void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}

// Function to partition the array and return the pivot index


int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Select the last element as the pivot
int i = low - 1; // Index of smaller element

for (int j = low; j < high; j++) {


// If current element is smaller than or equal to pivot
if (arr[j] <= pivot) {
i++; // Increment index of smaller element
swap(&arr[i], &arr[j]); // Swap the elements
}
}
swap(&arr[i + 1], &arr[high]); // Swap the pivot element with the element at (i + 1)
return (i + 1); // Return the partitioning index
}

// Function to implement Quick Sort algorithm


void quickSort(int arr[], int low, int high) {
if (low < high) {
// Partition the array and get the pivot index
int pivotIndex = partition(arr, low, high);

// Recursively sort elements before and after the pivot


quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}

// Function to print an array


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Example usage
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
printArray(arr, n);
quickSort(arr, 0, n - 1);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}

Shell sort
// C++ implementation of Shell Sort
#include <iostream>
using namespace std;

/* function to sort arr using shellSort */


int shellSort(int arr[], int n)
{
// Start with a big gap, then reduce the gap
for (int gap = n/2; gap > 0; gap /= 2)
{
// Do a gapped insertion sort for this gap size.
// The first gap elements a[0..gap-1] are already in gapped order
// keep adding one more element until the entire array is
// gap sorted
for (int i = gap; i < n; i += 1)
{
// add a[i] to the elements that have been gap sorted
// save a[i] in temp and make a hole at position i
int temp = arr[i];

// shift earlier gap-sorted elements up until the correct


// location for a[i] is found
int j;
for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
arr[j] = arr[j - gap];

// put temp (the original a[i]) in its correct location


arr[j] = temp;
}
}
return 0;
}

void printArray(int arr[], int n)


{
for (int i=0; i<n; i++)
cout << arr[i] << " ";
}

int main()
{
int arr[] = {12, 34, 54, 2, 3}, i;
int n = sizeof(arr)/sizeof(arr[0]);

cout << "Array before sorting: \n";


printArray(arr, n);

shellSort(arr, n);
cout << "\nArray after sorting: \n";
printArray(arr, n);

return 0;
}
Q1) Write a c program to implement simple hash table using arrays with
following keys.
0, 1, 4, 16, 9
The hash function is f(x) = x mod 10;
Ans) #include <stdio.h>
#include <stdlib.h>

#define SIZE 10

struct Node {
int key;
int value;
struct Node *next;
};

struct Node *hashTable[SIZE];

int hashFunc(int key) {


return key % SIZE;
}

void insert(int key, int value) {


int index = hashFunc(key);
struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->key = key;
newNode->value = value;
newNode->next = NULL;

if (hashTable[index] == NULL) {
hashTable[index] = newNode;
} else {
struct Node *current = hashTable[index];
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}

int search(int key) {


int index = hashFunc(key);
struct Node *current = hashTable[index];
while (current != NULL) {
if (current->key == key) {
return current->value;
}
current = current->next;
}
return -1;
}

int main() {
for (int i = 0; i < SIZE; i++) {
hashTable[i] = NULL;
}

insert(0, 10);
insert(1, 20);
insert(4, 30);
insert(16, 40);
insert(9, 50);

int keys[] = {0, 1, 4, 16, 9};


for (int i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {
int key = keys[i];
int value = search(key);
if (value != -1) {
printf("Key %d found with value %d\n", key, value);
} else {
printf("Key %d not found\n", key);
}
}

return 0;
}

Output:
Key 0 found with value 10
Key 1 found with value 20
Key 4 found with value 30
Key 16 found with value 40
Key 9 found with value 50

Q2) Write a c program to implement simple hash table using arrays with
following keys.0, 1, 4, 9, 16, 25, 36, 49, 64, 81The hash function is f(x) = x
mod 10;
Ans)
#include <stdio.h>
#include <stdlib.h>
#define SIZE 10

struct Node{
int key;
int value;
struct Node *next;
};

struct Node *hashTable[SIZE];

int hashFunc(int key) {


return key%SIZE;
}

void insert(int key, int value){


int index=hashFunc(key);
struct Node *newNode=(struct Node *)malloc(sizeof(struct Node));
newNode->key=key;
newNode->value=value;
newNode->next=NULL;

if (hashTable[index]==NULL) {
hashTable[index]=newNode;
} else {
struct Node *current=hashTable[index];
while(current->next!=NULL){
current=current->next;
}
current->next=newNode;
}
}

int search(int key){


int index=hashFunc(key);
struct Node *current=hashTable[index];
while (current!=NULL) {
if (current->key==key) {
return current->value;
}
current=current->next;
}
return -1;
}

int main() {
for (int i=0;i<SIZE;i++) {
hashTable[i]=NULL;
}
int keys[]={0,1,4,9,16,25,36,49,64,81};
for (int i=0;i<sizeof(keys)/sizeof(keys[0]);i++) {
insert(keys[i],keys[i]*keys[i]);
}
for (int i=0;i<sizeof(keys)/sizeof(keys[0]);i++){
int key=keys[i];
int value=search(key);
if (value!=-1){
printf("Key %d found with value %d\n", key, value);
}
else{
printf("Key %d not found\n", key);
}
}

return 0;
}

Output:
Key 0 found with value 0
Key 1 found with value 1
Key 4 found with value 16
Key 9 found with value 81
Key 16 found with value 256
Key 25 found with value 625
Key 36 found with value 1296
Key 49 found with value 2401
Key 64 found with value 4096
Key 81 found with value 6561
Q3) Write a c program to implement heap sort for sorting the following
numbers 2, 5, 3, 7, 4, 9, 20, 30, 45, 50.By generating min
heap and max heap.
Ans)
#include <stdio.h>

void swap(int *a, int *b) {


int temp = *a;
*a = *b;
*b = temp;
}

void maxHeapify(int arr[], int n, int i) {


int largest = i;
int left = 2*i + 1;
int right = 2*i + 2;

if (left < n && arr[left] > arr[largest])


largest = left;

if (right < n && arr[right] > arr[largest])


largest = right;

if (largest != i) {
swap(&arr[i], &arr[largest]);
maxHeapify(arr, n, largest);
}
}

void buildMaxHeap(int arr[], int n) {


for (int i = n/2 - 1; i >= 0; i--) {
maxHeapify(arr, n, i);
}
}

void heapSortMaxHeap(int arr[], int n) {


buildMaxHeap(arr, n);

for (int i = n - 1; i > 0; i--) {


swap(&arr[0], &arr[i]);
maxHeapify(arr, i, 0);
}
}

void minHeapify(int arr[], int n, int i) {


int smallest = i;
int left = 2*i + 1;
int right = 2*i + 2;

if (left < n && arr[left] < arr[smallest])


smallest = left;

if (right < n && arr[right] < arr[smallest])


smallest = right;

if (smallest != i) {
swap(&arr[i], &arr[smallest]);
minHeapify(arr, n, smallest);
}
}

void buildMinHeap(int arr[], int n) {


for (int i = n/2 - 1; i >= 0; i--) {
minHeapify(arr, n, i);
}
}

void heapSortMinHeap(int arr[], int n) {


buildMinHeap(arr, n);

for (int i = n - 1; i > 0; i--) {


swap(&arr[0], &arr[i]);
minHeapify(arr, i, 0);
}
}

int main() {
int arr[] = {2, 5, 3, 7, 4, 9, 20, 30, 45, 50};
int n = sizeof(arr) / sizeof(arr[0]);

heapSortMaxHeap(arr, n);
printf("Sorted array using max heap:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

heapSortMinHeap(arr, n);
printf("Sorted array using min heap:\n");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");

return 0;
}

Output:
Sorted array using max heap:
2 3 4 5 7 9 20 30 45 50
Sorted array using min heap:
50 45 30 20 9 7 5 4 3 2

You might also like