[go: up one dir, main page]

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

DS File

The document contains multiple C programs that perform various operations on arrays and strings, including insertion, deletion, traversal, sorting, searching, and handling sparse matrices. Each program is menu-driven, allowing users to choose specific operations such as bubble sort, linear search, and matrix conversion to tuple form. The programs demonstrate fundamental concepts in data structures and algorithms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views119 pages

DS File

The document contains multiple C programs that perform various operations on arrays and strings, including insertion, deletion, traversal, sorting, searching, and handling sparse matrices. Each program is menu-driven, allowing users to choose specific operations such as bubble sort, linear search, and matrix conversion to tuple form. The programs demonstrate fundamental concepts in data structures and algorithms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 119

PROGRAM-1

/* WAP to implement following operation on one dimensional array (i)


Insertion in sorted and unsorted arrays (ii) Deletion from sorted and
unsorted arrays (iii) Traversal (iv) Reverse */

#include <stdio.h>
int arr[100], size = 0;
void sort_array() {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void insert_sorted(int val) {
sort_array();
int i;
for (i = size - 1; i >= 0 && arr[i] > val; i--)
arr[i + 1] = arr[i];
arr[i + 1] = val;
size++;
}
void insert_unsorted(int pos, int val) {
for (int i = size; i > pos; i--)
arr[i] = arr[i - 1];
arr[pos] = val;
size++;
}
void delete_sorted(int val) {
sort_array();
int pos = -1;
for (int i = 0; i < size; i++) {
if (arr[i] == val) {
pos = i;
break;
}
}
if (pos == -1) return;
for (int i = pos; i < size - 1; i++)
arr[i] = arr[i + 1];
size--;
}
void delete_unsorted(int val) {
int pos = -1;
for (int i = 0; i < size; i++) {
if (arr[i] == val) {
pos = i;
break;
}
}
if (pos == -1) return;
arr[pos] = arr[size - 1]; // Replace with last element
size--;
}
void traverse() {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
void reverse() {
for (int i = 0, j = size - 1; i < j; i++, j--) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}

int main() {
int choice, val, pos;
printf("Enter number of elements: ");
scanf("%d", &size);
printf("Enter elements: ");
for (int i = 0; i < size; i++)
scanf("%d", &arr[i]);
while (1) {
printf("\n1. Insert in Sorted\n2. Insert in Unsorted\n3. Delete from Sorted\n4. Delete from
Unsorted\n5. Traverse\n6. Reverse\n7. Exit\nChoose: ");
scanf("%d", &choice);
switch (choice) {
case 1:
sort_array();
printf("Enter value to insert: ");
scanf("%d", &val);
insert_sorted(val);
break;
case 2:
printf("Enter position and value: ");
scanf("%d %d", &pos, &val);
insert_unsorted(pos, val);
break;
case 3:
sort_array();
printf("Enter value to delete: ");
scanf("%d", &val);
delete_sorted(val);
break;
case 4:
printf("Enter value to delete: ");
scanf("%d", &val);
delete_unsorted(val);
break;
case 5:
traverse();
break;
case 6:
reverse();
break;
case 7:
return 0;
default:
printf("Invalid choice\n");
}
}
}
Output:-
PROGRAM-2
/*WAP to perform following string related function (user defined) on an
array
i. Finding string length ii. Concatenation of two strings iii. Comparing two
string iv. Copy one string to another*/

#include <stdio.h>
char str1[50], str2[50], str3[100];
int get_length(char str[]) {
int i = 0;
while (str[i] != '\0' && str[i] != '\n') {
i++;
}
return i;
}

void concat_strings(char s1[], char s2[]) {


int i = 0, j = 0;
while (s1[i] != '\0' && s1[i] != '\n') {
str3[j++] = s1[i++];
}
i = 0;
while (s2[i] != '\0' && s2[i] != '\n') {
str3[j++] = s2[i++];
}
str3[j] = '\0';
}

int compare_strings(char s1[], char s2[]) {


int i = 0;
while (s1[i] != '\0' && s1[i] != '\n' && s2[i] != '\0' && s2[i] != '\n') {
if (s1[i] != s2[i])
return 0;
i++;
}
return (s1[i] == s2[i]);
}
void copy_string(char s1[], char s2[]) {
int i = 0;
while (s1[i] != '\0' && s1[i] != '\n') {
s2[i] = s1[i];
i++;
}
s2[i] = '\0';
}

int main() {
int choice;
printf("Choose an operation:\n");
printf("1. Get String Length\n");
printf("2. Concatenate Two Strings\n");
printf("3. Compare Two Strings\n");
printf("4. Copy a String\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar();

switch (choice) {
case 1:
printf("Enter the string: ");
fgets(str1, sizeof(str1), stdin);
printf("Length of string: %d\n", get_length(str1));
break;
case 2:
printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin);
printf("Enter second string: ");
fgets(str2, sizeof(str2), stdin);
concat_strings(str1, str2);
printf("Concatenated String: %s\n", str3);
break;
case 3:
printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin);
printf("Enter second string: ");
fgets(str2, sizeof(str2), stdin);
if (compare_strings(str1, str2))
printf("Strings are the same.\n");
else
printf("Strings are different.\n");
break;
case 4:
printf("Enter the string: ");
fgets(str1, sizeof(str1), stdin);
copy_string(str1, str2);
printf("Copied String: %s\n", str2);
break;
default:
printf("Invalid choice.\n");
}
return 0;
}

Output:-
PROGRAM-3
/*WAP to perform sorting in array(Menu Driven) :-

i. Bubble sort ii. Selection sort iii. Insertion sort iv. merge sort v. Merging
two sorted array*/

#include <stdio.h>

void bubble_sort(int arr[], int n);


void selection_sort(int arr[], int n);
void insertion_sort(int arr[], int n);
void merge_sort(int arr[], int l, int r);
void merge(int arr[], int l, int m, int r);
void merge_arrays(int a[], int n1, int b[], int n2, int res[]);
void input_array(int arr[], int *n);
void display_array(int arr[], int n);

int main() {
int arr[100], n, choice;

printf("Choose an operation:\n");
printf("1. Bubble Sort\n2. Selection Sort\n3. Insertion Sort\n4. Merge Sort\n5. Merge Two Sorted
Arrays\n");
printf("Enter your choice: ");
scanf("%d", &choice);

if (choice >= 1 && choice <= 4) {


input_array(arr, &n);
}

switch (choice) {
case 1:
bubble_sort(arr, n);
printf("Sorted Array (Bubble Sort):\n");
display_array(arr, n);
break;
case 2:
selection_sort(arr, n);
printf("Sorted Array (Selection Sort):\n");
display_array(arr, n);
break;
case 3:
insertion_sort(arr, n);
printf("Sorted Array (Insertion Sort):\n");
display_array(arr, n);
break;
case 4:
merge_sort(arr, 0, n - 1);
printf("Sorted Array (Merge Sort):\n");
display_array(arr, n);
break;
case 5: {
int a[50], b[50], c[100], n1, n2;
printf("Enter first sorted array:\n");
input_array(a, &n1);
printf("Enter second sorted array:\n");
input_array(b, &n2);
merge_arrays(a, n1, b, n2, c);
printf("Merged Sorted Array:\n");
display_array(c, n1 + n2);
break;
}
default:
printf("Invalid choice!\n");
}

return 0;
}

void input_array(int arr[], int *n) {


printf("Enter number of elements: ");
scanf("%d", n);
printf("Enter elements:\n");
for (int i = 0; i < *n; i++) {
scanf("%d", &arr[i]);
}
}

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


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

void bubble_sort(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]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

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


for (int i = 0; i < n - 1; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min])
min = j;
}
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}

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


for (int i = 1; i < n; i++) {
int key = arr[i], j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}

void merge(int arr[], int l, int m, int r) {


int i = l, j = m + 1, k = 0, temp[r - l + 1];
while (i <= m && j <= r) {
temp[k++] = (arr[i] < arr[j]) ? arr[i++] : arr[j++];
}
while (i <= m) temp[k++] = arr[i++];
while (j <= r) temp[k++] = arr[j++];
for (i = l, k = 0; i <= r; i++, k++) arr[i] = temp[k];
}

void merge_sort(int arr[], int l, int r) {


if (l < r) {
int m = (l + r) / 2;
merge_sort(arr, l, m);
merge_sort(arr, m + 1, r);
merge(arr, l, m, r);
}
}

void merge_arrays(int a[], int n1, int b[], int n2, int res[]) {
int i = 0, j = 0, k = 0;
while (i < n1 && j < n2) {
res[k++] = (a[i] < b[j]) ? a[i++] : b[j++];
}
while (i < n1) res[k++] = a[i++];
while (j < n2) res[k++] = b[j++];
}
Output:-
PROGRAM-4
/*WAP to perform searching in array(Menu Driven) :-
i. Linear search ii. Binary Search*/

#include <stdio.h>

void input();
int search();
void linear();
void binary();

int arr[100], n;

int main() {
int choice;
printf("1. Linear Search\n2. Binary Search\nEnter choice: ");
scanf("%d", &choice);

input();

if (choice == 1) linear();
else if (choice == 2) binary();
else printf("Invalid choice\n");

return 0;
}

void input() {
printf("Enter number of elements: ");
scanf("%d", &n);

printf("Enter elements:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
}

int search() {
int ele;
printf("Enter element to search: ");
scanf("%d", &ele);
return ele;
}

void linear() {
int ele = search(), found = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == ele) {
found = 1;
printf("Element found at index %d\n", i);
break;
}
}
if (!found) printf("Element not found\n");
}

void binary() {
int ele = search(), low = 0, high = n - 1, mid, found = 0;

while (low <= high) {


mid = (low + high) / 2;
if (arr[mid] == ele) {
found = 1;
printf("Element found at index %d\n", mid);
break;
}
else if (arr[mid] > ele) high = mid - 1;
else low = mid + 1;
}

if (!found) printf("Element not found\n");


}

Output:-
PROGRAM-5
/* WAP to accept a matrix from user and find out whether matrix is sparse
or not and convert into triplex matrix or tuple form */

#include <stdio.h>

void to_tuple(int r, int c, int nz, int mat[r][c], int tuple[][3]);

int main() {
int r, c, nz = 0;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);

int mat[r][c];
printf("Enter elements:\n");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
scanf("%d", &mat[i][j]);
if (mat[i][j] != 0) nz++;
}
}

int total = r * c;
if (total - nz >= total / 2) {
printf("\nThe matrix is a sparse matrix.\n");
int tuple[nz + 1][3];
to_tuple(r, c, nz, mat, tuple);
printf("Tuple form:\n");
printf("row\tcol\tval\n");
for (int i = 0; i <= nz; i++)
printf("%d\t %d\t %d\n", tuple[i][0], tuple[i][1], tuple[i][2]);
} else {
printf("The matrix is not a sparse matrix.\n");
}
return 0;
}

void to_tuple(int r, int c, int nz, int mat[r][c], int tuple[][3]) {


tuple[0][0] = r;
tuple[0][1] = c;
tuple[0][2] = nz;

int k = 1;
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
if (mat[i][j] != 0) {
tuple[k][0] = i;
tuple[k][1] = j;
tuple[k][2] = mat[i][j];
k++;
}
}
}
}

Output:-
PROGRAM-6
/* WAP to display the sparse matrix in the following way(Menu Driven) :-
i. Upper triangular matrix ii. Lower triangular matrix iii. Diagonal
matrix*/

#include <stdio.h>

void lower(int r, int c, int mat[r][c]);


void upper(int r, int c, int mat[r][c]);
void diagonal(int r, int c, int mat[r][c]);

int main() {
int r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);

int mat[r][c];
printf("Enter elements:\n");
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
scanf("%d", &mat[i][j]);

int choice;
printf("\n1 - Lower Triangular\n2 - Upper Triangular\n3 - Diagonal\nEnter choice: ");
scanf("%d", &choice);

switch (choice) {
case 1: lower(r, c, mat); break;
case 2: upper(r, c, mat); break;
case 3: diagonal(r, c, mat); break;
default: printf("Invalid choice\n");
}
return 0;
}

void lower(int r, int c, int mat[r][c]) {


printf("Lower Triangular Matrix:\n");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++)
printf(i < j ? "0 " : "%d ", mat[i][j]);
printf("\n");
}
}

void upper(int r, int c, int mat[r][c]) {


printf("Upper Triangular Matrix:\n");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++)
printf(i > j ? "0 " : "%d ", mat[i][j]);
printf("\n");
}
}

void diagonal(int r, int c, int mat[r][c]) {


printf("Diagonal Matrix:\n");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++)
printf(i == j ? "%d " : "0 ", mat[i][j]);
printf("\n");
}
}

Output:-


PROGRAM-7
/* WAP to perform the following operations on sparse matrix(Menu
Driven:
i. Transpose of sparse matrix ii. Add two sparse matrices iii. Multiply two
sparse matrices*/

#include <stdio.h>

#define MAX 10

void convertToTuple(int normal[][MAX], int rows, int cols, int tuple[][3]);


void inputNormalMatrix(int mat[][MAX], int rows, int cols);
void printTuple(int tuple[][3]);
void transpose(int matrix[][3]);
void add(int mat1[][3], int mat2[][3], int res[][3]);
void multiply(int mat1[][3], int mat2[][3], int res[][3]);

int main() {
int rows, cols, choice;

printf("Enter rows and columns of the matrix: ");


scanf("%d %d", &rows, &cols);

int normal[MAX][MAX], tuple[MAX][3];

printf("Enter elements of the matrix:\n");


inputNormalMatrix(normal, rows, cols);

convertToTuple(normal, rows, cols, tuple);


printf("Sparse Matrix in Tuple Form:\n");
printTuple(tuple);

printf("\nChoose an operation:\n1 - Transpose\n2 - Addition\n3 - Multiplication\nEnter choice: ");


scanf("%d", &choice);

int mat2[MAX][3], res[MAX][3];

if (choice == 1) {
transpose(tuple);
}
else if (choice == 2) {
printf("Enter second matrix:\n");
inputNormalMatrix(normal, rows, cols);
convertToTuple(normal, rows, cols, mat2);
add(tuple, mat2, res);
}
else if (choice == 3) {
int rows2, cols2;
printf("Enter rows and columns of the second matrix: ");
scanf("%d %d", &rows2, &cols2);

if (cols != rows2) {
printf("Multiplication not possible.\n");
return 0;
}

printf("Enter elements of the second matrix:\n");


inputNormalMatrix(normal, rows2, cols2);
convertToTuple(normal, rows2, cols2, mat2);
multiply(tuple, mat2, res);
}
else {
printf("Invalid choice.\n");
}

return 0;
}

void inputNormalMatrix(int mat[][MAX], int rows, int cols) {


for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &mat[i][j]);
}
}
}

void convertToTuple(int normal[][MAX], int rows, int cols, int tuple[][3]) {


int k = 1;
tuple[0][0] = rows;
tuple[0][1] = cols;
tuple[0][2] = 0;

for (int i = 0; i < rows; i++) {


for (int j = 0; j < cols; j++) {
if (normal[i][j] != 0) {
tuple[k][0] = i;
tuple[k][1] = j;
tuple[k][2] = normal[i][j];
k++;
}
}
}

tuple[0][2] = k - 1;
}

void printTuple(int tuple[][3]) {


printf("row\tcol\tval\n");
for (int i = 0; i <= tuple[0][2]; i++) {
printf("%d\t%d\t%d\n", tuple[i][0], tuple[i][1], tuple[i][2]);
}
}

void transpose(int matrix[][3]) {


int res[MAX][3], k = 1;
res[0][0] = matrix[0][1];
res[0][1] = matrix[0][0];
res[0][2] = matrix[0][2];

for (int i = 0; i < matrix[0][1]; i++) {


for (int j = 1; j <= matrix[0][2]; j++) {
if (matrix[j][1] == i) {
res[k][0] = matrix[j][1];
res[k][1] = matrix[j][0];
res[k][2] = matrix[j][2];
k++;
}
}
}

printf("Transpose:\n");
printTuple(res);
}

void add(int mat1[][3], int mat2[][3], int res[][3]) {


if (mat1[0][0] != mat2[0][0] || mat1[0][1] != mat2[0][1]) {
printf("Addition not possible.\n");
return;
}

int i = 1, j = 1, k = 1;
res[0][0] = mat1[0][0];
res[0][1] = mat1[0][1];

while (i <= mat1[0][2] && j <= mat2[0][2]) {


if (mat1[i][0] < mat2[j][0] || (mat1[i][0] == mat2[j][0] && mat1[i][1] < mat2[j][1])) {
res[k][0] = mat1[i][0];
res[k][1] = mat1[i][1];
res[k][2] = mat1[i][2];
i++;
} else if (mat2[j][0] < mat1[i][0] || (mat2[j][0] == mat1[i][0] && mat2[j][1] < mat1[i][1])) {
res[k][0] = mat2[j][0];
res[k][1] = mat2[j][1];
res[k][2] = mat2[j][2];
j++;
} else {
res[k][0] = mat1[i][0];
res[k][1] = mat1[i][1];
res[k][2] = mat1[i][2] + mat2[j][2];
i++; j++;
}
k++;
}

while (i <= mat1[0][2]) {


res[k][0] = mat1[i][0];
res[k][1] = mat1[i][1];
res[k][2] = mat1[i][2];
i++; k++;
}

while (j <= mat2[0][2]) {


res[k][0] = mat2[j][0];
res[k][1] = mat2[j][1];
res[k][2] = mat2[j][2];
j++; k++;
}

res[0][2] = k - 1;
printf("Resultant Matrix (Addition):\n");
printTuple(res);
}

void multiply(int mat1[][3], int mat2[][3], int res[][3]) {


if (mat1[0][1] != mat2[0][0]) {
printf("Multiplication not possible.\n");
return;
}

int temp[MAX][MAX] = {0};

for (int i = 1; i <= mat1[0][2]; i++) {


for (int j = 1; j <= mat2[0][2]; j++) {
if (mat1[i][1] == mat2[j][0]) {
temp[mat1[i][0]][mat2[j][1]] += mat1[i][2] * mat2[j][2];
}
}
}

int k = 1;
res[0][0] = mat1[0][0];
res[0][1] = mat2[0][1];

for (int i = 0; i < res[0][0]; i++) {


for (int j = 0; j < res[0][1]; j++) {
if (temp[i][j] != 0) {
res[k][0] = i;
res[k][1] = j;
res[k][2] = temp[i][j];
k++;
}
}
}

res[0][2] = k - 1;
printf("Resultant Matrix (Multiplication):\n");
printTuple(res);
}
Output:-
PROGRAM-8
/* WAP to do the following operations on Singly linked list-
i. Create a list ii. Traverse a list(forward/backward) iii. Reversal of a list*/

#include <stdio.h>
#include <stdlib.h>

struct node {
int info;
struct node* next;
} *first = NULL;

void createList(int n) {
struct node *newNode, *last = NULL;
for (int i = 1; i <= n; i++) {
newNode = (struct node*)malloc(sizeof(struct node));
printf("Enter Node %d info: ", i);
scanf("%d", &newNode->info);
newNode->next = NULL;

if (first == NULL)
first = last = newNode;
else {
last->next = newNode;
last = newNode;
}
}
}

void displayForward() {
struct node *temp = first;
if (!temp) {
printf("List is empty.\n");
return;
}
printf("Forward List: \n");
while (temp) {
printf("%d -> ", temp->info);
temp = temp->next;
}
printf("NULL\n");
}

void displayBackward(struct node *temp) {


if (temp == NULL) return;
displayBackward(temp->next);
printf("%d <- ", temp->info);
}

void reverseList() {
struct node *prev = NULL, *current = first, *next = NULL;
while (current) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
first = prev;
}

int main() {
int choice, n;
while (1) {
printf("\nMenu:\n");
printf("1. Create List\n");
printf("2. Display List (Forward)\n");
printf("3. Display List (Backward)\n");
printf("4. Reverse List\n");
printf("5. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
if (first != NULL) {
printf("List already created.\n");
} else {
printf("Enter number of nodes: ");
scanf("%d", &n);
createList(n);
}
break;
case 2:
displayForward();
break;
case 3:
printf("Backward List: \n");
displayBackward(first);
printf("NULL\n");
break;
case 4:
reverseList();
printf("List reversed successfully.\n");
break;
case 5:
printf("Exiting...\n");
return 0;
default:
printf("Invalid choice! Try again.\n");
}
}
}

Output:-
PROGRAM-9
/*WAP to do the following operations on Singly linked list
i. Insertion in a list(sorted/unsorted list) :-
a. At the beginning b. At the end c. Anywhere in the middle*/

#include <stdio.h>
#include <stdlib.h>

struct node {
int info;
struct node* next;
} *first = NULL;

int isSorted = 0; // 1 for sorted, 0 for unsorted

void insertSorted(int info) {


struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->info = info;
newNode->next = NULL;

if (first == NULL || info < first->info) {


newNode->next = first;
first = newNode;
return;
}

struct node* temp = first;


while (temp->next && temp->next->info < info)
temp = temp->next;

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

void createList() {
int n, info;
printf("Enter the number of nodes: ");
scanf("%d", &n);

for (int i = 0; i < n; i++) {


printf("Enter info for node %d: ", i + 1);
scanf("%d", &info);
if (isSorted)
insertSorted(info);
else {
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->info = info;
newNode->next = NULL;

if (first == NULL)
first = newNode;
else {
struct node* temp = first;
while (temp->next)
temp = temp->next;
temp->next = newNode;
}
}
}
}

void insertBeginning(int info) {


struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->info = info;
newNode->next = first;
first = newNode;
}

void insertEnd(int info) {


struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->info = info;
newNode->next = NULL;

if (first == NULL)
first = newNode;
else {
struct node* temp = first;
while (temp->next)
temp = temp->next;
temp->next = newNode;
}
}
void insertMiddle(int info, int pos) {
struct node* newNode = (struct node*)malloc(sizeof(struct node));
newNode->info = info;

if (pos == 1) {
newNode->next = first;
first = newNode;
return;
}

struct node* temp = first;


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

if (temp == NULL) {
printf("Position out of range!\n");
free(newNode);
} else {
newNode->next = temp->next;
temp->next = newNode;
}
}

void displayList() {
struct node* temp = first;
if (!temp) {
printf("List is empty.\n");
return;
}
printf("Linked List: ");
while (temp) {
printf("%d -> ", temp->info);
temp = temp->next;
}
printf("NULL\n");
}

int main() {
int choice, info, pos;

printf("Choose list type:\n");


printf("1. Sorted Linked List\n");
printf("2. Unsorted Linked List\n");
printf("Enter choice: ");
scanf("%d", &isSorted);
isSorted = (isSorted == 1) ? 1 : 0;

createList();
displayList();

while (1) {
printf("\nMenu:\n");
printf("1. Insert at Beginning\n");
printf("2. Insert at End\n");
printf("3. Insert at Any Position\n");
printf("4. Display List\n");
printf("5. Exit\n");
printf("Enter choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter info: ");
scanf("%d", &info);
if (isSorted)
insertSorted(info);
else
insertBeginning(info);
break;
case 2:
printf("Enter info: ");
scanf("%d", &info);
if (isSorted)
insertSorted(info);
else
insertEnd(info);
break;
case 3:
if (isSorted) {
printf("For sorted list, elements are always inserted in order.\n");
break;
}
printf("Enter info: ");
scanf("%d", &info);
printf("Enter position: ");
scanf("%d", &pos);
insertMiddle(info, pos);
break;
case 4:
displayList();
break;
case 5:
printf("Exiting...\n");
return 0;
default:
printf("Invalid choice! Try again.\n");
}
}
}

Output:-
PROGRAM-10
/*WAP to do the following operations on Singly linked list:-

i.​ Deletion in a list(sorted/ unsorted list)


a.​ At the beginning
b.​ At the end
c. Anywhere in the middle*/
#include <stdio.h>
#include <stdlib.h>

struct node {
int info;
struct node* next;
} *first = NULL;

typedef struct node NODE;

void create_node();
void display_nodes();
void delete_from_sorted();
void delete_from_unsorted();

void main() {
printf("Select an operation:\n");
printf("1. Delete from a sorted linked list\n");
printf("2. Delete from an unsorted linked list\n");
printf("Enter your choice: ");

int user_choice;
scanf("%d", &user_choice);

switch (user_choice) {
case 1:
create_node();
printf("Current linked list:\n");
display_nodes();
delete_from_sorted();
printf("\nUpdated linked list:\n");
display_nodes();
break;
case 2:
create_node();
printf("Current linked list:\n");
display_nodes();
delete_from_unsorted();
printf("\nUpdated linked list:\n");
display_nodes();
break;
default:
printf("Invalid choice! Please select 1 or 2.\n");
break;
}
}

void create_node() {
NODE* last = NULL;
int total_nodes;

printf("How many nodes do you want to create? ");


scanf("%d", &total_nodes);

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


NODE* new_node = (NODE*)malloc(sizeof(NODE));
if (new_node == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
printf("Enter value for node %d: ", i);
scanf("%d", &new_node->info);
new_node->next = NULL;

if (first == NULL) {
first = new_node;
last = new_node;
} else {
last->next = new_node;
last = new_node;
}
}
}

void display_nodes() {
NODE* ptr = first;
if (ptr == NULL) {
printf("The list is empty.\n");
return;
}
while (ptr != NULL) {
printf("%d -> ", ptr->info);
ptr = ptr->next;
}
printf("NULL\n");
}

void delete_from_sorted() {
int value;
printf("\nEnter the element to delete: ");
scanf("%d", &value);

if (first == NULL) {
printf("The list is empty.\n");
return;
}

if (first->info == value) {
NODE* temp = first;
first = first->next;
free(temp);
printf("Element deleted successfully.\n");
return;
}

NODE* current = first;


while (current->next != NULL) {
if (current->next->info == value) {
NODE* temp = current->next;
current->next = temp->next;
free(temp);
printf("Element deleted successfully.\n");
return;
}
current = current->next;
}

printf("Element not found in the list.\n");


}
void delete_from_unsorted() {
int position;
printf("\nEnter the position to delete: ");
scanf("%d", &position);

if (first == NULL) {
printf("The list is empty.\n");
return;
}

if (position == 1) {
NODE* temp = first;
first = first->next;
free(temp);
printf("Node deleted successfully.\n");
return;
}

NODE* current = first;


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

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


printf("Invalid position. No node exists at position %d.\n", position);
return;
}

NODE* temp = current->next;


current->next = temp->next;
free(temp);
printf("Node deleted successfully.\n");
}
Output:-
PROGRAM-11
/* WAP to do the following operations on linked list:-

i. Searching from a list


ii. Sorting from a list */
#include <stdio.h>
#include <stdlib.h>

struct node {
int info;
struct node* next;
} *first = NULL;

typedef struct node NODE;

void createNode();
void displayNodes();
void searchNode();
void bubbleSort();

int main() {
printf("Choose from the following operations:\n");
printf("1 -- Search in the linked list\n");
printf("2 -- Sort the linked list\n");
printf("Enter your choice: ");
int userChoice;
scanf("%d", &userChoice);

switch (userChoice) {
case 1:
createNode();
printf("Current linked list:\n");
displayNodes();
searchNode();
break;
case 2:
createNode();
printf("Current linked list:\n");
displayNodes();
bubbleSort();
printf("\nSorted linked list:\n");
displayNodes();
break;
default:
printf("Invalid choice\n");
break;
}
return 0;
}

void createNode() {
NODE *last = NULL;
int n;
printf("Enter the number of nodes: ");
scanf("%d", &n);

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


NODE *newNode = (NODE *)malloc(sizeof(NODE));
if (newNode == NULL) {
printf("Memory allocation failed\n");
return;
}
printf("Enter Node %d value: ", i);
scanf("%d", &newNode->info);
newNode->next = NULL;

if (first == NULL) {
first = last = newNode;
} else {
last->next = newNode;
last = newNode;
}
}
}

void displayNodes() {
NODE *current = first;
while (current != NULL) {
printf("%d -> ", current->info);
current = current->next;
}
printf("NULL\n");
}
void searchNode() {
int element, found = 0, position = 0;
printf("\nEnter the element to search: ");
scanf("%d", &element);

NODE *current = first;


while (current != NULL) {
position++;
if (current->info == element) {
found = 1;
break;
}
current = current->next;
}

if (found) {
printf("Element found at node %d\n", position);
} else {
printf("Element not found\n");
}
}

void bubbleSort() {
int count = 0, temp;
NODE *current = first, *nextNode;

while (current != NULL) {


count++;
current = current->next;
}

for (int i = 0; i < count - 1; i++) {


current = first;
nextNode = current->next;
for (int j = 0; j < count - i - 1; j++) {
if (current->info > nextNode->info) {
temp = current->info;
current->info = nextNode->info;
nextNode->info = temp;
}
current = current->next;
nextNode = nextNode->next;
}
}
}

Output:-
PROGRAM-12
/*WAP to do the following operations on Doubly linked list-
1.​ Create a list
2.​ Traverse a list(forward/backward)*/

#include <stdio.h>
#include <stdlib.h>

struct dnode {
int info;
struct dnode *prev, *next;
} *first = NULL;

typedef struct dnode NODE;

void createNode();
void displayForward();
void displayBackward();

int main() {
createNode();
printf("Forward traversal:\n");
displayForward();
printf("\nBackward traversal:\n");
displayBackward();
return 0;
}

void createNode() {
NODE *last = NULL;
int n;
printf("Enter the number of nodes: ");
scanf("%d", &n);

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


NODE *newNode = (NODE *)malloc(sizeof(NODE));
if (newNode == NULL) {
printf("Memory allocation failed\n");
return;
}
printf("Enter Node %d value: ", i);
scanf("%d", &newNode->info);
newNode->prev = newNode->next = NULL;

if (first == NULL) {
first = last = newNode;
} else {
last->next = newNode;
newNode->prev = last;
last = newNode;
}
}
}

void displayForward() {
NODE *current = first;
printf("NULL -> ");
while (current != NULL) {
printf("%d -> ", current->info);
current = current->next;
}
printf("NULL\n");
}

void displayBackward() {
NODE *current = first;
if (current == NULL) {
printf("List is empty\n");
return;
}

while (current->next != NULL) {


current = current->next;
}

printf("NULL -> ");


while (current != NULL) {
printf("%d -> ", current->info);
current = current->prev;
}
printf("NULL\n");
}
Output:-
PROGRAM-13
/* WAP to do the following operations on Doubly linked list
i.​ Insertion in a list(sorted/unsorted list)
a.​ At the beginning
b.​ At the end
c.​ Anywhere in the middle*/

#include <stdio.h>
#include <stdlib.h>

struct dnode {
int info;
struct dnode *prev, *next;
} *first = NULL;

typedef struct dnode NODE;

void createNode();
void displayForward();
void insertSorted();
void insertUnsorted();

int main() {
printf("Choose from the following operations:\n");
printf("1 -- Insertion in sorted doubly linked list\n");
printf("2 -- Insertion in unsorted doubly linked list\n");
printf("Enter your choice: ");

int choice;
scanf("%d", &choice);

switch (choice) {
case 1:
createNode();
printf("\nCurrent linked list:\n");
displayForward();
insertSorted();
printf("\nUpdated linked list:\n");
displayForward();
break;
case 2:
createNode();
printf("\nCurrent linked list:\n");
displayForward();
insertUnsorted();
printf("\nUpdated linked list:\n");
displayForward();
break;
default:
printf("Invalid operation\n");
break;
}
return 0;
}

void createNode() {
NODE *last = NULL;
int n;
printf("Enter the number of nodes: ");
scanf("%d", &n);

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


NODE *newNode = (NODE *)malloc(sizeof(NODE));
if (newNode == NULL) {
printf("Memory allocation failed\n");
return;
}
printf("Enter Node %d value: ", i);
scanf("%d", &newNode->info);
newNode->prev = newNode->next = NULL;

if (first == NULL) {
first = last = newNode;
} else {
last->next = newNode;
newNode->prev = last;
last = newNode;
}
}
}

void displayForward() {
NODE *current = first;
printf("NULL -> ");
while (current != NULL) {
printf("%d -> ", current->info);
current = current->next;
}
printf("NULL\n");
}

void insertSorted() {
int element;
printf("\nEnter element to insert: ");
scanf("%d", &element);

NODE *newNode = (NODE *)malloc(sizeof(NODE));


if (newNode == NULL) {
printf("Memory allocation failed\n");
return;
}
newNode->info = element;
newNode->next = newNode->prev = NULL;

if (first == NULL || element < first->info) {


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

NODE *current = first;


while (current->next != NULL && element > current->next->info) {
current = current->next;
}

if (current->next == NULL) {
current->next = newNode;
newNode->prev = current;
} else {
newNode->next = current->next;
newNode->prev = current;
current->next->prev = newNode;
current->next = newNode;
}
}

void insertUnsorted() {
int position;
printf("\nEnter element to insert: ");

NODE *newNode = (NODE *)malloc(sizeof(NODE));


if (newNode == NULL) {
printf("Memory allocation failed\n");
return;
}
scanf("%d", &newNode->info);
newNode->next = newNode->prev = NULL;

printf("Enter position: ");


scanf("%d", &position);

if (position <= 0) {
printf("Invalid position\n");
free(newNode);
return;
}

if (position == 1) {
newNode->next = first;
if (first != NULL) {
first->prev = newNode;
}
first = newNode;
return;
}

NODE *current = first;


int count = 1;

while (count < position - 1 && current->next != NULL) {


current = current->next;
count++;
}

if (current->next == NULL) {
current->next = newNode;
newNode->prev = current;
} else {
newNode->next = current->next;
newNode->prev = current;
current->next->prev = newNode;
current->next = newNode;
}
}

Output:-
PROGRAM-14
/*WAP to do the following operations on Doubly linked list:-
i.​ Deletion in a list(sorted/unsorted list)
a.​At the beginning
b.​At the end
c.​Anywhere in the middle
*/
#include <stdio.h>
#include <stdlib.h>

struct node {
int info;
struct node *prev, *next;
} *first = NULL;

typedef struct node NODE;

void createNode();
void displayForward();
void deleteSorted();
void deleteUnsorted();

int main() {
printf("Choose from the following operations:\n");
printf("1 -- Deletion from sorted doubly linked list\n");
printf("2 -- Deletion from unsorted doubly linked list\n");
printf("Enter your operation: ");

int userOperation;
scanf("%d", &userOperation);

switch (userOperation) {
case 1:
createNode();
printf("\nCurrent Linked List:\n");
displayForward();
deleteSorted();
printf("\nUpdated Linked List:\n");
displayForward();
break;
case 2:
createNode();
printf("\nCurrent Linked List:\n");
displayForward();
deleteUnsorted();
printf("\nUpdated Linked List:\n");
displayForward();
break;
default:
printf("Oops! You entered an invalid operation\n");
break;
}
return 0;
}

void createNode() {
NODE *last = NULL;
int totalNodes;
printf("Enter the number of nodes you want to create: ");
scanf("%d", &totalNodes);

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


NODE *newNode = (NODE *)malloc(sizeof(NODE));
printf("Enter Node %d info: ", i);
scanf("%d", &newNode->info);
newNode->prev = NULL;
newNode->next = NULL;

if (first == NULL) {
first = newNode;
last = newNode;
} else {
last->next = newNode;
newNode->prev = last;
last = newNode;
}
}
}

void displayForward() {
NODE *ptr = first;
printf("NULL -> ");
while (ptr != NULL) {
printf("%d -> ", ptr->info);
ptr = ptr->next;
}
printf("NULL\n");
}

void deleteSorted() {
if (first == NULL) {
printf("\nList is empty!\n");
return;
}

int element;
printf("\nEnter the element to delete: ");
scanf("%d", &element);

NODE *ptr = first;

// If the element is at the beginning


if (ptr->info == element) {
first = ptr->next;
if (first != NULL) {
first->prev = NULL;
}
free(ptr);
printf("Element deleted successfully\n");
return;
}

while (ptr != NULL) {


if (ptr->info == element) {
if (ptr->next != NULL) {
ptr->next->prev = ptr->prev;
}
if (ptr->prev != NULL) {
ptr->prev->next = ptr->next;
}
free(ptr);
printf("Element deleted successfully\n");
return;
}
ptr = ptr->next;
}
printf("Element does not exist in linked list\n");
}

void deleteUnsorted() {
if (first == NULL) {
printf("\nList is empty!\n");
return;
}

int pos;
printf("\nEnter the position to delete: ");
scanf("%d", &pos);

NODE *ptr = first;


int count = 1;

if (pos == 1) {
first = ptr->next;
if (first != NULL) {
first->prev = NULL;
}
free(ptr);
printf("Node deleted successfully\n");
return;
}

while (ptr != NULL && count < pos) {


ptr = ptr->next;
count++;
}

if (ptr == NULL) {
printf("Node does not exist in linked list\n");
return;
}

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

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

free(ptr);
printf("Node deleted successfully\n");
}

Output:-
PROGRAM-15
/* WAP to do the following operations on Circular linked list-
i. Create a list
ii. Traverse a list(forward/backward)*/

#include <stdio.h>
#include <stdlib.h>

struct cnode {
int info;
struct cnode *prev, *next;
} *first = NULL;

typedef struct cnode NODE;

void createNode();
void displayForward();
void displayBackward();

int main() {
createNode();
printf("\nForward traversal:\n");
displayForward();
printf("\n\nBackward traversal:\n");
displayBackward();

return 0;
}

void createNode() {
NODE *last = NULL;
int totalNodes;
printf("Enter the number of nodes you want to create: ");
scanf("%d", &totalNodes);

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


NODE *newNode = (NODE *)malloc(sizeof(NODE));
printf("Enter Node %d info: ", i);
scanf("%d", &newNode->info);
if (first == NULL) {
first = newNode;
first->next = first;
first->prev = first;
last = first;
} else {
newNode->next = first;
newNode->prev = last;
last->next = newNode;
first->prev = newNode;
last = newNode;
}
}
}

void displayForward() {
if (first == NULL) {
printf("List is empty\n");
return;
}

NODE *ptr = first;


do {
printf("%d -> ", ptr->info);
ptr = ptr->next;
} while (ptr != first);
printf("HEAD\n");
}

void displayBackward() {
if (first == NULL) {
printf("List is empty\n");
return;
}

NODE *ptr = first->prev;


do {
printf("%d -> ", ptr->info);
ptr = ptr->prev;
} while (ptr != first->prev);
printf("HEAD\n");
}
Output:-
PROGRAM-16
/*WAP to do the following operations on Circular linked list
i.​ Insertion in a list(sorted/unsorted list)
a.​At the beginning
b.​At the end
c.​Anywhere in the middle*/

#include <stdio.h>
#include <stdlib.h>

struct cnode {
int info;
struct cnode *prev, *next;
} *head = NULL;
typedef struct cnode NODE;

void createNode();
void displayList();
void insertSorted();
void insertUnsorted();

int main() {
printf("Choose from the following operations:\n");
printf("1 -- Insertion in sorted double circular linked list\n");
printf("2 -- Insertion in unsorted double circular linked list\n");
printf("Enter your operation: ");

int userOption;
scanf("%d", &userOption);

switch (userOption) {
case 1:
createNode();
printf("Current linked list:\n");
displayList();
insertSorted();
printf("\nUpdated linked list:\n");
displayList();
break;
case 2:
createNode();
printf("Current linked list:\n");
displayList();
insertUnsorted();
printf("\nUpdated linked list:\n");
displayList();
break;
default:
printf("You entered an invalid operation\n");
break;
}

return 0;
}

void createNode() {
NODE *last = NULL;
int totalNodes;
printf("Enter the number of nodes you want to create: ");
scanf("%d", &totalNodes);

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


NODE *newNode = (NODE*)malloc(sizeof(NODE));
printf("Enter Node %d info: ", i);
scanf("%d", &newNode->info);
newNode->prev = last;
newNode->next = head;

if (head == NULL) {
head = newNode;
last = newNode;
head->next = head;
head->prev = head;
} else {
last->next = newNode;
last = newNode;
head->prev = last;
}
}
}
void displayList() {
if (head == NULL) {
printf("List is empty\n");
return;
}

NODE *ptr = head;


do {
printf("%d -> ", ptr->info);
ptr = ptr->next;
} while (ptr != head);
printf("HEAD\n");
}

void insertSorted() {
int element;
printf("\nEnter the element to insert: ");
scanf("%d", &element);

NODE *newNode = (NODE*)malloc(sizeof(NODE));


newNode->info = element;

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

NODE *ptr = head;

if (element < head->info) {


newNode->next = head;
newNode->prev = head->prev;
head->prev->next = newNode;
head->prev = newNode;
head = newNode;
} else {
while (ptr->next != head && element > ptr->next->info) {
ptr = ptr->next;
}

newNode->next = ptr->next;
newNode->prev = ptr;
ptr->next->prev = newNode;
ptr->next = newNode;
}
}

void insertUnsorted() {
NODE *newNode = (NODE*)malloc(sizeof(NODE));
int position;
printf("\nEnter the element to insert: ");
scanf("%d", &newNode->info);
printf("Enter the position to insert at: ");
scanf("%d", &position);

if (position < 1) {
printf("Invalid position\n");
return;
}

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

NODE *ptr = head;

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

for (int i = 1; i < position - 1 && ptr->next != head; i++) {


ptr = ptr->next;
}

newNode->next = ptr->next;
newNode->prev = ptr;
ptr->next->prev = newNode;
ptr->next = newNode;
}

Output:-
PROGRAM-17
/* WAP to do the following operations on Circular linked list:-
i.​ Deletion in a list(sorted/unsorted list)
a.​At the beginning
b.​At the end
c.Anywhere in the middle.*/

#include <stdio.h>
#include <stdlib.h>

struct cnode {
int info;
struct cnode *prev, *next;
}*first = NULL;

typedef struct cnode NODE;

void create_node();
void forward();
void delete_at_beginning();
void delete_at_end();
void delete_at_position();

int main() {
int choice;
create_node();
printf("\nCurrent Linked List:\n");
forward();

printf("\nChoose deletion operation:\n");


printf("1 -- Delete at beginning\n");
printf("2 -- Delete at end\n");
printf("3 -- Delete at a specific position\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
delete_at_beginning();
break;
case 2:
delete_at_end();
break;
case 3:
delete_at_position();
break;
default:
printf("Invalid choice!\n");
return 1;
}

printf("\nUpdated Linked List:\n");


forward();

return 0;
}

void create_node() {
NODE *last = NULL;
int total_nodes;
printf("Enter the number of nodes you want to create: ");
scanf("%d", &total_nodes);

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


NODE *new_node = (NODE *)malloc(sizeof(NODE));
if (new_node == NULL) {
printf("Memory allocation failed!\n");
return;
}

printf("Enter Node %d info: ", i);


scanf("%d", &new_node->info);

if (first == NULL) {
first = new_node;
first->next = first;
first->prev = first;
last = first;
} else {
new_node->next = first;
new_node->prev = last;
last->next = new_node;
first->prev = new_node;
last = new_node;
}
}
}

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

NODE *ptr = first;


do {
printf("%d -> ", ptr->info);
ptr = ptr->next;
} while (ptr != first);
printf("End\n");
}

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

NODE *temp = first;


if (first->next == first) { // Only one node in the list
first = NULL;
} else {
first->prev->next = first->next;
first->next->prev = first->prev;
first = first->next;
}
free(temp);
printf("First node deleted successfully.\n");
}

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

NODE *last = first->prev;


if (first->next == first) { // Only one node in the list
free(first);
first = NULL;
} else {
last->prev->next = first;
first->prev = last->prev;
free(last);
}
printf("Last node deleted successfully.\n");
}

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

int pos, count = 1;


printf("Enter the position to delete: ");
scanf("%d", &pos);

NODE *ptr = first;

if (pos == 1) {
delete_at_beginning();
return;
}

do {
if (count == pos) {
ptr->prev->next = ptr->next;
ptr->next->prev = ptr->prev;
free(ptr);
printf("Node at position %d deleted successfully.\n", pos);
return;
}
count++;
ptr = ptr->next;
} while (ptr != first);
printf("Invalid position.\n");
}
Output:-
PROGRAM-18
/*WAP to merge two singly sorted linked lists.*/
#include <stdio.h>
#include <stdlib.h>

struct node {
int info;
struct node *next;
};
typedef struct node NODE;

void create_node(NODE **first);


void merge(NODE *list1, NODE *list2, NODE **merge_list);
void free_list(NODE *head);

int main() {
NODE *list1 = NULL, *list2 = NULL;
printf("Creating 1st linked list:\n");
create_node(&list1);
printf("Linked list 1:\n");
NODE *ptr = list1;
while (ptr != NULL) {
printf("%d -> ", ptr->info);
ptr = ptr->next;
}
printf("NULL\n");

printf("Creating 2nd linked list:\n");


create_node(&list2);
printf("Linked list 2:\n");
ptr = list2;
while (ptr != NULL) {
printf("%d -> ", ptr->info);
ptr = ptr->next;
}
printf("NULL\n");

printf("Merging both linked lists:\n");


NODE *merge_list = NULL;
merge(list1, list2, &merge_list);

ptr = merge_list;
while (ptr != NULL) {
printf("%d -> ", ptr->info);
ptr = ptr->next;
}
printf("NULL\n");

// Free allocated memory


free_list(list1);
free_list(list2);
free_list(merge_list);

return 0;
}

void create_node(NODE **first) {


NODE *last = NULL;
int total_nodes;
printf("Enter the number of nodes: ");
scanf("%d", &total_nodes);

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


NODE *new_node = (NODE *)malloc(sizeof(NODE));
if (new_node == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
printf("Enter node %d info: ", i);
scanf("%d", &new_node->info);
new_node->next = NULL;

if (*first == NULL) {
*first = new_node;
last = new_node;
} else {
last->next = new_node;
last = new_node;
}
}
}

void merge(NODE *list1, NODE *list2, NODE **merge_list) {


NODE *ptr1 = list1;
NODE *ptr2 = list2;
NODE *last = NULL;

while (ptr1 != NULL && ptr2 != NULL) {


NODE *new_node = (NODE *)malloc(sizeof(NODE));
if (new_node == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}

if (ptr1->info < ptr2->info) {


new_node->info = ptr1->info;
ptr1 = ptr1->next;
} else if (ptr1->info > ptr2->info) {
new_node->info = ptr2->info;
ptr2 = ptr2->next;
} else {
// Skip duplicates by advancing both pointers
new_node->info = ptr1->info;
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}

new_node->next = NULL;

if (*merge_list == NULL) {
*merge_list = new_node;
last = new_node;
} else {
last->next = new_node;
last = new_node;
}
}

// Add remaining elements from list1


while (ptr1 != NULL) {
NODE *new_node = (NODE *)malloc(sizeof(NODE));
if (new_node == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
new_node->info = ptr1->info;
new_node->next = NULL;
if (last == NULL) {
*merge_list = new_node;
last = new_node;
} else {
last->next = new_node;
last = new_node;
}
ptr1 = ptr1->next;
}

while (ptr2 != NULL) {


NODE *new_node = (NODE *)malloc(sizeof(NODE));
if (new_node == NULL) {
printf("Memory allocation failed!\n");
exit(1);
}
new_node->info = ptr2->info;
new_node->next = NULL;
if (last == NULL) {
*merge_list = new_node;
last = new_node;
} else {
last->next = new_node;
last = new_node;
}
ptr2 = ptr2->next;
}
}

void free_list(NODE *head) {


NODE *temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
}

Output:-
PROGRAM-19
/*WAP to implement Polynomial addition operation using Singly linked
list.*/

#include <stdio.h>
#include <stdlib.h>

struct node {
int coeff;
int exp;
struct node *next;
};
typedef struct node NODE;

void create_poly(NODE **head);


void add_poly(NODE **poly1, NODE **poly2, NODE **result);
void free_list(NODE *head);

int main() {
NODE *poly1 = NULL, *poly2 = NULL;
printf("Creating Polynomial 1:\n");
create_poly(&poly1);
printf("Polynomial 1:\n");
NODE *current = poly1;
while (current != NULL) {
printf("%dx(%d) ", current->coeff, current->exp);
current = current->next;
}
printf("\n");

printf("Creating Polynomial 2:\n");


create_poly(&poly2);
printf("Polynomial 2:\n");
current = poly2;
while (current != NULL) {
printf("%dx(%d) ", current->coeff, current->exp);
current = current->next;
}
printf("\n");
NODE *result = NULL;
add_poly(&poly1, &poly2, &result);
printf("Resultant Polynomial:\n");
current = result;
while (current != NULL) {
printf("%dx(%d) ", current->coeff, current->exp);
current = current->next;
}
printf("\n");

free_list(poly1);
free_list(poly2);
free_list(result);

return 0;
}

void create_poly(NODE **head) {


NODE *last = NULL;
int terms;
printf("Enter number of terms: ");
scanf("%d", &terms);
for (int i = 0; i < terms; i++) {
NODE *new_node = (NODE *)malloc(sizeof(NODE));
if (new_node == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
printf("Term %d coefficient: ", i + 1);
scanf("%d", &new_node->coeff);
printf("Term %d exponent: ", i + 1);
scanf("%d", &new_node->exp);
new_node->next = NULL;

if (*head == NULL) {
*head = new_node;
last = new_node;
} else {
last->next = new_node;
last = new_node;
}
}
}

void add_poly(NODE **poly1, NODE **poly2, NODE **result) {


NODE *ptr1 = *poly1;
NODE *ptr2 = *poly2;
NODE *new_node, *last = NULL;

while (ptr1 != NULL && ptr2 != NULL) {


new_node = (NODE *)malloc(sizeof(NODE));
if (new_node == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
if (ptr1->exp > ptr2->exp) {
new_node->coeff = ptr1->coeff;
new_node->exp = ptr1->exp;
ptr1 = ptr1->next;
} else if (ptr1->exp < ptr2->exp) {
new_node->coeff = ptr2->coeff;
new_node->exp = ptr2->exp;
ptr2 = ptr2->next;
} else {
new_node->coeff = ptr1->coeff + ptr2->coeff;
new_node->exp = ptr1->exp;
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
new_node->next = NULL;

if (*result == NULL) {
*result = new_node;
last = new_node;
} else {
last->next = new_node;
last = new_node;
}
}

while (ptr1 != NULL) {


new_node = (NODE *)malloc(sizeof(NODE));
if (new_node == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
new_node->coeff = ptr1->coeff;
new_node->exp = ptr1->exp;
new_node->next = NULL;
ptr1 = ptr1->next;
if (last == NULL) {
*result = new_node;
last = new_node;
} else {
last->next = new_node;
last = new_node;
}
}

while (ptr2 != NULL) {


new_node = (NODE *)malloc(sizeof(NODE));
if (new_node == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
new_node->coeff = ptr2->coeff;
new_node->exp = ptr2->exp;
new_node->next = NULL;
ptr2 = ptr2->next;
if (last == NULL) {
*result = new_node;
last = new_node;
} else {
last->next = new_node;
last = new_node;
}
}
}

void free_list(NODE *head) {


NODE *temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
}

Output:-
PROGRAM-20
/* Write a C program to create two linked lists from a given list in following
way:-
INPUT List: - 1 2 3 4 5 6 7 8 9 10

OUTPUT:- First List:- 1 3 5 7 9 Second List:- 2 4 6 8 10*/


#include <stdio.h>
#include <stdlib.h>

struct node {
int data;
struct node *next;
};
typedef struct node NODE;

void create_list(NODE **head);


void separate(NODE **head, NODE **odd_head, NODE **even_head);
void free_list(NODE *head);

int main() {
NODE *head = NULL;
create_list(&head);
printf("Original linked list:\n");
NODE *current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");

NODE *odd_head = NULL, *even_head = NULL;


separate(&head, &odd_head, &even_head);

printf("Odd linked list:\n");


current = odd_head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
printf("Even linked list:\n");
current = even_head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");

free_list(head);
free_list(odd_head);
free_list(even_head);

return 0;
}

void create_list(NODE **head) {


NODE *last = NULL;
int n;
printf("Number of nodes: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
NODE *new_node = (NODE *)malloc(sizeof(NODE));
if (new_node == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
printf("Value for node %d: ", i + 1);
scanf("%d", &new_node->data);
new_node->next = NULL;

if (*head == NULL) {
*head = new_node;
last = new_node;
} else {
last->next = new_node;
last = new_node;
}
}
}
void separate(NODE **head, NODE **odd_head, NODE **even_head) {
NODE *ptr = *head;
NODE *new_node, *odd = NULL, *even = NULL;
while (ptr != NULL) {
new_node = (NODE *)malloc(sizeof(NODE));
if (new_node == NULL) {
printf("Memory allocation failed\n");
exit(1);
}
new_node->data = ptr->data;
new_node->next = NULL;
if (ptr->data % 2 == 0) {
if (*even_head == NULL) {
*even_head = new_node;
even = new_node;
} else {
even->next = new_node;
even = new_node;
}
} else {
if (*odd_head == NULL) {
*odd_head = new_node;
odd = new_node;
} else {
odd->next = new_node;
odd = new_node;
}
}
ptr = ptr->next;
}
}

void free_list(NODE *head) {


NODE *temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
}
Output:-
PROGRAM-21
/* WAP to implement Student Database using Linked List with the
following structure :-
i.​ Name
ii.​ Rollno
iii.​ Marks of 5 subjects
iv.​ Average
v. Result, If the average < 50, then print ‘Fail’, otherwise ‘Pass’*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node {
char name[50];
int roll;
int marks[5];
float avg;
char result[10];
struct node *next;
} *head = NULL;

typedef struct node NODE;

int main() {
NODE *tail = NULL;
int total;

printf("Total students: ");


if (scanf("%d", &total) != 1 || total <= 0) {
printf("Invalid input. Exiting...\n");
return 1;
}
while (getchar() != '\n'); // Clear input buffer

for (int i = 0; i < total; i++) {


NODE* student = (NODE*)malloc(sizeof(NODE));
if (student == NULL) {
printf("Memory allocation failed.\n");
return 1;
}

printf("Student %d details:\n", i + 1);

printf("Name: ");
fgets(student->name, sizeof(student->name), stdin);
student->name[strcspn(student->name, "\n")] = '\0';

printf("Roll No: ");


if (scanf("%d", &student->roll) != 1) {
printf("Invalid roll number.\n");
free(student);
return 1;
}
while (getchar() != '\n'); // Clear input buffer

int sum = 0;
for (int j = 0; j < 5; j++) {
printf("Marks in subject %d: ", j + 1);
if (scanf("%d", &student->marks[j]) != 1 || student->marks[j] < 0 || student->marks[j] > 100) {
printf("Invalid marks. Enter values between 0 and 100.\n");
free(student);
return 1;
}
sum += student->marks[j];
}

student->avg = (float)sum / 5;
strcpy(student->result, (student->avg < 50) ? "Fail" : "Pass");
student->next = NULL;

if (head == NULL) {
head = student;
tail = student;
} else {
tail->next = student;
tail = student;
}
}

NODE *ptr = head;


for (int i = 0; i < total; i++) {
printf("\nStudent %d:\n", i + 1);
printf("Name: %s\n", ptr->name);
printf("Roll No: %d\n", ptr->roll);
for (int j = 0; j < 5; j++) {
printf("Subject %d: %d ", j + 1, ptr->marks[j]);
}
printf("\nAverage: %.2f\n", ptr->avg);
printf("Result: %s\n", ptr->result);
ptr = ptr->next;
}

// Free memory
ptr = head;
while (ptr != NULL) {
NODE *temp = ptr;
ptr = ptr->next;
free(temp);
}

return 0;
}

Output:-
PROGRAM-22
/* Write a program in C to swap elements using call by reference*/
#include <stdio.h>
void swapNum(int *x,int *y)
{​ int t;
​ t=*x;
​ *x=*y;
​ *y=t;
}
void main()
{ int n1,n2;
​ printf("\n\n Pointer : Swap elements using call by reference :\n");
​ printf("​\n");
​ printf(" Input the value of 1st element : ");
​ scanf("%d",&n1);
​ printf(" Input the value of 2nd element : ");
​ scanf("%d",&n2);
​ printf("\n The value before swapping are :\n");
​ printf(" Number 1 = %d\n Number 2 = %d\n ",n1,n2);
​ swapNum(&n1,&n2);
​ printf("\n The value after swapping are :\n");
​ printf(" Number 1 = %d\n Number 2 = %d\n ",n1,n2);
}
Output:-
PROGRAM-23
/* Write a program in C to store n elements in an array and print the
elements using pointer.*/
#include <stdio.h>

void main()

{​ int arr[100],n,i,*ptr=arr;

​ printf("\n Enter size of array: ");

​ scanf("%d", &n);

​ printf("\n Enter elements in array:\n ");

​ for (i=0; i<n; i++)

​ {

​ ​ scanf("%d", ptr);

​ ​ ptr++;

​ }

​ ptr = arr;

​ printf("\n Array elements: \n");

​ for (i=0; i<n; i++)

​ {

​ ​ printf(" %d ",*ptr);

​ ​ ptr++;

​ }

Output:-
PROGRAM-24
/* Write a program in C to print a string in reverse using a pointer.*/
#include <stdio.h>

void main()

{​ char *s;

​ int len,i;

​ printf("\n Enter a string: ");

​ gets(s);

​ len=strlen(s);

​ printf("\n The reverse of the string is: ");

​ for(i=len; i>=0; i--)

​ ​ printf("%c",*(s+i));

Output:-
PROGRAM-25
/* Write a program in C to count the number of vowels and consonants in a
string using a pointer.*/
#include <stdio.h>

void main()

{​ char str1[50],*pt;

​ int v=0,c=0,n=0;

​ printf("\n Pointer : Count the number of vowels and consonants:\n");

​ printf("​\n");

​ printf(" Input a string: ");

​ gets(str1);

​ pt=str1;

​ while(*pt!='\0')

​ {​ if(*pt=='A' ||*pt=='E' ||*pt=='I' ||*pt=='O' ||*pt=='U' ||*pt=='a' ||*pt=='e'


||*pt=='i' ||*pt=='o' ||*pt=='u') v++;

​ ​ else if(*pt==' '||(*pt>='0'&&*pt<='9'))

​ ​ ​ n++;

​ ​ else

​ ​ ​ c++;

​ ​ pt++;

​ }

​ printf(" Number of vowels : %d\n Number of consonants : %d\n",v,c);

Output:-
PROGRAM-26
/* WAP to read and print employee details like Employee ID, EName,
salary using structures*/
#include<stdio.h>

#include<stdlib.h>

struct emp

​ char name[30];

​ int id;

​ long int salary;

} e[3];

void main()

​ int i, n;

​ printf(" Enter no. of employees: ");

​ scanf("%d",&n);

​ e[n];

​ printf(" Enter details of %d employees \n\n",n);

​ for(i=0; i<n; i++)

​ {

​ ​ printf(" Employee %d: \n",i+1);

​ ​ printf(" Name: ");

​ ​ scanf("%s",e[i].name);

​ ​ printf(" ID: ");

​ ​ scanf("%d",&e[i].id);

​ ​ printf(" Salary: ");


​ ​ scanf("%ld",&e[i].salary);

​ ​ printf("\n");

​ }

​ printf("------ All Employees Details ------​ \n");

​ for(i=0; i<n; i++)

​ {

​ ​ printf(" Employee %d:\n",i+1);

​ ​ printf(" Name \t: %s \n",e[i].name);

​ ​ printf(" ID \t: %d \n",e[i].id);

​ ​ printf(" Salary : %ld \n",e[i].salary);

​ ​ printf("\n");

​ }

Output:-
PROGRAM-27
/* Create a structure item (char item_name[10],int qty,float price,float
total_amt) . Enter details regarding items. Create a pointer variable *pitem
of a structure item and access the elements or members of a structure using
pointer variable by using -> operator.*/
#include <stdio.h>

struct item

{​ char item_name[10];

​ int qty;

​ float price, total_amt;

itm[10],*pitem=NULL;

void dummy(float *a)

{​ float b=*a;

​ dummy (&b);

void main()

{​ int n,i,j;

​ pitem=itm;

​ printf(" Enter no. of items to enter: ");

​ scanf("%d",&n);

​ for(i=0; i<n; i++)

​ {​ printf("\n Enter product %d details\n",i+1);

​ ​ printf(" Enter product name: ");

​ ​ scanf("%s",&pitem->item_name);

​ ​ printf(" Enter price: ");

​ ​ scanf("%f",&pitem->price);
​ ​ printf(" Enter quantity: ");

​ ​ scanf("%d",&pitem->qty);

​ ​ pitem->total_amt =(float)pitem->qty* pitem->price;

​ ​ pitem++;

​ }

​ pitem=itm;

​ printf("\n\t\t\tYOUR ORDER\n--------------------------------");

​ for(j=0; j<n; j++)

​ {​ printf("\n\n Item %d",j+1);

​ ​ printf("\n Name: %s",pitem->item_name);

​ ​ printf("\n Price: %.2f",pitem->price);

​ ​ printf("\n Quantity: %d",pitem->qty);

​ ​ printf("\n Total Amount: %.2f",pitem->total_amt);

​ ​ pitem++;

​ }

Output:-
PROGRAM-28
/* Create a structure student (charname[10],int marks[3],,int total and float
percentage). Enter the marks of 5 students in 3 subjects and calculate the
percentage .(Hint:Use the concept of array of structure).*/
#include <stdio.h>

struct student

{​ char name[10];

​ int roll_no;

​ int marks[3];

​ float percentage;

} s[5];

void dummy(float *a)

{​ float b=*a;

​ dummy(&b);

void main()

{​ int i=0,n;

​ printf("No. of students: ");

​ scanf("%d", &n);

​ for(i=0; i<n; i++)

​ {​ printf("\n Student %d\n",i+1);

​ ​ printf(" Enter roll no.: ");

​ ​ scanf("%d", &s[i].roll_no);

​ ​ printf(" Enter name: ");

​ ​ scanf("%s",s[i].name);

​ ​ printf(" Enter marks in subject 1: ");

​ ​ scanf("%d", &s[i].marks[0]);
​ ​ printf(" Enter marks in Subject 2: ");

​ ​ scanf("%d", &s[i].marks[1]);

​ ​ printf(" Enter marks in Subject 3: ");

​ ​ scanf("%d", &s[i].marks[2]);

​ ​ s[i].percentage = (float)(s[i].marks[0]+s[i].marks[1]+s[i].marks[2])/(float)(3);

​ ​ printf("\n Percentage of student %d: %.2f \n",i+1,s[i].percentage);

​ }

Output:-
PROGRAM-29
/* Create a union union Data { int i;float f;char str[20]}.WAP to show
how to access and print members of union and also print the maximum
memory occupied by union members.*/
#include <stdio.h>

union Data

{​ int i;

​ float f;

​ char str[20];

} d;

void main()

{​ d.i=12;

​ printf("\n Value of i\t: %d",d.i);

​ d.f=25.5;

​ printf("\n Value of f\t: %.2f",d.f);

​ strcpy(d.str, "C Programming");

​ printf("\n Value of str\t: %s",d.str);

​ printf("\n\n Maximum size occupied by union member: %d",sizeof(d));

Output:-
PROGRAM-30
/* Write a program in C to create and store information in a text file(using
fprintf and fscanf functions)*/
#include <stdio.h>

#include <stdlib.h>

void main()

​ int num;

​ FILE *fptr1, *fptr2;

​ fptr1 = fopen("file38.txt","w");

​ if(fptr1 == NULL)

​ {

​ ​ printf(" Error!");

​ ​ exit(1);

​ }

​ printf(" Enter num: ");

​ scanf("%d",&num);

​ fprintf(fptr1,"%d",num);

​ printf(" Value stored in file! \n");

​ fclose(fptr1);

​ if ((fptr2 = fopen("file38.txt","r")) == NULL)

​ {

​ ​ printf(" Error! opening file");

​ ​ exit(1);

​ }

​ printf("\n Now, reading from the file...");


​ fscanf(fptr2,"%d", &num);

​ printf("\n Value of n=%d", num);

​ fclose(fptr2);

Output:-
PROGRAM-31
/* Write a program in C to create and store information in a binary
file(using fread and fwrite functions)*/
#include<stdio.h> struct emp

​ char name[20], surname[20], no[20];

} e;

void main()

​ char another='y';

​ FILE *fp;

​ fp = fopen("student.bin","rb+");

​ if(fp == NULL)

​ {

​ ​ fp = fopen("student.bin","wb+");

​ ​ if(fp == NULL)

​ ​ {

​ ​ ​ printf("File is not opening.");

​ ​ ​ exit(1);

​ ​ }

​ }

​ fseek(fp, 0, SEEK_END);

​ while(another == 'y')

​ {

​ ​ printf("\n\n Enter name: ");

​ ​ scanf("%s",e.name);

​ ​ printf(" Enter surname: ");


​ ​ scanf("%s", &e.surname);

​ ​ printf(" Enter ID no.: ");

​ ​ scanf("%s", &e.no);

​ ​ fwrite(&e, sizeof(struct emp), 1, fp);

​ ​ printf("\n Want to write more?(y/n): ");

​ ​ another = getche();

​ }

​ printf(" \n\n Displaying contents of file:\n -----------------------------\n ");

​ rewind(fp);

​ while(fread(&e, sizeof(e),1,fp)==1)

​ {

​ ​ printf("\n %s\t %s\t %s", &e.name,&e.surname,&e.no);

​ }

Output:-
PROGRAM-32
/* Write a program in C to create and store information in a data file(using
getc and putc functions)*/
#include <stdio.h>

void main()

​ FILE * fp;

​ char c;

​ printf(" Enter text:\n ");

​ fp = fopen("file.txt", "w+");

​ while ((c = getchar()) != EOF)

​ {

​ ​ putc(c, fp);

​ }

​ printf(" Data Entered!\n");

​ fp = fopen("file.txt", "r+");

​ printf("\n Displaying contents from the file! \n ----------------------- \n ");

​ while ((c = getc(fp)) != EOF)

​ {

​ ​ printf("%c", c);

​ }

​ fclose(fp);

Output:-
PROGRAM-33
/* Write a program in C to create and store information in a data
file(using fgets and fputs functions)*/
# include <stdio.h>

# include <string.h>

void main( )

​ FILE *fp ;

​ char data[50];

​ fp = fopen("file41.txt", "a+") ;

​ if ( fp == NULL )

​ {

​ ​ printf( " Could not open file test2.txt! " ) ;

​ ​ exit(0);

​ }

​ printf( "\n Enter some text from keyboard to write in the file: \n " ) ;

​ {

​ ​ fputs(data, fp) ;

​ ​ fputs("\n", fp) ;

​ }

​ fclose(fp) ;

​ fp = fopen("file41.txt","r+");

​ if (fp==NULL)

​ {

​ ​ printf(" Could not open file test2.txt" );

​ ​ exit(0);

​ }
​ printf(" Contents of the file: \n​ \n" );

​ while(fgets(data,50,fp)!=NULL)

​ ​ printf( " %s", data );

​ fclose(fp);

Output:-
PROGRAM-34
/* Write a program in C to create and store information in a data
file(using getw and putw functions)*/
#include <stdio.h>

void main ()

​ FILE *fp;

​ int i, num;

​ printf(" Enter 5 numbers to write in file: \n ");

​ fp = fopen ("test42.txt","w+");

​ for(i=1; i<=5; i++)

​ {

​ ​ num= getw(stdin);

​ ​ putw(num,fp);

​ }

​ fclose(fp);

​ fp = fopen ("test42.txt","r+");

​ printf(" \n Contents in the file: \n​ \n ");

​ while((num=getw(fp))!=EOF)

​ {

​ ​ putw(num,stdout);

​ }

​ fclose(fp);

Output:-
PROGRAM-35
/* Write a program in C to count a number of words and characters in a
file.*/
#include<stdio.h>

void main()

​ FILE * fp;

​ char c,ch[50];

​ int w=0,chr=0;

​ printf(" Enter data to write in file: \n ");

​ fp = fopen("file44.txt", "w+");

​ fputs(ch,fp);

​ fputs("\n",fp);

​ fclose(fp);

​ printf("\n Data Entered! \n");

​ printf("\n Contents in the file: \n​ \n ");

​ fp = fopen("file44.txt", "r+");

​ while ((c = getc(fp)) != EOF)

​ {

​ ​ printf("%c", c);

​ ​ if(c==' '||c=='\n')

​ ​ ​ w++;

​ ​ else

​ ​ ​ chr++;

​ }

​ fclose(fp);

​ printf("\n The no. of words are: %d \n The no. of characters are:


​ %d\n",w,chr);

Output:-
PROGRAM-36
/* Write a program in C to merge two files and write it in a new file.*/
#include<stdio.h> #include <stdlib.h>
void main()
{
​ FILE *fold1, *fold2, *fnew;
​ char ch, fname1[20], fname2[20], fname3[30];
​ printf("\n\n Merge two files and write it in a new file :\n");
​ printf("​\n");
​ printf(" Input the 1st file name : ");
​ scanf("%s",fname1);
​ printf(" Input the 2nd file name : ");
​ scanf("%s",fname2);
​ printf(" Input the new file name where to merge the above two files : ");
​ scanf("%s",fname3);
​ fold1=fopen(fname1, "r+");
​ fold2=fopen(fname2, "r+");
​ if(fold1==NULL ||fold2==NULL)
​ {
​ ​ printf(" File does not exist or error in opening...!!\n");
​ ​ exit(0);
​ }
​ printf("\n\n Contents of file %s: \n ",fname1);
​ while((ch=fgetc(fold1))!=EOF)
​ {
​ ​ printf("%c",ch);
​ }
​ rewind(fold1);
​ printf("\n\n Contents of file %s: \n ",fname2);
​ while((ch=fgetc(fold2))!=EOF)
​ {
​ ​ printf("%c",ch);
​ }
​ rewind(fold2);
​ fnew=fopen(fname3,"w+");
​ if(fnew==NULL)
​ {
​ ​ printf(" File does not exist or error in opening...!!\n");
​ ​ exit(0);
​ }
​ while((ch=fgetc(fold1))!=EOF)
​ {
​ ​ fputc(ch,fnew);
​ }
​ while((ch=fgetc(fold2))!=EOF)
​ {
​ ​ fputc(ch,fnew);
​ }
​ rewind(fnew);
​ printf("\n\n Contents of new merged file %s: \n ",fname3);
​ while((ch=fgetc(fnew))!=EOF)
​ {
​ ​ printf("%c",ch);
​ }
​ fclose(fold1);
​ fclose(fold2);
​ fclose(fnew);
}
Output:-
PROGRAM-37
/* WAP in C that takes the file name as an input from user, create a file
“data” to store integer numbers from 1 to 10. Create two more files “even”
and “odd” , read the contents of “data” and check whether the number is
even and odd and copied the same in to “ even” and “odd” file. */
#include<stdio.h>

#include<process.h>

void main()

​ int a,i;

​ char fname[30];

​ FILE *fp1,*fp2,*fp3;

​ printf(" Enter the name of file to store info: ");

​ gets(fname);

​ fp1=fopen(fname,"w+");

​ if(fp1==NULL)

​ {

​ ​ printf(" File could not open!! ");

​ ​ exit(0);

​ }

​ for(a=1; a<=10; ++a)

​ {

​ ​ putw(a,fp1);

​ }

​ rewind(fp1);

​ printf("\n Contents of %s file: \n ",fname);

​ while((a=getw(fp1))!=EOF)
​ {

​ ​ printf("%d ",a);

​ }

​ rewind(fp1);

​ fclose(fp1);

​ fp1=fopen(fname,"r");

​ fp2=fopen("odd.txt","w");

​ fp3=fopen("even.txt","w");

​ if(fp1==NULL||fp2==NULL||fp3==NULL)

​ {

​ ​ printf(" File could not open!! ");

​ ​ exit(0);

​ }

​ while((a=getw(fp1))!=EOF)

​ {​ if(a%2!=0)

​ ​ ​ putw(a,fp2);

​ ​ else putw(a,fp3);

​ }

​ fclose(fp1);

​ fclose(fp2);

​ fclose(fp3);

​ fp2=fopen("odd.txt","r");

​ fp3=fopen("even.txt","r");

​ if(fp2==NULL||fp3==NULL)

​ {

​ ​ printf(" File could not open!! ");

​ ​ exit(0);
​ }

​ printf("\n Contents of ODD file: \n ");

​ while((a=getw(fp2))!=EOF) printf("%d ",a);

​ printf("\n Contents of EVEN file: \n ");

​ while((a=getw(fp3))!=EOF) printf("%d ",a);

​ fclose(fp2);

​ fclose(fp3);

Output:-
PROGRAM-38
/* WAP in C to show the use of all dynamic memory allocation and
deallocation functions.*/
#include <stdio.h>

#include <stdlib.h>

int main() {

​ int *ptr, *arr;

​ int n, i;

​ ptr = (int*)malloc(sizeof(int));

​ if (ptr == NULL) {

​ ​ printf("Memory allocation failed for ptr\n");

​ ​ return 1;

​ }

​ *ptr = 10;

​ printf("Value allocated by malloc: %d\n", *ptr);

​ printf("Enter the number of elements for calloc: ");

​ scanf("%d", &n);

​ arr = (int*)calloc(n, sizeof(int));

​ if (arr == NULL) {

​ ​ printf("Memory allocation failed for arr\n");

​ ​ free(ptr); // Freeing ptr to avoid memory leak

​ ​ return 1;

​ }
​ printf("Array initialized by calloc: ");

​ for (i = 0; i < n; i++) {

​ ​ printf("%d ", arr[i]);

​ }

​ printf("\n");

​ printf("Enter the new size for realloc: ");

​ scanf("%d", &n);

​ arr = (int*)realloc(arr, n * sizeof(int));

​ if (arr == NULL) {

​ ​ printf("Memory reallocation failed\n");

​ ​ free(ptr);

​ ​ return 1;

​ }

​ for (i = 0; i < n; i++) {

​ ​ arr[i] = i * 2;

​ }

​ printf("Array after realloc: ");

​ for (i = 0; i < n; i++) {

​ ​ printf("%d ", arr[i]);

​ }

​ printf("\n");

​ free(ptr);

​ free(arr);

​ printf("Memory deallocated successfully\n");

​ return 0;

}
Output:-
PROGRAM-39
/* Write a C Program to search a element in an array.*/
#include <stdio.h>

int main() {

​ int n, i, key, found = 0;

​ printf("Enter the size of the array: ");

​ scanf("%d", &n);

​ int arr[n];

​ printf("Enter %d elements:\n", n);

​ for (i = 0; i < n; i++) {

​ ​ printf("Element %d: ", i + 1);

​ ​ scanf("%d", &arr[i]);

​ }

​ printf("Enter the element to search: ");

​ scanf("%d", &key);

​ for (i = 0; i < n; i++) {

​ ​ if (arr[i] == key) {

​ ​ ​ found = 1;

​ ​ ​ break;

​ ​ }

​ }

​ if (found) {

​ ​ printf("Element %d found at position %d.\n", key, i + 1);

​ } else {
​ ​ printf("Element %d not found in the array.\n", key);

​ }

​ return 0;

Output;-
PROGRAM-40
/* Write a C Program to sort a element of an array.*/
#include <stdio.h>

int main() {

​ int n, i, j, temp;

​ printf("Enter the size of the array: ");

​ scanf("%d", &n);

​ int arr[n];

​ printf("Enter %d elements:\n", n);

​ for (i = 0; i < n; i++) {

​ ​ printf("Element %d: ", i + 1);

​ ​ scanf("%d", &arr[i]);

​ }

​ for (i = 0; i < n - 1; i++) {

​ ​ for (j = 0; j < n - i - 1; j++) {

​ ​ ​ if (arr[j] > arr[j + 1]) {

​ ​ ​ ​ temp = arr[j];

​ ​ ​ ​ arr[j] = arr[j + 1];

​ ​ ​ ​ arr[j + 1] = temp;

​ ​ ​ }

​ ​ }

​ }

​ printf("Sorted array in ascending order:\n");

​ for (i = 0; i < n; i++) {

​ ​ printf("%d ", arr[i]);

​ }
​ printf("\n");

​ return 0;

Output:-

You might also like