0% found this document useful (0 votes)
7 views77 pages

24213_Sarita File 1

The document is a practical file for the M.Sc. Computer Science program at Maharshi Dayanand University, detailing various C programming assignments related to data structures and algorithms. It includes tasks such as finding the largest and smallest elements in an array, implementing sorting algorithms, and demonstrating stack and queue operations. Each program is accompanied by code snippets and expected outputs.

Uploaded by

pardeep3007771
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)
7 views77 pages

24213_Sarita File 1

The document is a practical file for the M.Sc. Computer Science program at Maharshi Dayanand University, detailing various C programming assignments related to data structures and algorithms. It includes tasks such as finding the largest and smallest elements in an array, implementing sorting algorithms, and demonstrating stack and queue operations. Each program is accompanied by code snippets and expected outputs.

Uploaded by

pardeep3007771
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/ 77

MAHARSHI DAYANAND UNIVERSITY,

ROHTAK

PRACTICAL FILE
BASED ON
SOFTWARE LAB : 24MSCSCS202DS01
M.SC. COMPUTER SCIENCE

Submitted To : Submitted by :
Dr. Priti Sharma Sarita
Dr. Amrinder Kaur M.sc. Cs 2nd sem
Mr. Amit Dhaka Roll No. : 24213

1|Page
S.No. Program Page No.
1. Write a C program to declare and initialize an array, 3
then find and print the largest and smallest elements in
the array.
2. Write a C program to demonstrate basic data structure 4-6
operations such as creating, inserting, deleting, and
displaying elements in an array.
Write a C program to insert and delete an element at a 7-9
3. specified position in a linear array.
Write a C program to implement and demonstrate a 10
4. sequential search on an array.
Write a C program to implement and demonstrate a 11
5. binary search on a sorted array.
Write a C program to implement and demonstrate the 12
6. Bubble sort algorithm.
Write a C program to perform operations: push, pop, 13-14
7. and display.
Write a C program to implement a queue using an array 15-16
8. and perform basic queue operations: enqueue, dequeue,
and display.
Write a C program to implement and demonstrate the 17-18
9. Selection sort algorithm
Write a C program to implement and demonstrate the 19-20
10. Insertion sort algorithm.
Write a C program to implement and demonstrate the 21-22
11. Quick sort algorithm.
Write a C program to implement and demonstrate the 23-24
12. Merge sort algorithm.
Write a C program to implement a singly linked list and 25-27
13. perform insertion, deletion, and traversal operations.
Write a C program to implement a binary tree and 28-29
14. perform in-order, pre-order, and post-order traversal
using recursion.
Write a C program to implement a binary search tree 30-32
15. (BST) and perform insertion, deletion, and search
operations.

2|Pag e
1. Write a C program to declare and initialize an array, then find and print the
largest and smallest elements in the array.

#include <stdio.h>

int main() {
int n;
printf("Enter the number of elements: ");
scanf("%d", &n);

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

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


if (arr[i] > largest) {
largest = arr[i];
}
if (arr[i] < smallest) {
smallest = arr[i];
}
}
printf("Largest element: %d\n", largest);
printf("Smallest element: %d\n", smallest);

return 0;
}

Output

3|Pag e
2. Write a C program to demonstrate basic data structure operations such as
creating, inserting, deleting, and displaying elements in an array.

#include <stdio.h>
void display(int arr[], int n) {
if (n == 0) {
printf("Array is empty.\n");
} else {
printf("Array elements: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
}

void insert(int arr[], int *n, int element, int position) {


if (*n >= 100) {
printf("Array is full!\n");
} else if (position < 0 || position > *n) {
printf("Invalid position!\n");
} else {
for (int i = *n; i > position; i--) {
arr[i] = arr[i - 1];
}
arr[position] = element;
(*n)++;
printf("Element %d inserted at position %d.\n", element, position);
}
}

void delete(int arr[], int *n, int position) {


if (*n == 0) {
printf("Array is empty, nothing to delete.\n");
} else if (position < 0 || position >= *n) {
printf("Invalid position!\n");
} else {
for (int i = position; i < *n - 1; i++) {
arr[i] = arr[i + 1];
}
(*n)--;
printf("Element at position %d deleted.\n", position);

4|Pag e
}
}

int main() {
int arr[100], n = 0, choice, element, position;

while (1) {
printf("\nMenu:\n");
printf("1. Insert element\n");
printf("2. Delete element\n");
printf("3. Display array\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter element to insert: ");
scanf("%d", &element);
printf("Enter position to insert (0 to %d): ", n);
scanf("%d", &position);
insert(arr, &n, element, position);
break;

case 2:
printf("Enter position to delete (0 to %d): ", n - 1);
scanf("%d", &position);
delete(arr, &n, position);
break;

case 3:
display(arr, n);
break;

case 4:
return 0;

default:
printf("Invalid choice! Please try again.\n");
}
}

return 0;

5|Pag e
}

Output

6|Pag e
3. Write a C program to insert and delete an element at a specified
position in a linear array.
#include <stdio.h>

void insert(int arr[], int *n, int element, int position) {


if (*n >= 100) {
printf("Array is full!\n");
} else if (position < 0 || position > *n) {
printf("Invalid position!\n");
} else {
for (int i = *n; i > position; i--) {
arr[i] = arr[i - 1];
}
arr[position] = element;
(*n)++;
printf("Element %d inserted at position %d.\n", element, position);
}
}

void delete(int arr[], int *n, int position) {


if (*n == 0) {
printf("Array is empty, nothing to delete.\n");
} else if (position < 0 || position >= *n) {
printf("Invalid position!\n");
} else {
for (int i = position; i < *n - 1; i++) {
arr[i] = arr[i + 1];
}
(*n)--;
printf("Element at position %d deleted.\n", position);
}
}

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


if (n == 0) {
printf("Array is empty.\n");
} else {
printf("Array elements: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

7|Pag e
}

int main() {
int arr[100], n = 0, choice, element, position;

while (1) {
printf("\nMenu:\n");
printf("1. Insert element\n");
printf("2. Delete element\n");
printf("3. Display array\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter element to insert: ");
scanf("%d", &element);
printf("Enter position to insert (0 to %d): ", n);
scanf("%d", &position);
insert(arr, &n, element, position);
break;

case 2:
printf("Enter position to delete (0 to %d): ", n - 1);
scanf("%d", &position);
delete(arr, &n, position);
break;

case 3:
display(arr, n);
break;

case 4:
return 0;

default:
printf("Invalid choice! Please try again.\n");
}
}

return 0;
}

8|Pag e
Output

9|Pag e
4. Write a C program to implement and demonstrate a sequential search on
an array.

#include <stdio.h>
int sequentialSearch(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i;
}
}
return -1;
}
int main() {
int arr[] = {34, 78, 12, 56, 89, 23};
int n = sizeof(arr) / sizeof(arr[0]);
int key, result;
printf("Enter the element to search: ");
scanf("%d", &key);

result = sequentialSearch(arr, n, key);


if (result != -1) {
printf("Element %d found at index %d.\n", key, result);
} else {
printf("Element %d not found in the array.\n", key);
}

return 0;
}

Output

10 | P a g e
5. Write a C program to implement and demonstrate a binary search on a sorted array.
#include <stdio.h>
int binarySearch(int arr[], int n, int key) {
int low = 0, high = n - 1, mid;

while (low <= high) {


mid = low + (high - low) / 2;

if (arr[mid] == key) {
return mid;
}
else if (arr[mid] < key) {
low = mid + 1;
}
else {
high = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {12, 23, 34, 45, 56, 67, 78, 89};
int n = sizeof(arr) / sizeof(arr[0]);
int key, result;

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


scanf("%d", &key);

result = binarySearch(arr, n, key);


if (result != -1) {
printf("Element %d found at index %d.\n", key, result);
} else {
printf("Element %d not found in the array.\n", key);
}
return 0;
}
Output

11 | P a g e
6. Write a C program to implement and demonstrate the Bubble sort algorithm.
#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]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void display(int arr[], int n) {
printf("Array elements: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


display(arr, n);

bubbleSort(arr, n);

printf("Sorted array: ");


display(arr, n);
return 0;
}
Output

12 | P a g e
7. Write a C program to perform operations: push, pop, and display.
#include <stdio.h>
#include <stdlib.h>

#define MAX 5

struct Stack {
int arr[MAX];
int top;
};
void initStack(struct Stack* stack) {
stack->top = -1;
}
int isFull(struct Stack* stack) {
return stack->top == MAX - 1;
}
int isEmpty(struct Stack* stack) {
return stack->top == -1;
}
void push(struct Stack* stack, int value) {
if (isFull(stack)) {
printf("Stack Overflow\n");
} else {
stack->arr[++stack->top] = value;
}
}
void pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack Underflow\n");
} else {
printf("%d popped from stack\n", stack->arr[stack->top--]);
}
}

void display(struct Stack* stack) {


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

13 | P a g e
}
}

int main() {
struct Stack stack;
initStack(&stack);

push(&stack, 2);
push(&stack, 6);
push(&stack, 5);
push(&stack, 3);
display(&stack);
pop(&stack);
display(&stack);

return 0;
}

Output

14 | P a g e
8. Write a C program to implement a queue using an array and perform basic
queue operations: enqueue, dequeue, and display.

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

#define MAX 5

struct Queue {
int arr[MAX];
int front;
int rear;
};
void initQueue(struct Queue* queue) {
queue->front = -1;
queue->rear = -1;
}
int isFull(struct Queue* queue) {
return queue->rear == MAX - 1;
}
int isEmpty(struct Queue* queue) {
return queue->front == -1 || queue->front > queue->rear;
}
void enqueue(struct Queue* queue, int value) {
if (isFull(queue)) {
printf("Queue Overflow\n");
} else {
if (queue->front == -1) {
queue->front = 0;
}
queue->arr[++queue->rear] = value;
}
}
void dequeue(struct Queue* queue) {
if (isEmpty(queue)) {
printf("Queue Underflow\n");
} else {
printf("%d dequeued from queue\n", queue->arr[queue->front]);
queue->front++;
}
}
void display(struct Queue* queue) {
if (isEmpty(queue)) {

15 | P a g e
printf("Queue is empty\n");
} else {
printf("Queue elements: ");
for (int i = queue->front; i <= queue->rear; i++) {
printf("%d ", queue->arr[i]);
}
printf("\n");
}
}
int main() {
struct Queue queue;
initQueue(&queue);

enqueue(&queue, 10);
enqueue(&queue, 20);
enqueue(&queue, 30);
enqueue(&queue, 40);
enqueue(&queue, 50);
enqueue(&queue, 60);

display(&queue);
display(&queue);

enqueue(&queue, 60);
display(&queue);

return 0;
}
Output

16 | P a g e
9. Write a C program to implement and demonstrate the Selection sort
algorithm.

#include <stdio.h>

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


int i, j, minIndex, temp;

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


minIndex = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (minIndex != i) {
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
void display(int arr[], int n) {
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


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

display(arr, n);

return 0;

17 | P a g e
}

Output

18 | P a g e
10. Write a C program to implement and demonstrate the
Insertion sort algorithm.

#include <stdio.h>

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

int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;

while (j >= 0 && arr[j] > key) {


arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
void display(int arr[], int n) {

printf("Sorted array: ");

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


printf("%d ", arr[i]);
}
printf("\n");
}
int main() {

int arr[] = {64, 34, 25, 12, 22, 11};


int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");

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


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

insertionSort(arr, n);
display(arr, n);

19 | P a g e
return 0;
}

Output

20 | P a g e
11. Write a C program to implement and demonstrate the Quick sort
algorithm.
#include <stdio.h>

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


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

int partition(int arr[], int low, int high) {


int pivot = arr[high];
int i = low - 1;

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


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return i + 1;
}

void quickSort(int arr[], int low, int high) {


if (low < high) {
int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);


quickSort(arr, pi + 1, high);
}
}

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


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

int main() {
int arr[] = {64, 34, 25, 12, 22, 11};

21 | P a g e
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


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

quickSort(arr, 0, n - 1);

display(arr, n);

return 0;
}

Output

22 | P a g e
12. Write a C program to implement and demonstrate the Merge sort
algorithm.
#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 i = 0; i < n2; i++) {
R[i] = arr[mid + 1 + i];
}

int i = 0, j = 0, k = left;

while (i < n1 && j < n2) {


if (L[i] <= R[j]) {
arr[k++] = L[i++];
} else {
arr[k++] = R[j++];
}
}

while (i < n1) {


arr[k++] = L[i++];
}

while (j < n2) {


arr[k++] = R[j++];
}
}

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);

23 | P a g e
merge(arr, left, mid, right);
}
}

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


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

int main() {
int arr[] = {64, 34, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");


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

mergeSort(arr, 0, n - 1);

display(arr, n);

return 0;
}

Output

24 | P a g e
13. Write a C program to implement a singly linked list and
perform insertion, deletion, and traversal operations.

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

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

void insertAtEnd(struct Node** head, int value) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head;

newNode->data = value;
newNode->next = NULL;

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

while (last->next != NULL) {


last = last->next;
}

last->next = newNode;
}

void insertAtBeginning(struct Node** head, int value) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = *head;
*head = newNode;
}

void deleteNode(struct Node** head, int value) {


struct Node* temp = *head;
struct Node* prev = NULL;

if (temp != NULL && temp->data == value) {


*head = temp->next;

25 | P a g e
free(temp);
return;
}

while (temp != NULL && temp->data != value) {


prev = temp;
temp = temp->next;
}

if (temp == NULL) {
printf("Element not found\n");
return;
}

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

void traverseList(struct Node* head) {


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

struct Node* temp = head;


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

int main() {
struct Node* head = NULL;

insertAtEnd(&head, 10);
insertAtEnd(&head, 20);
insertAtEnd(&head, 30);
insertAtBeginning(&head, 5);

printf("Linked List: ");


traverseList(head);

26 | P a g e
deleteNode(&head, 20);
printf("After deleting 20: ");
traverseList(head);

deleteNode(&head, 100); // Element not found


printf("After attempting to delete 100: ");
traverseList(head);

return 0;
}

Output

27 | P a g e
14. Write a C program to implement a binary tree and perform in-
order, pre-order, and post-order traversal using recursion.
#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* left;
struct Node* right;
};

struct Node* createNode(int value) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = newNode->right = NULL;
return newNode;
}

void preOrder(struct Node* root) {


if (root == NULL) {
return;
}
printf("%d ", root->data);
preOrder(root->left);
preOrder(root->right);
}

void inOrder(struct Node* root) {


if (root == NULL) {
return;
}
inOrder(root->left);
printf("%d ", root->data);
inOrder(root->right);
}

void postOrder(struct Node* root) {


if (root == NULL) {
return;
}
postOrder(root->left);
postOrder(root->right);
printf("%d ", root->data);

28 | P a g e
}

int main() {
struct Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);
root->right->left = createNode(6);
root->right->right = createNode(7);

printf("Pre-order traversal: ");


preOrder(root);
printf("\n");

printf("In-order traversal: ");


inOrder(root);
printf("\n");

printf("Post-order traversal: ");


postOrder(root);
printf("\n");

return 0;
}

Output

29 | P a g e
15. Write a C program to implement a binary search tree (BST) and perform
insertion, deletion, and search operations.

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

struct Node {
int data;
struct Node* left;
struct Node* right;
};
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->left = newNode->right = NULL;
return newNode;
}

struct Node* insert(struct Node* root, int value) {


if (root == NULL) {
return createNode(value);
}

if (value < root->data) {


root->left = insert(root->left, value);
} else if (value > root->data) {
root->right = insert(root->right, value);
}

return root;
}

struct Node* search(struct Node* root, int value) {


if (root == NULL || root->data == value) {
return root;
}

if (value < root->data) {


return search(root->left, value);
}
return search(root->right, value);
}
struct Node* minNode(struct Node* root) {

30 | P a g e
struct Node* current = root;
while (current && current->left != NULL) {
current = current->left;
}
return current;
}
struct Node* delete(struct Node* root, int value) {
if (root == NULL) {
return root;
}
if (value < root->data) {
root->left = delete(root->left, value);
} else if (value > root->data) {
root->right = delete(root->right, value);
} else {
if (root->left == NULL) {
struct Node* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct Node* temp = root->left;
free(root);
return temp;
}
struct Node* temp = minNode(root->right);
root->data = temp->data;
root->right = delete(root->right, temp->data);
}
return root;
}
void inOrderTraversal(struct Node* root) {
if (root != NULL) {
inOrderTraversal(root->left);
printf("%d ", root->data);
inOrderTraversal(root->right);
}
}
int main() {
struct Node* root = NULL;

root = insert(root, 50);


root = insert(root, 30);
root = insert(root, 20);

31 | P a g e
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);

printf("In-order traversal: ");


inOrderTraversal(root);
printf("\n");

int searchValue = 40;


struct Node* searchResult = search(root, searchValue);
if (searchResult != NULL) {
printf("Node %d found in the BST.\n", searchValue);
} else {
printf("Node %d not found in the BST.\n", searchValue);
}

int deleteValue = 20;


printf("Deleting node %d...\n", deleteValue);
root = delete(root, deleteValue);

printf("In-order traversal after deletion: ");


inOrderTraversal(root);
printf("\n");

return 0;
}
Output

32 | P a g e
MAHARSHI DAYANAND UNIVERSITY,
ROHTAK

PRACTICAL FILE
BASED ON
SOFTWARE LAB : 24MSCSCS202DS02
M.SC. COMPUTER SCIENCE

Submitted To : Submitted by :
Dr. Priti Sharma Sarita
Dr. Amrinder Kaur M.sc. Cs 2nd sem
Mr. Amit Dhaka Roll No. : 24213

1|P age
S.No. Program Page No.
1. To understand and run basic UNIX/LINUX commands 3

2. To study of Basic Unix/Linux Commands and various 4


Unix/Linux editors such as vi, ed, ex and EMACS
To study basic file manipulation commands of Unix/Linux 5
3. commands

To write C Programs using the following system calls of 6-7


4. Unix/Linux operating system fork, exec, getpid, exit, wait.
To write C Programs using the following system calls of 8-9
5. Unix/Linux operating system close, stat, opendir, readdir.
To write C programs to simulate Unix/Linux commands like 10-12
6. cp, ls, grep
Write a Shell program to check the given number is even 13
7. or odd.
Write a Shell program to check the given year is leap year 14
8. or not
Write a Shell program to find the factorial of a number. 15
9.
Write a C program for implementation of Priority 16-17
10. scheduling algorithms.
To write a C program for implementation of Round Robin 18-19
11. scheduling algorithms
To write a C program for implementation of FCFS and SJF 20
12. scheduling algorithms.
To write a C program for implementation of SJF scheduling 21
13. algorithms
To write a C-program to implement the producer – 22-24
14. consumer problem using semaphores.
To write a C program to implement banker’s algorithm for 25-26
15. deadlock avoidance.

2|P age
Basic Linux Commands:-

ls command in Linux

pwd command in Linux

cd command in Linux

touch command in Linux

cat command in Linux

3|P age
echo command in Linux

4|P age
File Manipulation Commands: -

mkdir command in Linux

rmdir command in Linux

cp command of Linux .

mv command in Linux

rm command in Linux

5|P age
C Program Using system calls fork, exec, getpid, exit, wait
.
#include <stdio.h>
#include <string.h>

int main() {
// Simulate 'cp'
char source[] = "This is a test file.";
char destination[100];
strcpy(destination, source);
printf("Simulated cp:\n");
printf("Source Content: %s\n", source);
printf("Destination Content after copy: %s\n\n", destination);

// Simulate 'ls'
printf("Simulated ls:\n");
printf("main.c\nfile1.txt\nfile2.txt\nnotes.docx\nimage.png\n\n");

// Simulate 'grep'
char *lines[] = {
"This is a sample text file.",
"We are learning Linux commands.",
"grep is used to search text.",
"Enjoy coding in C.",
"Practice regularly for better understanding."
};
char keyword[] = "text";

printf("Simulated grep (search for word: '%s'):\n", keyword);


for (int i = 0; i < 5; i++) {
if (strstr(lines[i], keyword)) {
printf("%s\n", lines[i]);
}
}

return 0;
}

6|P age
7|P age
To write C Programs using the following system calls of Unix/Linux operating
system close, stat, opendir, readdir

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main() {
struct stat fileStat;
int fd;

// Demonstrate open and stat


fd = open("test.txt", O_RDONLY);
if (fd < 0) {
perror("open");
return 1;
}

if (fstat(fd, &fileStat) < 0) {


perror("stat");
return 1;
}

printf("File size: %ld bytes\n", fileStat.st_size);


printf("Number of links: %ld\n", fileStat.st_nlink);
printf("File inode: %ld\n", fileStat.st_ino);

// Close the file


close(fd);

// Demonstrate opendir and readdir


DIR *d;
struct dirent *dir;
d = opendir(".");
if (d == NULL) {
perror("opendir");
return 1;
}

printf("\nContents of current directory:\n");


while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);

return 0;
}
8|P age
Output

9|P age
C Program to system call cp, ls, grep-
#include <stdio.h>
#include <string.h>

int main() {
// Simulate 'cp'
char source[] = "This is a test file.";
char destination[100];
strcpy(destination, source);
printf("Simulated cp:\n");
printf("Source Content: %s\n", source);
printf("Destination Content after copy: %s\n\n", destination);

// Simulate 'ls'
printf("Simulated ls:\n");
printf("main.c\nfile1.txt\nfile2.txt\nnotes.docx\nimage.png\n\n");

// Simulate 'grep'
char *lines[] = {
"This is a sample text file.",
"We are learning Linux commands.",
"grep is used to search text.",
"Enjoy coding in C.",
"Practice regularly for better understanding."
};
char keyword[] = "text";

printf("Simulated grep (search for word: '%s'):\n", keyword);


for (int i = 0; i < 5; i++) {
if (strstr(lines[i], keyword)) {
printf("%s\n", lines[i]);
}
}

return 0;
}

10 | P a g
e
11 | P a g
e
12 | P a g
e
Write a Shell program to check the given number is even or odd.

#!/bin/bash

number=7

if [ $((number % 2)) -eq 0 ]


then
echo "$number is Even"
else
echo "$number is Odd"
fi

13 | P a g
e
Write a shell program to check given year is leap year or not

#!/bin/bash

year=2024

if (( (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ))


then
echo "$year is a Leap Year"
else
echo "$year is Not a Leap Year"
fi

14 | P a g
e
Shell Program to Find factorial-

#!/bin/bash

num=5
fact=1

for (( i=1; i<=num; i++ ))


do
fact=$((fact * i))
done

echo "Factorial of $num is $fact"

15 | P a g e
Write a C Program for implementation of priority scheduling algorithms

#include <stdio.h>

int main() {
int n = 4, i, j;
int pid[] = {1, 2, 3, 4};
int bt[] = {10, 5, 8, 6};
int pr[] = {2, 1, 4, 3};
int wt[4], tat[4];

// Sort based on priority


for(i = 0; i < n - 1; i++) {
for(j = i+1; j < n; j++) {
if(pr[i] > pr[j]) {
int temp = pr[i]; pr[i] = pr[j]; pr[j] = temp;
temp = bt[i]; bt[i] = bt[j]; bt[j] = temp;
temp = pid[i]; pid[i] = pid[j]; pid[j] = temp;
}
}
}

wt[0] = 0;
for(i = 1; i < n; i++)
wt[i] = bt[i-1] + wt[i-1];

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


tat[i] = wt[i] + bt[i];

printf("PID\tBT\tPR\tWT\tTAT\n");
for(i = 0; i < n; i++)
printf("P%d\t%d\t%d\t%d\t%d\n", pid[i], bt[i], pr[i], wt[i], tat[i]);

return 0;
}

16 | P a g e
OUTPUT

17 | P a g e
To write a C program for implementation of Round Robin scheduling algorithms

#include <stdio.h>

int main() {
int n = 4, tq = 3;
int bt[] = {5, 15, 4, 3};
int wt[4] = {0}, tat[4], rem_bt[4];
int i, time = 0;

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


rem_bt[i] = bt[i];

while(1) {
int done = 1;
for(i = 0; i < n; i++) {
if(rem_bt[i] > 0) {
done = 0;
if(rem_bt[i] > tq) {
time += tq;
rem_bt[i] -= tq;
} else {
time += rem_bt[i];
wt[i] = time - bt[i];
rem_bt[i] = 0;
}
}
}
if(done) break;
}

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


tat[i] = wt[i] + bt[i];

printf("PID\tBT\tWT\tTAT\n");
for(i = 0; i < n; i++)
printf("P%d\t%d\t%d\t%d\n", i+1, bt[i], wt[i], tat[i]);

return 0;
}

18 | P a g e
OUTPUT

19 | P a g e
To write a C program for implementation of FCFS and SJF scheduling algorithms.

#include <stdio.h>

// Function to perform FCFS Scheduling


void fcfs() {
int n = 4;
int bt[] = {6, 8, 7, 3};
int wt[4], tat[4];

wt[0] = 0;
for (int i = 1; i < n; i++)
wt[i] = bt[i - 1] + wt[i - 1];

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


tat[i] = wt[i] + bt[i];

printf("\n--- FCFS Scheduling ---\n");


printf("PID\tBT\tWT\tTAT\n");
for (int i = 0; i < n; i++)
printf("P%d\t%d\t%d\t%d\n", i + 1, bt[i], wt[i], tat[i]);
}

// Function to perform SJF Scheduling


void sjf() {
int n = 4;
int bt[] = {6, 8, 7, 3};
int wt[4], tat[4], i, j;

// Sort burst time (SJF)


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

wt[0] = 0;
for (i = 1; i < n; i++)
wt[i] = wt[i - 1] + bt[i - 1];

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


tat[i] = wt[i] + bt[i];

printf("\n--- SJF Scheduling ---\n");


printf("PID\tBT\tWT\tTAT\n");
for (i = 0; i < n; i++)
printf("P%d\t%d\t%d\t%d\n", i + 1, bt[i], wt[i], tat[i]);
}
20 | P a g e
int main() {
fcfs();
sjf();
return 0;
}

Output

21 | P a g e
C Program to implement Producer-Consumer Problem Using Semaphores
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>

#define SIZE 5

int buffer[SIZE];
int in = 0, out = 0;

sem_t empty, full;


pthread_mutex_t mutex;

void* producer(void* arg) {


int item;
for (int i = 0; i < 10; i++) {
item = i + 1;
sem_wait(&empty);
pthread_mutex_lock(&mutex);

buffer[in] = item;
printf("Producer produced item %d at position %d\n", item, in);
in = (in + 1) % SIZE;

pthread_mutex_unlock(&mutex);
sem_post(&full);
sleep(1);
}
return NULL;
}

void* consumer(void* arg) {


int item;
for (int i = 0; i < 10; i++) {
sem_wait(&full);
pthread_mutex_lock(&mutex);

item = buffer[out];
printf("Consumer consumed item %d from position %d\n", item, out);
out = (out + 1) % SIZE;

pthread_mutex_unlock(&mutex);
sem_post(&empty);
sleep(2);
}
return NULL;
}

int main() {
pthread_t prod, cons;
22 | P a g e
sem_init(&empty, 0, SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL);

pthread_create(&prod, NULL, producer, NULL);


pthread_create(&cons, NULL, consumer, NULL);

pthread_join(prod, NULL);
pthread_join(cons, NULL);

sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);

return 0;
}

23 | P a g e
Output

24 | P a g e
C Program to Implement Banker,s Algorithm for Deadlock Avoidance

#include <stdio.h>
#define P 5 // Number of processes
#define R 3 // Number of resources

int main() {
int alloc[P][R] = { {0, 1, 0}, {2, 0, 0}, {3, 0, 2}, {2, 1, 1}, {0, 0, 2} };
int max[P][R] = { {7, 5, 3}, {3, 2, 2}, {9, 0, 2}, {2, 2, 2}, {4, 3, 3} };
int avail[R] = {3, 3, 2};

int need[P][R], finish[P], safeSeq[P], count = 0;

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


for (int j = 0; j < R; j++)
need[i][j] = max[i][j] - alloc[i][j];
finish[i] = 0;
}

while (count < P) {


int found = 0;
for (int p = 0; p < P; p++) {
if (!finish[p]) {
int j;
for (j = 0; j < R; j++)
if (need[p][j] > avail[j])
break;

if (j == R) {
for (int k = 0; k < R; k++)
avail[k] += alloc[p][k];
safeSeq[count++] = p;
finish[p] = 1;
found = 1;
}
}
}

if (!found) {
printf("System is not in a safe state.\n");
return 0;
}
}

printf("System is in a safe state.\nSafe sequence is: ");


for (int i = 0; i < P; i++)
printf("P%d ", safeSeq[i]);
printf("\n");

return 0;
}

25 | P a g e
Output

26 | P a g e
MAHARSHI DAYANAND UNIVERSITY,
ROHTAK

PRACTICAL FILE
BASED ON
SOFTWARE LAB : 24MSCSCS202DS03
M.SC. COMPUTER SCIENCE

Submitted To : Submitted by :
Dr. Priti Sharma Sarita
Dr. Amrinder Kaur M.sc. Cs 2nd sem
Mr. Amit Dhaka Roll No. : 24213

1|Page
S.No. Program Page No.
1. Write a C++ program to take two numbers as input from 3
the user and display their sum.
2. Write a C++ program to demonstrate decision-making 4
constructs like if-else and looping constructs like for and
while loops.
Write a C++ program to define a class called `Rectangle` 5
3. with attributes `length` and `width`, and display the area of
the rectangle.
Write a C++ program to demonstrate the concept of 6
4. inheritance by creating a base class `Shape` and derived
class `Rectangle`. Display the area of the rectangle using
inheritance.
Write a C++ program to define a class called `Student` with 7
5. attributes `name` and `roll number`. Use member functions
to input and display student details.
Write a C++ program to demonstrate the use of constructor 8
6. and destructor in a class.
Write a C++ program to showcase the use of access 9-10
7. specifiers (`public`, `private`, `protected`) in a class.
Write a C++ program to demonstrate function overloading 11
8. by defining multiple functions with the same name but
different parameters.
Write a C++ program to demonstrate dynamic 12
9. polymorphism using virtual functions.
Write a C++ program to demonstrate the working of friend 13
10. function.
.Write a C++ program to demonstrate the use of pointers to 14
11. objects. Define a class `Book` with attributes `title` and
`author`, and use pointers to access and display book
details.
Write a C++ program to handle exceptions using `try- 15
12. catch` blocks.
Write C++ code to implement a simple template function to 16
13. find the maximum of two numbers. Test the function with
different data types.
Write a C++ program to perform file input and output 17
14. operations, including opening, reading, writing, and closing
files.
Implement error handling during file operations in a C++ 18-19
15. program, including handling exceptions and error codes.

2|Page
1. Write a C++ program to take two numbers as input from the user and
display their sum.

#include <iostream>
using namespace std;
int main() {
double num1, num2, sum;

cout << "Enter the first number: ";


cin >> num1;

cout << "Enter the second number: ";


cin >> num2;

sum = num1 + num2;

cout << "The sum of " << num1 << " and " << num2 << " is " << sum << sendl;

return 0;
}

3|Page
2. Write a C++ program to demonstrate decision-making constructs like if-
else and looping constructs like for and while loops.

#include <iostream>
using namespace std;
int main() {
int number;

cout << "Enter a number: ";


cin >> number;

if (number % 2 == 0) {
cout << number << " is even." << endl;
} else {
cout << number << " is odd." << endl;
}
cout << "\nCounting from 1 to 5 using for loop:" << endl;
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
cout << "\n\nCounting down from 5 to 1 using while loop:" << endl;
int count = 5;
while (count >= 1) {
cout << count << " ";
count--;
}

cout << endl;


return 0;
}

4|Page
3. Write a C++ program to define a class called `Rectangle` with attributes
`length` and `width`, and display the area of the rectangle.

#include <iostream>
using namespace std;
class Rectangle{
public :
int length, width;

void get(){
cout<<"Enter length and width of Rectangle :";
cin>>length>>width;
}

void area(){
cout<<"Area of Rectangle = "<<length*width;
}
};
int main() {

Rectangle r;
r.get();
r.area();

return 0;
}

5|Page
4. Write a C++ program to demonstrate the concept of inheritance by
creating a base class `Shape` and derived class `Rectangle`. Display the
area of the rectangle using inheritance.

#include <iostream>
using namespace std;
class Shape {
protected:
double length;
double width;

public:
void set(double l, double w) {
length = l;
width = w;
}
};
class Rectangle : public Shape {
public:
double getArea() {
return length * width;
}
};
int main() {
Rectangle rect;
int l, w;

cout << "Enter length: ";


cin >> l;
cout << "Enter width: ";
cin >> w;

rect.set(l, w);
cout<< "Area of the rectangle: "<< rect.getArea()<<endl;

return 0;
}

6|Page
5. Write a C++ program to define a class called `Student` with attributes
`name` and `roll number`. Use member functions to input and display
student details.

#include <iostream>
#include <string>
using namespace std;

class Student {
private:
string name;
int rollNumber;

public:
void inputDetails() {
cout << "Enter name: ";
getline(cin, name);

cout << "Enter roll number: ";


cin >> rollNumber;
}
void displayDetails() {
cout << "\nStudent Details:" << endl;
cout << "Name: " << name << endl;
cout << "Roll Number: " << rollNumber << endl;
}
};
int main() {
Student s;
s.inputDetails();
s.displayDetails();

return 0;
}

7|Page
6. Write a C++ program to demonstrate the use of constructor and
destructor in a class.
#include <iostream>
using namespace std;

class Demo {
public:
Demo() {
cout << "Constructor called" << endl;
}

~Demo() {
cout << "Destructor called" << endl;
}

void display() {
cout << "Hello from display function" << endl;
}
};

int main() {
Demo obj;
obj.display();
return 0;
}

8|Page
7. Writea C++ program to showcase the use of access specifiers (`public`,
`private`, `protected`) in a class.

#include <iostream>
using namespace std;

class A {
private:
int privateVar;

protected:
int protectedVar;

public:
int publicVar;

A() {
privateVar = 1;
protectedVar = 2;
publicVar = 3;
}
void show() {
cout << "Private Variable: " << privateVar << endl;
cout << "Protected Variable: " << protectedVar << endl;
cout << "Public Variable: " << publicVar << endl;
}
};
class B : public A {
public:
void showDerivedAccess() {
// cout << privateVar << endl; // Not accessible
cout << "Protected Variable (from Derived): " << protectedVar << endl;
cout << "Public Variable (from Derived): " << publicVar << endl;
}
};

int main() {

B Obj;
Obj.show();

9|Page
Obj.showDerivedAccess();
cout << "Accessing public variable from main: " << Obj.publicVar << endl;

return 0;
}

10 | P a g e
8. Write a C++ program to demonstrate function overloading by defining
multiple functions with the same name but different parameters.
#include <iostream>
using namespace std;

class Calculator {
public:
void add(int a, int b) {
cout << "Sum of two integers: " << a + b << endl;
}

void add(double a, double b) {


cout << "Sum of two doubles: " << a + b << endl;
}

void add(int a, int b, int c) {


cout << "Sum of three integers: " << a + b + c << endl;
}
};

int main() {
Calculator calc;
calc.add(5, 10);
calc.add(3.5, 2.5);
calc.add(1, 2, 3);
return 0;
}

11 | P a g e
9. Write a C++ program to demonstrate dynamic polymorphism using virtual
functions.
#include <iostream>
using namespace std;

class Animal {
public:
virtual void sound() {
cout << "Animal makes a sound" << endl;
}
};
class Dog : public Animal {
public:
void sound() override {
cout << "Dog barks" << endl;
}
};
class Cat : public Animal {
public:
void sound() override {
cout << "Cat meows" << endl;
}
};
int main() {
Animal* animal;
Dog dog;
Cat cat;

animal = &dog;
animal->sound();

animal = &cat;
animal->sound();
return 0;
}

12 | P a g e
10. Write a C++ program to demonstrate the working of friend function.
#include <iostream>
using namespace std;

class Box {
private:
int length;

public:
Box() {
length = 0;
}

void setLength(int l) {
length = l;
}

friend void printLength(Box b);


};

void printLength(Box b) {
cout << "Length of box: " << b.length << endl;
}

int main() {
Box box;
box.setLength(15);
printLength(box);
return 0;
}

13 | P a g e
11. Write a C++ program to demonstrate the use of pointers to objects.
Define a class `Book` with attributes `title` and `author`, and use pointers
to access and display book details.

#include <iostream>
using namespace std;

class Book {
public:
string title;
string author;

void setDetails(string t, string a) {


title = t;
author = a;
}

void display() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
}
};

int main() {
Book book1;
Book* ptr;

ptr = &book1;

ptr->setDetails("The Great Gatsby", "F. Scott Fitzgerald");


ptr->display();

return 0;
}

14 | P a g e
12. Write a C++ program to handle exceptions using `try-catch` blocks.
#include <iostream>
using namespace std;

int main() {
int a, b;
cout << "Enter two integers (a and b): ";
cin >> a >> b;

try {
if (b == 0) {
throw "Division by zero is not allowed.";
}
cout << "Result: " << a / b << endl;
}
catch (const char* msg) {
cout << "Exception caught: " << msg << endl;
}
return 0;
}

15 | P a g e
13. Write C++ code to implement a simple template function to find the
maximum of two numbers. Test the function with different data types.

#include <iostream>
using namespace std;

template <typename T>


T getMax(T a, T b) {
return (a > b) ? a : b;
}

int main() {
cout << "Max of 10 and 20: " << getMax(10, 20) << endl;
cout << "Max of 3.5 and 2.7: " << getMax(3.5, 2.7) << endl;
cout << "Max of 'A' and 'Z': " << getMax('A', 'Z') << endl;
cout << "Max of \"Apple\" and \"Banana\": " << getMax(string("Apple"), string("Banana")) <<
endl;

return 0;
}

16 | P a g e
14. Write a C++ program to perform file input and output operations,
including opening, reading, writing, and closing files.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
ofstream outFile("sample.txt");
if (outFile.is_open()) {
outFile << "Hello, world!\n";
outFile << "File operations in C++.\n";
outFile.close();
} else {
cout << "Error: Cannot create file for writing." << endl;
return 1;
}

ifstream inFile("sample.txt");
if (inFile.is_open()) {
string line;
while (getline(inFile, line)) {
cout << line << endl;
}
inFile.close();
} else {
cout << "Error: Cannot open file for reading." << endl;
return 1;
}

return 0;
}

17 | P a g e
15. Implement error handling during file operations in a C++ program,
including handling exceptions and error codes.

#include <iostream>
#include <fstream>
#include <stdexcept> // for exceptions
using namespace std;

int main() {
const char* filename = "sample.txt";
ofstream outFile;

try {
outFile.open(filename, ios::out);
if (!outFile) {
throw runtime_error("Error opening file for writing");
}

outFile << "Writing some data to the file.\n";


outFile << "C++ file handling with error handling!\n";

outFile.close(); // Close file after writing

if (outFile.is_open()) {
throw runtime_error("Error closing the file after writing.");
}

ifstream inFile(filename);
if (!inFile) {
throw runtime_error("Error opening file for reading.");
}

string line;
while (getline(inFile, line)) {
cout << line << endl; // Print each line
}
inFile.close(); // Close the file after reading

if (inFile.is_open()) {

18 | P a g e
throw runtime_error("Error closing the file after reading.");
}
}
catch (const ios_base::failure& e) {
cerr << "File I/O error: " << e.what() << endl;
}
catch (const runtime_error& e) {
cerr << "Runtime error: " << e.what() << endl;
}
catch (const exception& e) {
cerr << "Unexpected error: " << e.what() << endl;
}

return 0;
}

19 | P a g e

You might also like