0% found this document useful (0 votes)
14 views83 pages

DSAMANUAL

The document is a lab manual for the Diploma in Artificial Intelligence & Machine Learning program, focusing on Data Structures and Algorithms. It outlines various practical exercises related to C programming, including pointer operations, file handling, linked lists, stacks, queues, sorting algorithms, searching techniques, hashing, and tree operations. Additionally, it includes project ideas and detailed instructions for setting up the programming environment and executing C programs.
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)
14 views83 pages

DSAMANUAL

The document is a lab manual for the Diploma in Artificial Intelligence & Machine Learning program, focusing on Data Structures and Algorithms. It outlines various practical exercises related to C programming, including pointer operations, file handling, linked lists, stacks, queues, sorting algorithms, searching techniques, hashing, and tree operations. Additionally, it includes project ideas and detailed instructions for setting up the programming environment and executing C programs.
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/ 83

Government Technical Training Centre (GTTC)

Lab Manual

Diploma
in
Artificial Intelligence
& Machine Learning(DAIML)

Semester 2

DATA STRUCTURES AND


ALGORITHMS LAB
MANUAL
Hrs./Week-6
Subject Code: 24AI21P
CONTENT
# Practical Tittle Hours

i OS Installation on VM/Partition

Pointer Basics & Dynamic Memory Allocation Basic Pointer


Operations:
a. C program to create, initialize and use pointers.
b. C program to add two numbers using pointers.
c. C program to swap two numbers using pointers.

Array Operations with Pointers:


1 a. C program to input and print array elements using pointer. 12
b. C program to copy one array to another using pointer.

Dynamic Memory Allocation with Pointers:


a. C program that dynamically allocates memory for an array of integers,
initializes it with user input, and displays the sum of the elements.
b. C program that dynamically allocates memory for a string and stores the
user-inputted string. Then, it displays the string in reverse order.

Files
File Creation, Writing, Reading, and Appending:
a. C program to create a file and write contents, save, and close the file.
b. C program to read file contents and display on the console.
c. C program to append content to a file.

2 12
File Manipulation and Comparison:
a. C program to read numbers from a file and write even, odd, and prime
numbers to separate files.
b. C program to compare two files.
c. C program to copy contents from one file to another file.
d.C program to remove a word from a text file.

i
Linked list
Singly Linked list implementation:
a. C program to traverse, insert, delete, reverse and search an element
using singly linked list.
3 12
Doubly Linked list implementation:
a. C program to traverse, insert, delete, reverse using doubly linked list.

Circular Linked list implementation:


a. C program to implement the circular linked list.

Stack
Stack Implementation:
a. C program to implement stack operations.

Postfix to Infix Conversion:


4 12
a. C program to convert infix to postfix using an array-based stack.
b. C program to convert infix to postfix using stack.
c. C program to convert postfix to infix using a stack.

Queue
Queue Implementations:
a. C program to implement a queue using a linked list.
5 b. C program to implement a queue using arrays. 12

Priority Queue Implementation:


a. C Program to Implement Priority Queue to Add and Delete Elements

Sorting
Basic Sorting Algorithms:
a. C Program to sort an array using Bubble Sort technique.
6 b. C Program to sort an array in ascending order using Insertion Sort. 12
c. C Program to sort an array of integers using Quick Sort.
d. C Program to Implement Selection Sort.
e. C Program to Perform Merge Sort using Recursion and Functions.

ii
Recursive Implementations and Other Sorts:
a. Bubble Sort Program in C using recursion.
b. C Program to sort an array in ascending order using Insertion Sort
using a separate function.
c. C program to perform Quick sort on a user provided array using
recursion.
d. C Program to Implement Selection Sort using Recursion.

Searching
Linear Search Operations:
a. C program to input N numbers and store them in an array. Do a
linear search for a given key and report success or failure.
7 b. C program to find the position of an element using linear search. 12

Recursive Search Algorithms:


a. C Program to implement Linear Search Algorithm recursively.
b. C Program to Perform Binary Search using Recursion.

Hashing
Setting up the Hash Table and Basic Operations:
a. C program to create a hash table and perform operations to insert,
8 search, and delete an element in the hash table. 12

Deleting the Entire Hash Table:


a. C program to delete the entire hash table.

Tree
Binary Tree Operations and Traversals:
a. C program to implement Binary Tree operations like insertion,
deletion, and traversal (in-order, pre-order, post- order) of nodes in the
tree.
9 12

Binary Search Tree Operations and Traversals:


a. C program to implement Binary Search Tree (BST) operations such
as insertion, deletion, and traversal (in-order, pre-order, post-order) of
nodes in the tree.

iii
1.Title: To-Do List Application:
Create a to-do list app that allows users to add, update, and delete
tasks. Implement data structures like linked lists to manage the tasks
efficiently. You can also add features like setting due dates and task
priorities.

2.Title: Simple Calculator:


Build a basic calculator application capable of performing arithmetic
operations. Implement stacks to handle expressions, and enhance it
by adding a history feature that shows previous calculations.
10 20
3.Title: Library Management System:
Design a system to manage a library’s inventory, including adding,
deleting, and updating books. Employ data structures such as arrays
to organize the data effectively and add a feature to generate due date
reminders.

4.Title: Banking System using Queues:


Build a simple banking system simulation using queues. Implement
functionalities like adding customers to the queue (bank line), serving
customers, and managing the queue based on different criteria.

iv
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

i OS Installation on VM/Partition Hours Allotted: 2

Objectives : Installing an operating system on a virtual machine or a separate partition.

1. Installing Code Blocks

1.1 On Windows :

1.Open your web browser and navigate to the official Python website:
https://www.codeblocks.org/downloads/

2.Click on the Download Python button to get the latest version.

5
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

3.Runs the installer once downloaded.

4.After launching the installer, the setup wizard will appear on screen. To continue, click the
"Next" button.

5.Read the Software Agreement. Read the end user license agreement. After reading, click "I
Agree" if you agree to the terms and want to install the software.

6
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

6.Choose your components: Make sure that "Full" installation is selected from the drop down
menu at the top; this includes all necessary software components. After this is done, click
"Next" to continue.

7.Choose the install path: By default, Code Blocks will install under C:\Program Files
(x86)\Code Blocks\. If you want to use this, click "Install", otherwise, use the "Browse" button
to select a custom install path before starting install.

7
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

8.Wait for the installation to complete : The installation will take several minutes to complete
and will show its progress in the window.

9.Finish the installation : When prompted, do not run Code::Blocks. First, complete install
wizard. This is done by clicking the "Next" button on the installer screen, then clicking
"Finish" on the completion page.

8
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Setting Up Your C File :

1.Launch Code::Blocks. To launch the program, double click the Code Blocks icon the
installer placed on your desktop. If you do not have a desktop shortcut, the program can be
found under Start--> All Programs ---> Code::Blocks --> CodeBlocks.exe

2.Complete the compiler setup. If prompted, accept GNU GCC Compiler as the default. To do
this, click the entry for GNU GCC Compiler, then click "Set as Default". To continue, click
"OK".

9
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

3. Set file associations. If prompted, select the option to associate Code::Blocks with C and
C++ file types, then click "OK". This will allow you to open these types of files in
Code::Blocks by default.

4.Create a new project. On the main page, select the link next to the folder icon. This will open
a new window in which you will set up your project.

10
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

5.Choose your project type: On the "New from Template" window, select the "Files" heading
on the left side of the window. Then, select the "C/C++ Source" option. Click "Go" to
continue

6.Use the Empty File Wizard : Use the wizard to create and configure your C file. To continue,
click "Next".

11
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

7.Choose your file type : Select the option to create a "C" file. Once selected, click the "Next"
button to continue.

8.Set the file path : Click the "..." button on the setup menu to open the explorer window to
allow you to create your C file.

12
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

9.Select file name : First, browse to the location you wish to save your C file in (it is
recommended that you make a separate folder for each project). Next, choose a name for
your C file. Finally, click "Save" to save your file with the name and location specified.

10.Finish using the File Wizard : To confirm creation of your C file, click "Finish".

13
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Creating a Simple C Program:


1. Enter source code : To create your "Hello World" program.

2.Run the program: Click the "Build and Run" icon to run your program. This function
compiles then runs your program in one convenient step.

14
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

3. View the program : After running, a terminal window will pop up with the message "Hello
World." The process should return 0. If a different value appears, there may be an issue with
your program. The execution time will vary based on the speed of your computer

15
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

C program to create, initialize and use


Experiment No. 1a Hours Allotted: 2
pointers.

Objectives : C program to create, initialize and use pointers.

Theory :
Pointers are variables that store the address of other variables. They allow indirect access to
memory, enabling flexible data manipulation. The dereference operator (*) retrieves the value
stored at the memory address, while the address-of operator (&) fetches the address of a variable

Equipment/Components :

# Equipment/Components Specification

1 Computer/Laptop CodeBlocks installed

2 C IDE/Interpreter Code::Blocks 20:03


3 Libraries stdio.h

Procedure :
Write the code in a C file (e.g., pointers_basics.c).
Compile the program using a C compiler.
Execute the code and observe the output.
Review the output, paying attention to the displayed address and the value accessed via the
pointer.
Algorithm :
Step 1: Start the program.
Step 2 : Declare an integer variable num and assign it a value.
Step 3: Declare a pointer variable ptr of type int *.
Step 4: Assign the address of num to the pointer ptr using the address-of operator (&).
Step 5: Print the address of num using ptr.
Step 6 : Access the value of num by dereferencing ptr using the * operator.
Step 7 : Print the value of num obtained through the pointer.
Step 8: End the program.

16
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Flowchart :

Code :

#include <stdio.h>
int main() {
int num = 10; // Declare and initialize variable
int *ptr = &num; // Initialize pointer with the address of 'num'

printf("Address of num: %p\n", ptr);


printf("Value of num using pointer: %d\n", *ptr);

return 0;
}

Output :
Address of num: 0061FF18
Value of num using pointer:10

17
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Observations :
Pointers store the memory address of variables, allowing indirect access to their values. The
address-of operator (&) fetches a variable's address, while the dereference operator (*) retrieves
the value at that address. Modifying the value via the pointer directly changes the original
variable, demonstrating memory manipulation.

Learning/Interpretation:

1: What is a pointer in C?
Answer : A pointer in C is a variable that holds the memory address of another variable.
2: How do you declare a pointer in C?
Answer : A pointer is declared using the * operator. For example, int *ptr; declares a pointer to
an integer.
3: What is the role of the address-of operator (&) in C?
Answer : The address-of operator (&) is used to retrieve the memory address of a variable.
4: What is the purpose of the dereference operator (*)?
Answer : The dereference operator (*) is used to access or modify the value stored at the memory
address the pointer is pointing to.
5: What happens if you dereference an uninitialized pointer?
Answer : Dereferencing an uninitialized pointer leads to undefined behavior and can cause the
program to crash.
6: How do pointers contribute to program efficiency?
Answer : Pointers allow direct access to memory, minimizing data copying and enhancing
performance when working with arrays, structures, and dynamic memory.

Inference:

Date of Score: Write Score: Score: Total Score: Signature:


Completion Up Learning/ 5S/5 ------/15
(Neatness)/5 5

18
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

C program to add two numbers using


Experiment No. 1b Hours Allotted: 2
pointers.

Objectives : C program to add two numbers using pointers.

Theory :
In this program, pointers will be used to store the addresses of two integer variables, retrieve their
values, and calculate their sum.
Pointer Declaration: A pointer is declared using the * symbol. For example, int *ptr; defines a
pointer capable of holding the address of an integer.
Dereferencing: The dereference operator (*) allows us to access the value stored at the memory
address the pointer is referencing.
Address-of Operator: The & operator is used to get the memory address of a variable.

Equipment/Components :
# Equipment/Components Specification

1 Computer/Laptop CodeBlocks installed

2 C IDE/Interpreter Code::Blocks 20:03


3 Libraries stdio.h

Procedure :
Write the code in a C file (e.g., pointers_basics.c).
Compile the program using a C compiler.
Execute the code and observe the output.
Review the output, paying attention to the displayed address and the value accessed via the
pointer.

Algorithm :
Step 1 : Start the program.
Step 2 : Declare two integer variables, a and b, for storing the numbers.
Step 3 : Declare two pointers, ptr1 and ptr2, of type int * to store the addresses of a and b.
Step 4 : Input the values for a and b from the user.
Step 5 : Assign the addresses of a and b to ptr1 and ptr2 respectively using the address-of operator
(&).
Step 6: Print the value and type of float_num.
Step 7 : Dereference ptr1 and ptr2 to get the values of a and b.
Step 8 : Add the values obtained through the pointers and store the result in the variable sum.
Step 9 : Print the sum.
Step 10 : End the program.
19
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Flowchart :

Code :
#include <stdio.h>
int main() {
int a, b, sum; // Declare integer variables for the numbers and sum
int *ptr1, *ptr2; // Declare pointer variables to store addresses of a and b
// Input two numbers from the user
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
// Assign addresses of a and b to ptr1 and ptr2
ptr1 = &a;
ptr2 = &b;
// Dereference ptr1 and ptr2 to get the values of a and b, and add them
sum = *ptr1 + *ptr2;
// Print the sum
printf("Sum of %d and %d is %d\n", a, b, sum);
return 0;
}

20
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Output :
Enter two numbers: 5 7
Sum of 5 and 7 is 12

Observations:
Pointers Store Addresses: ptr1, ptr2, and ptrSum hold the addresses of num1, num2, and
sum.
Input via Pointers: scanf directly stores values into num1 and num2 using their pointers.
Dereferencing for Operations: *ptrSum = *ptr1 + *ptr2 accesses values stored at addresses
for addition.
Direct Memory Access: Pointers interact with memory efficiently, avoiding extra variables.
Concise Code: Reusing pointers simplifies operations and improves readability.

Learning/Interpretation:
1: What is the purpose of using pointers in this program?
Answer : The purpose of using pointers in this program is to access the memory addresses of the
variables a and b, dereference them to retrieve their values, and perform arithmetic operations
(addition) using those values. Pointers allow indirect access to the variables.

2: How are the values of a and b accessed in this program using pointers?
Answer : The values of a and b are accessed through their respective pointers (ptr1 and ptr2) by
dereferencing them using the * operator. For example, *ptr1 accesses the value of a, and *ptr2
accesses the value of b.

3: What happens when we use the dereference operator (*) in this program?
Answer : When we use the dereference operator (*) in this program, it allows us to access the value
stored at the memory address the pointer is pointing to. For instance, *ptr1 gives the value stored
at the address of a, and *ptr2 gives the value stored at the address of b.

21
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

4: How is the sum of a and b computed in this program?


Answer : The sum of a and b is computed by dereferencing the pointers ptr1 and ptr2 to get the
values of a and b, respectively, and then adding them together. The result is stored in the variable
sum.

5: Why is the & operator used in this program?


Answer : The & operator is used to obtain the memory address of variables a and b. These
addresses are then assigned to the pointer variables ptr1 and ptr2 so that the program

6: What is the significance of using pointers in the context of larger programs?


Answer : In larger programs, pointers are crucial for dynamic memory management, passing large
data structures efficiently (e.g., arrays, structures, or linked lists), and manipulating data directly
in memory. They reduce memory usage by avoiding data duplication and increase performance by
enabling more direct memory access. Pointers are also essential for system-level programming and
low-level operations, such as interacting with hardware.

Inference:

Date of Score: Write Score: Score: Total Score: Signature:


Completion Up Learning/ 5S/5 ------/15
(Neatness)/5 5

22
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

C program to swap two numbers using


Experiment No. 1c pointers. Hours Allotted: 2

Objectives : C program to swap two numbers using pointers.

Theory :
In this program, pointers are used to store the addresses of two integer variables. The values at
these memory addresses will be swapped using the dereferencing technique.
Pointer Declaration: A pointer is declared using the * symbol. For example, int *ptr; defines a
pointer capable of holding the address of an integer.
Dereferencing: The dereference operator (*) allows us to access the value stored at the
memory address the pointer is referencing.
Address-of Operator: The & operator is used to get the memory address of a variable.

Equipment/Components :

# Equipment/Components Specification

1 Computer/Laptop CodeBlocks installed

2 C IDE/Interpreter Code::Blocks 20:03


3 Libraries stdio.h

Procedure :
Write the code in a C file (e.g., pointers_basics.c).
Compile the program using a C compiler.
Execute the code and observe the output.
Review the output, paying attention to the displayed address and the value accessed via the
pointer.
Algorithm :
Step 1: Start the program.
Step 2: Declare two integer variables, a and b, for storing the numbers.
Step 3: Declare two pointers, ptr1 and ptr2, of type int * to store the addresses of a and b.
Step 4: Input the values for a and b from the user.
Step 5: Assign the addresses of a and b to ptr1 and ptr2 respectively using the address-of
operator (&).
Step 6: Print the value and type of float_num.
Step 7: Swap the values pointed to by ptr1 and ptr2 using a temporary variable.
Step 8: Print the swapped values of a and b
Step 9 : End the program.

23
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Flow Chart:

Code :

#include <stdio.h>
int main() {
int a, b, temp; // Declare integer variables for the numbers and a temporary variable for
swapping
int *ptr1, *ptr2; // Declare pointer variables to store addresses of a and b
// Input two numbers from the user
printf("Enter two numbers: ");
scanf("%d %d", &a, &b);
// Assign addresses of a and b to ptr1 and ptr2
ptr1 = &a;
ptr2 = &b;
// Swap the values pointed to by ptr1 and ptr2 using a temporary variable
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
// Print the swapped values
printf("After swapping:\n");
printf("a = %d, b = %d\n", a, b);
return 0;
}

24
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
Output :
Enter two numbers: 5 7
After swapping:
a = 7, b = 5

Observations:
Pointer Arguments: swap function takes pointers to integers as arguments (int *a and int
*b).
Memory Access via Pointers: Inside the swap function, values are accessed and modified
directly using pointers.
Temporary Variable: A temporary variable is used to facilitate the swapping process.
In-Place Swapping: Actual variables (num1 and num2) are modified in memory through
pointers, demonstrating the power of pass-by-reference.
Efficient Data Handling: No need to return values, as changes are made directly to the
original variables.

Learning/Interpretation:
1: How are the values of a and b swapped using pointers?
Answer : The values of a and b are swapped by first storing the value of a in a temporary variable.
Then, the value pointed to by ptr1 (which holds the address of a) is assigned to the value pointed
to by ptr2 (which holds the address of b). Finally, the temporary variable is used to assign the
original value of a to b.

2 Why is a temporary variable used in the swapping process?


Answer : A temporary variable is used in the swapping process to hold the value of one of the
variables during the swap. Without a temporary variable, the value of one variable would be
overwritten before the other can be assigned to it.

25
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

3: What is the advantage of using pointers for swapping values compared to using normal variables?
Answer : Using pointers for swapping values allows direct access to the memory locations of
variables, enabling efficient and flexible manipulation of data. This is particularly useful in large
programs, where passing large data structures or arrays by reference through pointers is more
efficient than passing them by value. It also allows for modifying values directly in the caller
function without needing to return values.

4 : What happens if you do not use the temporary variable while swapping values with pointers?
Answer : If you do not use a temporary variable, you would lose one of the values during the
swap operation. This is because, when you assign one pointer’s value to another, the original
value is overwritten, and without a temporary variable, you would lose that original value.

Inference:

Date of Score: Write Score: Score: Total Score: Signature:


Completion Up Learning/ 5S/5 ------/15
(Neatness)/5 5

26
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

C program to input and print array elements


Experiment No. 1d using pointer. Hours Allotted: 2

Objectives : C program to input and print array elements using pointer.

Theory :
In C, an array is a collection of elements of the same type, stored in contiguous memory locations.
Pointers can be used to access and manipulate these elements efficiently.
Pointer and Arrays: An array name is essentially a pointer to the first element of the array.
This means that arrays and pointers are closely related, and pointers can be used to traverse
and manipulate arrays.
Dereferencing Pointers: The dereference operator * is used to access the value stored at the
memory address the pointer is pointing to.
Pointer Arithmetic: Pointer arithmetic can be used to access different array elements. The
pointer can be incremented to point to the next element in the array.
Equipment/Components :

# Equipment/Components Specification

1 Computer/Laptop CodeBlocks installed

2 C IDE/Interpreter Code::Blocks 20:03


3 Libraries stdio.h

Procedure :
Open the C IDE or terminal.
Create a new C file for writing the program.
Write the code to input and print array elements using pointers.
Execute the program and observe the output.
Record the results and any observations.
Algorithm :
Step 1: Start the program.
Step 2 : Declare an integer array and a pointer variable.an integer variable num and assign it a
value.
Step 3: Input the size of the array from the user.
Step 4: Use a pointer to input the values of the array elements using the dereference operator.
Step 5: Use a pointer to print the values of the array elements by dereferencing the pointer and
incrementing it.
Step 6: End the program.

27
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Flow Chart:

Code :
#include <stdio.h>

int main() {
int n; // Declare a variable to store the size of the array
int *ptr; // Declare a pointer to store the address of array elements

// Input the size of the array


printf("Enter the number of elements in the array: ");
scanf("%d", &n);
// Declare an array of size n
int arr[n];

// Assign the address of the first element of the array to the pointer
ptr = arr;
// Input array elements using pointer
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
printf("Element %d: ", i + 1);
scanf("%d", ptr); // Dereference the pointer to input the value
ptr++;// Move the pointer to the next element
}

28
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

// Print the array elements using pointer


printf("\nArray elements are:\n");
ptr = arr; // Reset pointer to the beginning of the array
for (int i = 0; i < n; i++) {
printf("Element %d: %d\n", i + 1, *ptr); // Dereference the pointer to print the value
ptr++;// Move the pointer to the next element
}

return 0;
}

Output :
Enter the number of elements in the array: 5
Enter 5 elements:
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50
Array elements are:
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50

29
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Observations:
Pointer to Array: A pointer (ptr) is used to iterate over the array elements.
Input Using Pointers: scanf is used with pointer arithmetic (ptr + i) to store values in the
array.
Output Using Pointers: *(ptr + i) is used to access and print each array element.
Memory Efficiency: Direct memory access through pointers avoids explicit indexing.
Pointer Arithmetic: Shows how pointers can navigate arrays using arithmetic.

Learning/Interpretation:
1: How are array elements accessed using pointers in this program?
Answer : Array elements are accessed using pointers by assigning the address of the array’s first
element to the pointer. The pointer is incremented to access subsequent elements. The dereference
operator * is used to access the value at the memory address the pointer is pointing to.

2: What is the advantage of using pointers to handle arrays instead of directly using array indices?
Answer : Using pointers to handle arrays makes it easier to manipulate memory directly, without
explicitly using array indices. Pointer arithmetic can simplify accessing elements of an array and
can improve performance, especially when dealing with large data structures.

3 : How does pointer arithmetic work in this program to navigate through the array?
Answer : In this program, pointer arithmetic is used by incrementing the pointer (ptr++). Each
time the pointer is incremented, it points to the next memory location, which corresponds to the
next element in the array. This allows the program to traverse the array and access each element
sequentially.

4: What would happen if we tried to input or print elements outside the array's bounds using pointers?
Answer : If we tried to input or print elements outside the bounds of the array, it would result in
undefined behavior, such as accessing invalid memory locations, causing the program to crash, or
printing garbage values. It's essential to ensure that the pointer does not exceed the array's size
while accessing elements.

Inference:

Date of Score: Write Score: Score: Total Score: Signature:


Completion Up Learning/ 5S/5 ------/15
(Neatness)/5 5

30
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

C Program to Copy One Array to Another


Experiment No. 1e Using Pointer Hours Allotted: 2

Objectives : C Program to Copy One Array to Another Using Pointer.

Theory :
In C, pointers store memory addresses, allowing direct manipulation of memory. In this program,
pointers are used to copy elements from one array to another.
Pointer Declaration: A pointer is declared using the * symbol, e.g., int *ptr;, and it stores the
address of a variable.

Array and Pointers: The array name acts as a pointer to the first element. Using pointers, we
can traverse the array and access its values.
Dereferencing: The dereference operator * is used to access the value at the memory address
the pointer points to.
Pointer Arithmetic: Pointers can be incremented to move through the array’s elements, e.g.,
ptr++.

Equipment/Components :

# Equipment/Components Specification

1 Computer/Laptop CodeBlocks installed

2 C IDE/Interpreter Code::Blocks 20:03


3 Libraries stdio.h

Procedure :
Open the C IDE or terminal.
Create a new C file for writing the program.
Write the code to input and print array elements using pointers.
Execute the program and observe the output.
Record the results and any observations.
Algorithm :
Step 1: Start the program.
Step 2 : Declare two arrays: one for storing the original data and one for the copied data.
Step 3: Declare a pointer variable for each array.
Step 4: Input the values into the original array.
Step 5: Use pointers to copy each element from the original array to the new array.
Step 6 : Print the contents of both arrays..
Step 7: End the program.

31
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Flow Chart:

Code :
#include <stdio.h>
int main() {
int n; // Declare the size of the arrays
int *ptr1, *ptr2; // Declare pointers for both arrays

// Input the size of the array


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

// Declare two arrays


int arr1[n], arr2[n];

// Assign pointers to the arrays


ptr1 = arr1;
ptr2 = arr2;

// Input elements into the first array


printf("Enter %d elements for the first array:\n", n);
for (int i = 0; i < n; i++) {
printf("Element %d: ", i + 1);
scanf("%d", ptr1); // Input value at the address ptr1 points to
ptr1++;// Move to the next element
}

32
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

// Reset ptr1 to point to the first element of arr1


ptr1 = arr1;

// Copy elements from arr1 to arr2 using pointers


for (int i = 0; i < n; i++) {
*ptr2 = *ptr1; // Dereference pointers to copy values
ptr1++;// Move to the next element in arr1
ptr2++;// Move to the next element in arr2
}

// Print the original and copied arrays


ptr1 = arr1;
ptr2 = arr2;

printf("\nOriginal array: ");


for (int i = 0; i < n; i++) {
printf("%d ", *ptr1); // Print value from arr1
ptr1++;// Move to the next element in arr1
}
printf("\nCopied array: ");
for (int i = 0; i < n; i++) {
printf("%d ", *ptr2); // Print value from arr2
ptr2++;// Move to the next element in arr2
}
return 0;
}

Output :
Enter the number of elements: 5
Enter 5 elements for the first array:
Element 1: 10
Element 2: 20
Element 3: 30
Element 4: 40
Element 5: 50
Original array: 10 20 30 40 50
Copied array: 10 20 30 40 50

33
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Observations:

Pointer Initialization: Pointers ptr1 and ptr2 are used to reference the source (arr1) and
destination (arr2) arrays.
Input via Pointers: Elements of the source array are input directly using ptr1, and the
pointer is incremented to move through the array.
Array Copy Using Pointers: The values from the source array are copied to the destination
array using *ptr2 = *ptr1 and pointer increments.
Efficient Memory Access: The program demonstrates direct manipulation of array
elements through pointer dereferencing, without indexing.
Pointer Arithmetic: Pointers ptr1 and ptr2 are incremented in loops to iterate through the
arrays.
Result Validation: Both the original and copied arrays are displayed to confirm the
successful copying of data.

Learning/Interpretation:
1: How does the program copy array elements from one array to another using pointers?
Answer : The program copies array elements by using two pointers: ptr1 pointing to the first
array (arr1) and ptr2 pointing to the second array (arr2). The values of the elements in arr1 are
copied to arr2 by dereferencing both pointers and using pointer arithmetic to move through the
arrays.

2: What is the significance of using pointers in this program instead of array indexing?
Answer : Using pointers in this program allows direct manipulation of memory locations,
providing flexibility and efficiency. Pointers enable the program to access and copy elements
without explicitly using array indices. Pointer arithmetic helps traverse the arrays seamlessly.

34
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

3: Why do we reset ptr1 to the beginning of the first array before copying the elements?
Answer : We reset ptr1 to the beginning of arr1 to ensure that we start copying from the first
element of the array. After inputting values, the pointer has been incremented to the end of arr1,
so it needs to be reset to its initial position for the copying operation.

4: How is pointer arithmetic used in this program to navigate the arrays?


Answer : Pointer arithmetic is used by incrementing the pointers ptr1 and ptr2 to move to the
next memory location of the arrays. Each increment (ptr1++ and ptr2++) advances the pointer
to the next element in the array, allowing traversal and copying of all elements.

Q5: What could happen if the pointers are not incremented during the copy operation?
Answer : If the pointers are not incremented during the copy operation, the program would copy
the first element repeatedly to the second array. The copy operation would not proceed to the
next element in either array, resulting in incorrect copying.

Inference:

Date of Score: Write Score: Score: Total Score: Signature:


Completion Up Learning/ 5S/5 ------/15
(Neatness)/5 5

35
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

C program that dynamically allocates


Experiment No. 1f memory for an array of integers Hours Allotted: 2

Objectives : C program that dynamically allocates memory for an array of integers, initializes it
with user input, and displays the sum of the elements.

Theory :

Dynamic memory allocation in C allows programs to allocate memory at runtime, which is


particularly useful when the size of the data is not known in advance. The malloc() function is
used to allocate memory dynamically for arrays or other variables, and the free() function is
used to deallocate that memory when no longer needed.

Dynamic Memory Allocation: In C, dynamic memory is allocated using the malloc() or


calloc() function. It allows the allocation of memory during runtime.
Example: int *arr = (int *)malloc(n * sizeof(int)); // Dynamically allocate memory for an array
of size n
Dereferencing: The dereference operator * allows accessing the value at the memory address
the pointer is pointing to.
Memory Deallocation: The free() function is used to release the dynamically allocated
memory when it is no longer needed.

Equipment/Components :

# Equipment/Components Specification

1 Computer/Laptop CodeBlocks installed

2 C IDE/Interpreter Code::Blocks 20:03


3 Libraries stdio.h

Procedure :
Open the C IDE or terminal.
Create a new C file for writing the program.
Write the code to dynamically allocate memory for the array, input elements, and calculate
the sum.
Execute the program and observe the output.
Record the results and any observations.

36
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Algorithm :
Step 1: Start the program.
Step 2: Declare a pointer variable for the array..
Step 3: Input the number of elements (n) for the array.
Step 4: Dynamically allocate memory for the array usingmalloc().
Step 5: Input values into the array.
Step 6 : Calculate the sum of the elements by dereferencing the pointer and adding the values.
Step 7 : Print the Sum.
Step 8 : Free the dynamically allocated memory.
Step 9: End the program.

Flow Chart:

37
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Code :

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

int main() {
int *arr; // Pointer to hold the dynamically allocated array
int n, sum = 0;

// Input the number of elements


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

// Dynamically allocate memory for the array


arr = (int *)malloc(n * sizeof(int));

// Check if memory allocation was successful


if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1; // Exit if memory allocation failed
}
// Input values into the array
printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}
// Calculate the sum of the elements
for (int i = 0; i < n; i++) {
sum += arr[i];
}
// Display the sum
printf("Sum of the elements: %d\n", sum);
// Free the dynamically allocated memory
free(arr);
return 0;
}

38
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Output :
Enter the number of elements: 5
Enter 5 elements:
Element 1: 2
Element 2: 4
Element 3: 6
Element 4: 8
Element 5: 10
Sum of the elements: 30

Observations:
Dynamic Memory: Used malloc to allocate memory for the array.
Error Check: Verified successful memory allocation with arr == NULL.
User Input: Stored elements directly in the allocated memory using arr[i].
Sum Calculation: Computed the sum of array elements in a loop.
Memory Release: Freed memory using free to prevent leaks.
Runtime Flexibility: Array size determined dynamically based on user input.
Learning/Interpretation:
1: What is the purpose of using dynamic memory allocation in this program?
Answer : The purpose of using dynamic memory allocation is to allocate memory for the array at
runtime based on the user's input. This makes the program more flexible, as the array size is not
fixed and can be determined dynamically.

2: What would happen if memory allocation fails in this program?


Answer : If memory allocation fails, the program will print an error message ("Memory allocation
failed.") and terminate with an error code. This happens because malloc() returns NULL if it
cannot allocate the requested memory.
39
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

3: Why is the free() function used in this program?


Answer : The free() function is used to deallocate the dynamically allocated memory once it is no
longer needed. This helps prevent memory leaks, which can lead to inefficient memory usage and
system crashes.

4: How does the program calculate the sum of the elements in the array?
Answer : The program calculates the sum by iterating through the array using a loop and adding
each element to the sum variable. The sum is then printed to the screen.

5: What would happen if we forget to call free() in this program?


Answer : If free() is not called, the dynamically allocated memory will not be released, causing a
memory leak. This could eventually lead to the exhaustion of available memory in a program
with multiple allocations.

Inference:

Date of Score: Write Score: Score: Total Score: Signature:


Completion Up Learning/ 5S/5 ------/15
(Neatness)/5 5

40
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

C program that dynamically allocates


Experiment No. 1g memory for a string and stores the user- Hours Allotted: 2
inputted string

Objectives : C program that dynamically allocates memory for a string and stores the user-inputted
string. Then, it displays the string in reverse order.

Theory :

Strings are arrays of characters. However, arrays in C have a fixed size, making them less flexible
for handling unknown-sized input. Dynamic memory allocation allows us to allocate memory
during runtime, enabling us to work with strings of varying lengths.
Dynamic Memory Allocation: Dynamic memory for a string can be allocated using the
malloc() function. The sizeof(char) is typically 1, as each character is stored in a single byte.
Example : char *str = (char *)malloc(n * sizeof(char));
Reversing a String: To reverse a string, we can use a loop to swap characters from the start
and end of the string until the middle is reached.
Memory Deallocation: After the string has been processed, the dynamically allocated memory
should be freed using the free() function to prevent memory leaks.

Equipment/Components :

# Equipment/Components Specification

1 Computer/Laptop CodeBlocks installed

2 C IDE/Interpreter Code::Blocks 20:03


3 Libraries stdio.h

Procedure :
Open the C IDE or terminal.Create a new C file to write the program.
Use the malloc() function to dynamically allocate memory for the string.
Input the string and store it in the dynamically allocated memory.
Use a loop to reverse the string and print it.
Deallocate the memory using the free() function after the string is processed.Run the
program, and observe the output.Record the results and any observations.

Algorithm :
Step 1: Start the program.
Step 2: Declare a pointer variable for the string.
Step 3: Input the length of the string (n).
Step 4: Dynamically allocate memory for the string using malloc( ).

41
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Step 5: Input the string from the user.


Step 6 : Reverse the string by swapping characters.
Step 7 : Print the reversed string.
Step 8 : Free the allocated memory using free( ).
Step 9: End the program.

Flow Chart:

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

int main() {
char *str; // Pointer to hold the dynamically allocated string
int n;

// Input the length of the string


printf("Enter the length of the string: ");
scanf("%d", &n);

42
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

// Dynamically allocate memory for the string


str = (char *)malloc((n + 1) * sizeof(char)); // +1 for the null-terminator

// Check if memory allocation was successful


if (str == NULL) {
printf("Memory allocation failed.\n");
return 1;
}

// Input the string


printf("Enter the string: ");
scanf(" "); // to consume any extra newline characters in input buffer
fgets(str, n + 1, stdin); // Read the string including spaces

// Reverse the string


int start = 0;
int end = strlen(str) - 1;

while (start < end) {


// Swap characters
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}

// Display the reversed string


printf("Reversed string: %s\n", str);

// Free the dynamically allocated memory


free(str);

return 0;
}

43
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Output :
Enter the length of the string:6
Enter the string:Hello!
Reversed string: !olleH

Observations:
Dynamic Memory Allocation: The program uses malloc to allocate memory for the string
based on user input (n + 1 to include the null terminator).
Error Checking: It checks whether memory allocation was successful by verifying if str ==
NULL.
String Input: The program reads the input string using fgets, which allows input with spaces.
scanf(" ") is used to clear the input buffer.
String Reversal: The string is reversed using a while loop that swaps characters from the start
and end, moving towards the center.
Memory Management: The dynamically allocated memory is freed using free after the string
is processed.
Pointer-Based String Manipulation: The string is handled and manipulated via pointers,
showcasing dynamic memory usage.

Learning/Interpretation:

1: What is the purpose of dynamically allocating memory for the string in this program?
Answer : The purpose of dynamically allocating memory is to allow the program to handle strings
of variable length based on user input. This makes the program more flexible and memory
efficient.

44
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

2: Why is malloc() used to allocate memory for the string?


Answer : malloc() is used to allocate memory at runtime for the string. It allows us to allocate just
enough memory for the string based on its length, rather than declaring a fixed-size array.

3: How is the string reversed in this program?


Answer : The string is reversed by using a loop that swaps characters from the start and end of the
string until the middle of the string is reached.

4: Why do we add +1 to the size in malloc() when allocating memory for the string?
Answer : The +1 is added to ensure that there is enough memory to store the null-terminator (\0),
which marks the end of the string in C.

5: What would happen if free() was not called in this program?


Answer : If free() is not called, the dynamically allocated memory would not be released, leading
to memory leaks. Over time, this can cause the program to consume more and more memory and
eventually crash.

6: What is the significance of using fgets() instead of scanf() for string input?
Answer : fgets() is used because it allows the program to handle strings with spaces and prevents
buffer overflow issues. scanf() can stop reading when it encounters a space, which is not desirable
for multi-word strings.

Inference:

Date of Score: Write Score: Score: Total Score: Signature:


Completion Up Learning/ 5S/5 ------/15
(Neatness)/5 5

45
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

To create a file and write contents, save, and


Experiment No. 2a close the file. Hours Allotted: 2

Objectives : C program to create a file and write contents, save, and close the file.

Theory :

File handling in C allows us to perform operations such as reading, writing, and appending data
to files. The C Standard Library provides functions such as fopen(), fprintf(), and fclose() to
handle file operations.

File Creation: A file is created using the fopen() function with the mode "w" (write) or "a"
(append). If the file already exists, "w" mode will overwrite it, and "a" mode will append data to
it.

File Writing: The fprintf() function is used to write formatted data into a file.

File Closing: After writing data to the file, the fclose() function is used to close the file, ensuring
the data is saved and resources are freed.

Equipment/Components :

# Equipment/Components Specification

1 Computer/Laptop CodeBlocks installed

2 C IDE/Interpreter Code::Blocks 20:03


3 Libraries stdio.h

Procedure :

Open the C IDE or terminal.


Create a new C file to write the program.
Use the fopen() function to create a file with the "w" mode (write).
Use fprintf() to write content to the file.
Close the file using fclose() to save the data.
1. Run the program and check the file for the written contents.
2. Observe the results and make sure the file is created and the contents are saved.

46
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Algorithm :
Step 1: Start the program.
Step 2: Declare a file pointer.
Step 3: Open the file using fopen() in "w" mode.
Step 4: Check if the file was successfully opened.
Step 5: Write contents to the file using fprintf().
Step 6 : Close the file using fclose().
Step 7: End the program.

Flow Chart:

47
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Code :
#include <stdio.h>
int main() {
FILE *fp; // Declare a file pointer
// Open the file for writing. If the file does not exist, it will be created.
fp = fopen("example.txt", "w");

// Check if the file was opened successfully


if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}
// Write content to the file
fprintf(fp, "This is a sample text written to the file.\n");
fprintf(fp, "File handling in C is important for data persistence.\n");

// Close the file to save and release resources


fclose(fp);

printf("File created and content written successfully.\n");


return 0;
}

Output :

File created and content written successfully.


//The contents of the file example.txt will be:
This is a sample text written to the file.
File handling in C is important for data persistence.

48
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Observations:

File Creation: Used fopen with mode "w" to create and open the file for writing.
Error Check: Verified successful file opening with fp == NULL.
Content Writing: Used fprintf to write text into the file.
File Closing: Closed the file using fclose to save changes and release resources.
Persistence: Demonstrates basic file handling for data storage in C.

Learning/Interpretation:
1: What is the purpose of using fopen() in this program?
Answer : The purpose of fopen() is to open a file for reading, writing, or appending. In this
case, "w" mode is used to create a new file or overwrite an existing file and prepare it for
writing (saving data).

2: What happens if the file cannot be opened successfully?


Answer : If the file cannot be opened, fopen() returns NULL, and the program displays an
error message indicating the failure. This might happen if there are permission issues or if the
file path is invalid.

3: How does fprintf() work in this program?


Answer : fprintf() writes formatted output to a file. It allows us to save the data into the file by
writing the desired content to it.

4: Why is fclose() important?


Answer : fclose() is crucial because it saves (flushes) the contents to the disk. Without calling
fclose(), the data might not be permanently saved, and the system resources would remain
allocated.

49
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Q5: What would happen if fclose() was not called?


Answer : If fclose() is not called, the data might not be saved properly to the file (it could remain in
memory), and system resources would not be freed, potentially leading to file corruption or
memory leaks.

Q6: How would you modify this program to append data to an existing file?
Answer : To append data instead of overwriting, the file should be opened in "a" mode (append).
This can be done by replacing "w" with "a" in the fopen() function.

Inference:

Date of Score: Write Score: Score: Total Score: Signature:


Completion Up Learning/ 5S/5 ------/15
(Neatness)/5 5

50
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

C program to read file contents and display


Experiment No. 2b on the console. Hours Allotted: 2

Objectives : C program to read file contents and display on the console.

Theory :

File handling in C allows you to perform operations like reading, writing, and appending to files.
The fopen() function is used to open a file, while fgetc() and fgets() are used to read data from a
file. After reading the file content, the fclose() function is used to close the file.
Opening a File: The fopen() function is used to open a file for reading (with "r" mode).
Reading from a File:
1. The fgetc() function reads a single character from the file.
2. The fgets() function reads a string (line) from the file.
Closing the File: The fclose() function is used to close the file after reading to release the file
pointer and system resources.

Equipment/Components :

# Equipment/Components Specification

1 Computer/Laptop CodeBlocks installed

2 C IDE/Interpreter Code::Blocks 20:03


3 Libraries stdio.h

Procedure :

Open the C IDE or terminal.


Create a new C file to write the program.
Use the fopen() function to open the file in "r" mode (read).
Use fgetc() or fgets() to read content from the file.
Display the contents on the console using printf().
Close the file using fclose().
Run the program and check the output.
Observe the results to ensure the file content is correctly displayed.

51
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Algorithm :

Step 1: Start the program.


Step 2: Declare a file pointer.
Step 3: Open the file using fopen() in "r" mode.
Step 4: Check if the file was opened successfully.
Step 5: Read the contents using fgetc() or fgets().
Step 6 : Display the content on the console using printf().
Step 7 : Close the file using fclose().
Step 8: End the program.

Flow Chart:

52
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Code :
#include <stdio.h>
int main() {
FILE *fp; // Declare a file pointer
char ch; // Variable to hold each character read from the file
// Open the file for reading
fp = fopen("example.txt", "r");
// Check if the file was opened successfully
if (fp == NULL) {
printf("Error opening the file.\n");
return 1;
}
// Read and display contents of the file
printf("File Contents:\n");
while ((ch = fgetc(fp)) != EOF) {
putchar(ch); // Display the character on the console
}
// Close the file
fclose(fp);
return 0;
}

Output :
Assume example.txt contains the following:
Hello, World!
This is a test file.
File handling in C is fun!
The program output will be:
File Contents:
Hello, World!
This is a test file.
File handling in C is fun!

53
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Observations:
File Opening: Opened the file in "r" mode using fopen to read its contents.
Error Check: Verified successful file opening with fp == NULL.
Content Reading: Used fgetc to read the file character by character until EOF (end of file).
Display Content: Used putchar to output the read characters to the console.
File Closing: Closed the file using fclose to release resources.
Practical Use: Demonstrates basic file reading and displaying functionality in C.

Learning/Interpretation:
1: What is the purpose of the fopen() function in this program?
Answer : The fopen() function is used to open the file in "r" mode for reading. It allows the
program to access the contents of the file.

2: How does the program read the content of the file?


Answer : The program uses fgetc() to read one character at a time from the file until it reaches the
end of the file (EOF). Each character is then displayed on the console using putchar().

3: What does EOF mean in this program?


Answer : EOF stands for "End Of File." It is a constant used to signify that there is no more data
to be read from the file. The fgetc() function returns EOF when it reaches the end of the file.

4: Why is it necessary to close the file using fclose()?


Answer : The fclose() function is used to close the file after reading. This ensures that any resources
allocated for file handling are freed and that all changes to the file (if any) are saved. It also
prevents file corruption.

54
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

5: What happens if the file does not exist or cannot be opened?


Answer : If the file cannot be opened (for example, if it doesn't exist), fopen() returns NULL,
and the program displays an error message indicating the failure to open the file.

6: Can we read a file line by line instead of character by character?


Answer : Yes, we can use fgets() to read the file line by line instead of character by character.
The fgets() function reads a string (one line) from the file until a newline character or the end
of the file is reached.

Inference:

Date of Score: Write Score: Score: Total Score: Signature:


Completion Up Learning/ 5S/5 ------/15
(Neatness)/5 5

55
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Experiment No. 2c Appending content to a file. Hours Allotted: 2

Objectives : C program to append content to a file.

Theory :

Appending to a file allows adding new data at the end of an existing file without overwriting its
original contents. In C, the "a" mode in the fopen() function is used for appending. If the file does
not exist, it creates a new file.

Opening a File for Appending: The "a" mode opens the file for appending. If the file does not
exist, it is created.

Writing to a File: The fprintf() function is used to write formatted data to the file.

Closing the File: The fclose() function closes the file and releases resources.

Equipment/Components :

# Equipment/Components Specification

1 Computer/Laptop CodeBlocks installed

2 C IDE/Interpreter Code::Blocks 20:03


3 Libraries stdio.h

Procedure :

Open a text editor or C IDE.


Create a new C file to write the program.
Use the fopen() function with the "a" mode to open the file for appending.
Use fprintf() or fputs() to append new content to the file.
Close the file using fclose().
Run the program and verify the file content after appending.
Observe the results to ensure new data is added at the end without overwriting existing content.

56
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Algorithm :
Step 1: Start the program.
Step 2 : Declare a file pointer.
Step 3: Open the file using fopen() in "a" mode.
Step 4: Check if the file was opened successfully.
Step 5: Prompt the user to enter content to append to the file.
Step 6 : Write the input content to the file using fprintf() or fputs().
Step 7 : Close the file using fclose().
Step 8: End the program.

Flow Chart:

57
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Code :
#include <stdio.h>
int main() {
FILE *fp; // Declare a file pointer
char data[100]; // Array to store user input

// Open the file in append mode


fp = fopen("example.txt", "a");

// Check if the file was opened successfully


if (fp == NULL) {
printf("Error opening file.\n");
return 1;
}

// Prompt the user for input to append


printf("Enter content to append to the file: ");
fgets(data, sizeof(data), stdin);

// Write the input content to the file


fprintf(fp, "%s", data);

// Close the file


fclose(fp);

printf("Content successfully appended to the file.\n");

return 0;
}

Output :
Enter content to append to the file: This is new content appended to the file.
File Content (example.txt) After Execution:
Existing file content...
This is new content appended to the file.
Content successfully appended to the file.

58
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Observations:
Opened the file in "a" (append) mode using fopen to add content to an existing file.
Error Check: Verified successful file opening with fp == NULL.
User Input: Used fgets to accept input from the user for appending content.
Appending Content: Used fprintf to write user-provided data to the file without
overwriting existing content.
File Closing: Closed the file using fclose to save changes and release resources.
File Persistence: Demonstrates appending functionality to update files dynamically.

Learning/Interpretation:
1: What does the "a" mode in fopen() do?
Answer : The "a" mode opens a file for appending. If the file exists, the content is added to the
end. If it doesn’t exist, a new file is created.

2: How does the program ensure that content is appended rather than overwritten?
Answer : The "a" mode ensures that new data is added to the end of the file without deleting or
overwriting the existing content.

3: Why is fclose() necessary in this program?


Answer : The fclose() function ensures that the file is properly closed and that all the data written
is saved. It also releases any system resources associated with the file.

4: What happens if the file does not exist when the program is executed?
Answer : If the file does not exist, the "a" mode automatically creates a new file and writes the
user-provided content to it.

59
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

5: How can the program be extended to handle multiple lines of input?


Answer : The program can use a loop to allow the user to append multiple lines of input to the
file, stopping when the user enters a specific termination keyword (e.g., "END").

Inference:

Date of Score: Write Score: Score: Total Score: Signature:


Completion Up Learning/ 5S/5 ------/15
(Neatness)/5 5

60
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Experiment No. 2d C program to read numbers from a file Hours Allotted: 2

Objectives : C program to read numbers from a file and write even, odd, and prime numbers to
separate files.

Theory :

This program demonstrates how to process numeric data from a file and write specific categories
of numbers to separate files.
Reading a File: Using the "r" mode with fopen() to read data from a file.
Writing to Files: Using the "w" mode with fopen() to write categorized data into separate files.
Even Numbers: Numbers divisible by 2 without a remainder.
Odd Numbers: Numbers not divisible by 2.
Prime Numbers: Numbers greater than 1 that are divisible only by 1 and themselves.

Equipment/Components :

# Equipment/Components Specification

1 Computer/Laptop CodeBlocks installed

2 C IDE/Interpreter Code::Blocks 20:03


3 Libraries stdio.h

Procedure :

Prepare Input File: Create a text file containing a list of integers separated by spaces or new
lines.
Write the Program: Create a C file to read from the input file and write categorized data to
separate files.
Open Files: Use fopen() in "r" mode for reading and "w" mode for writing.
Read Numbers: Read numbers from the input file using fscanf().
Classify Numbers:
Check divisibility for even and odd numbers.
Verify primality for prime numbers.
Write to Files: Write numbers to the corresponding files (even.txt, odd.txt, prime.txt).
Close Files: Use fclose() to close all files.
Verify Output: Open the output files and verify the categorized data.

61
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Algorithm :
Step 1: Start the program.
Step 2 : Create three output files for even, odd, and prime numbers.
Step 3: Open the input file in "r" mode.
Step 4: Assign Check if the input file opened successfully; if not, print an error and exit.
Step 5: Read numbers from the input file using a loop.
Step 6 : Classify Numbers:
If divisible by 2, write to the even file.
If not divisible by 2, write to the odd file.
If prime, also write to the prime file.
Step 7 : Close all files using fclose().
Step 6: End the program.

Flow Chart:

62
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Code :
#include <stdio.h>
#include <math.h>

// Function to check if a number is prime


int isPrime(int num) {
if (num <= 1) return 0;
for (int i = 2; i <= sqrt(num); i++) {
if (num % i == 0) return 0;
}
return 1;
}

int main() {
FILE *inputFile, *evenFile, *oddFile, *primeFile;
int num;

// Open files
inputFile = fopen("numbers.txt", "r");
evenFile = fopen("even.txt", "w");
oddFile = fopen("odd.txt", "w");
primeFile = fopen("prime.txt", "w");
// Check if input file opened successfully
if (inputFile == NULL) {
printf("Error: Could not open input file.\n");
return 1;
}
// Read numbers and classify
while (fscanf(inputFile, "%d", &num) != EOF) {
if (num % 2 == 0) {
fprintf(evenFile, "%d\n", num); // Write to even file
} else {
fprintf(oddFile, "%d\n", num); // Write to odd file
}
if (isPrime(num)) {
fprintf(primeFile, "%d\n", num); // Write to prime file
}
}

63
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

// Close all files


fclose(inputFile);
fclose(evenFile);
fclose(oddFile);
fclose(primeFile);

printf("Numbers categorized successfully into even.txt, odd.txt, and prime.txt.\n");

return 0;
}

Output :
even.txt:
12
2
18
odd.txt:
7
9
5
29
17
prime.txt:
7
5
2
29
17

64
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Observations:
Files Used: Read from numbers.txt; wrote to even.txt, odd.txt, and prime.txt.
Classification: Numbers categorized as even, odd, and prime.
Prime Check: Used isPrime function with square root logic.
Output: Data written to respective files using fprintf.
File Management: Ensured all files were properly closed.
Confirmation: Success message displayed after processing.

Learning/Interpretation:

1: What mode is used to open files for writing categorized data?


Answer : The "w" mode is used to open files for writing categorized data. If the file does not
exist, it is created.

2: How does the program classify even and odd numbers?


Answer : The program uses the modulus operator (%). If a number is divisible by 2 (num % 2 ==
0), it is even; otherwise, it is odd.

65
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

3: How does the program identify prime numbers?


Answer : The program uses a helper function isPrime(), which checks if a number is greater
than 1 and is divisible only by 1 and itself.

4: What happens if the input file is not found?


Answer : The program checks if the input file is successfully opened. If not, it prints an error
message and exits.

5: How can this program be extended for large datasets?


Answer : For large datasets, the program can be optimized by using buffered I/O or
implementing more efficient prime-checking algorithms like the Sieve of Eratosthenes.

Inference:

Date of Score: Write Score: Score: Total Score: Signature:


Completion Up Learning/ 5S/5 ------/15
(Neatness)/5 5

66
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Experiment No. 2e C program to compare two files. Hours Allotted: 2

Objectives : C program to compare two files.

Theory :
File comparison involves reading the contents of two files and comparing them character by
character. If all characters match, the files are identical; otherwise, they differ.
File Handling in C : Files are managed using the fopen(), fgetc(), and fclose() functions.
Comparison Process:
o Open the two files in "r" mode.
o Read characters sequentially from both files.
o Compare corresponding characters from both files.
o Identify mismatches or end-of-file conditions.

Equipment/Components :

# Equipment/Components Specification

1 Computer/Laptop CodeBlocks installed

2 C IDE/Interpreter Code::Blocks 20:03


3 Libraries stdio.h

Procedure :
Prepare Input Files: Create two files containing data to be compared.
Write the Program: Create a C file to implement the file comparison logic.
Open Files: Use fopen() to open both files in "r" mode.
Compare Files: Use fgetc() to read and compare the characters of both files:
o If a mismatch is found, mark the files as different.
o If the end of both files is reached without mismatches, they are identical.
Close Files: Use fclose() to close both files.
Display Results: Print whether the files are identical or different.
Verify Output: Test the program with identical and different file contents.

Algorithm :

Step 1: Start the program.


Step 2: Open both files using fopen() in "r" mode.

67
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Step 3: Check if the files opened successfully; if not, print an error message and exit.
Step 4: Read characters from both files using fgetc() in a loop.
Step 5: Compare the characters:
If a mismatch is found, mark files as different and exit the loop.
If the end of both files is reached simultaneously, mark them as identical.
Step 6 : Close both files using fclose().
Step 7 : Display whether the files are identical or different.
Step 8: End the program.

Flow Chart:

68
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

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

int main() {
FILE *file1, *file2;
char ch1, ch2;
int isIdentical = 1; // Flag to track file comparison

// Open files
file1 = fopen("file1.txt", "r");
file2 = fopen("file2.txt", "r");

// Check if files opened successfully


if (file1 == NULL || file2 == NULL) {
printf("Error: Unable to open one or both files.\n");
return 1;
}
// Compare files character by character
while (((ch1 = fgetc(file1)) != EOF) && ((ch2 = fgetc(file2)) != EOF)) {
if (ch1 != ch2) {
isIdentical = 0; // Files are different
break;
}
}

// Check if one file has additional content


if (isIdentical && (fgetc(file1) != EOF || fgetc(file2) != EOF)) {
isIdentical = 0;
}

// Close files
fclose(file1);
fclose(file2);

// Print result
if (isIdentical) {

69
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

printf("Files are identical.\n");


} else {
printf("Files are different.\n");
}

return 0;
}

Output :
Test Case 1:
file1.txt:
Hello, World!
file2.txt:
Hello, World!
Output:
Files are identical.
Test Case 2:
file1.txt:
Hello, World!
file2.txt:
Hello, Universe!
Output:
Files are different.

70
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Observations:

Purpose: Compares two files character by character.


Logic: Checks for mismatches or extra content in either file.
Output: Prints if files are identical or different.
Key Points: Uses fgetc for comparison; ensures files are closed properly.

Learning/Interpretation:

1: What function is used to read characters from the files?


Answer : The fgetc() function is used to read characters sequentially from the files.

2: How does the program handle file mismatches?


Answer : The program compares each character from both files. If a mismatch is found, it
terminates the comparison and marks the files as different.

3: What happens if one file has extra content?


Answer : If the end of one file is reached but the other file still has characters, the program
identifies the files as different.

4: Can this program handle large files efficiently?


Answer : Yes, the program reads one character at a time, which is memory-efficient. However, for
very large files, buffered reading could improve performance.

Inference:

Date of Score: Write Score: Score: Total Score: Signature:


Completion Up Learning/ 5S/5 ------/15
(Neatness)/5 5

71
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

C program to copy contents from one file to


Experiment No. 2f Hours Allotted: 2
another file.

Objectives : C program to copy contents from one file to another file.

Theory :
File copying involves reading the content from a source file and writing it to a destination file. It
demonstrates basic file handling in C.
File Handling Basics:
1. Files are accessed using FILE pointers.
2. The fopen() function is used to open files in specific modes like "r" for reading and "w" for
writing.
3. The fgetc() function reads data from the source file, and fputc() writes data to the destination
file.
4. Files must be closed using fclose() to release resources.

Equipment/Components :

# Equipment/Components Specification

1 Computer/Laptop CodeBlocks installed

2 C IDE/Interpreter Code::Blocks 20:03


3 Libraries stdio.h

Procedure :
Prepare Input File: Create a file with some content to serve as the source file.
Write the Program: Create a C file to implement the file copying logic.
Open Files: Use fopen() to open the source file in "r" mode and the destination file in "w"
mode.
Read and Write: Use fgetc() to read characters from the source file and fputc() to write them
to the destination file in a loop.
Close Files: Use fclose() to close both files.
Verify Output: Open the destination file to confirm the copied content matches the source file.

Algorithm :
Step 1 : Start the program.
Step 2 : Open the source file in "r" mode.
Step 3 : Check if the source file opened successfully; if not, display an error and exit.
Step 4 : Open the destination file in "w" mode.

72
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Step 5: Check if the destination file opened successfully; if not, display an error and exit.
Step 6 : Read characters from the source file using fgetc() in a loop.
Step 7 : Write each character to the destination file usingfputc().
Step 8 : Continue until the end of the source file is reached.
Step 9 : Close both files using fclose().
Step 10: End the program.

Flow Chart:

73
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Code :

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

int main() {
FILE *sourceFile, *destFile;
char ch;

// Open the source file in read mode


sourceFile = fopen("source.txt", "r");
if (sourceFile == NULL) {
printf("Error: Unable to open source file.\n");
return 1;
}

// Open the destination file in write mode


destFile = fopen("destination.txt", "w");
if (destFile == NULL) {
printf("Error: Unable to open destination file.\n");
fclose(sourceFile);
return 1;
}

// Copy contents from source to destination


while ((ch = fgetc(sourceFile)) != EOF) {
fputc(ch, destFile);
}

// Close the files


fclose(sourceFile);
fclose(destFile);

printf("File contents copied successfully.\n");

return 0;
}

74
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Output :

Input File (source.txt):

Hello, World!
This is a test file.

After Execution (destination.txt):

Hello, World!
This is a test file.

Output Message:

File contents copied successfully.

75
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Observations:
Purpose: Copies the contents of source.txt to destination.txt.
Logic: Opens source file in read mode, destination file in write mode, and copies character
by character using fgetc and fputc.
Error Handling: Checks if files can be opened, ensuring program termination if
unsuccessful.
Key Features: Efficient character-by-character copying; closes files to prevent resource
leaks.
Learning/Interpretation:
1: What function is used to read data from the source file?
Answer: The fgetc() function is used to read characters sequentially from the source file.

2: How is data written to the destination file?


Answer : Data is written to the destination file using the fputc() function.

3: What happens if the source file does not exist?


Answer : If the source file does not exist, the program displays an error message and exits without
performing the copy operation.

4: Can this program copy binary files?


Answer : No, this program is designed for text files. For binary files, the fread() and fwrite()
functions should be used.

5: What is the importance of closing files after operations?


Answer : Closing files ensures that all data is properly written, and resources are released to avoid
memory leaks or file corruption.

Inference:

Date of Score: Write Score: Score: Total Score: Signature:


Completion Up Learning/ 5S/5 ------/15
(Neatness)/5 5

76
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

C Program to Remove a Word from a Text


Experiment No. 2g Hours Allotted: 2
File

Objectives : C Program to Remove a Word from a Text File .

Theory :
File manipulation in C enables modifying the content of files programmatically. Removing a word
from a text file involves reading the file, identifying the specified word, and rewriting the text
without the targeted word.
File Handling Concepts:
1. Use FILE pointers to handle files.
2. Open the file in "r" mode to read its contents and "w" mode to overwrite data.
3. Use functions like fgets() to read lines and string operations (strstr(), strcmp()) to identify the
word to be removed.
4. Write updated content back to the file using fprintf() or fputs().

Key String Manipulation:


1. The strstr() function finds the first occurrence of a substring in a string.
2. Tokens from a line can be extracted using strtok() for processing.

Equipment/Components :

# Equipment/Components Specification
1 Computer/Laptop CodeBlocks installed
2 C IDE/Interpreter Code::Blocks 20:03

3 Libraries stdio.h,stdlib.h,string.h

Procedure :
Prepare Input File: Create a text file containing some sample text.
Write the Program: Create a C program that removes a specific word.
Open Files: Open the source file in "r" mode and a temporary file in "w" mode.
Read and Process: Read each line of the source file, split it into words, and remove the
specified word.
Write Updated Content: Write the processed lines to the temporary file.
Replace Original File: Rename the temporary file to replace the original file.
Close Files: Close both files after operations.
Verify Output: Check the updated file to ensure the word is removed.

77
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Algorithm :

Step 1: Start the program.


Step 2: Open the source file in "r" mode for reading.
Step 3: Open a temporary file in "w" mode for writing updated content.
Step 4: Assign Input the word to be removed from the user.
Step 5: Read each line from the source file using fgets( ).
Step 6 : Split the line into words using strtok( ).
Step 7 : Compare each word with the input word using strcmp( ).
Step 8 : Write words that do not match to the temporary file.
Step 9 : Repeat until all lines are processed.
Step 10 : Close both files.
Step 11 : Replace the original file with the temporary file.
Step 12: End the program.

Flow Chart:

78
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Code :

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

#define MAX_LINE_SIZE 256

int main() {
FILE *sourceFile, *tempFile;
char line[MAX_LINE_SIZE];
char wordToRemove[50];
char *token;

// Input the word to remove


printf("Enter the word to remove: ");
scanf("%s", wordToRemove);

// Open the source file in read mode


sourceFile = fopen("source.txt", "r");
if (sourceFile == NULL) {
printf("Error: Could not open source file.\n");
return 1;
}

// Open a temporary file in write mode


tempFile = fopen("temp.txt", "w");
if (tempFile == NULL) {
printf("Error: Could not open temporary file.\n");
fclose(sourceFile);
return 1;
}

// Process each line


while (fgets(line, MAX_LINE_SIZE, sourceFile)) {
token = strtok(line, " \n"); // Split line into words
while (token != NULL) {

79
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

if (strcmp(token, wordToRemove) != 0) { // If word is not the target


fprintf(tempFile, "%s ", token); // Write word to temp file
}
token = strtok(NULL, " \n");
}
fprintf(tempFile, "\n"); // Write a new line after processing the line
}

// Close the files


fclose(sourceFile);
fclose(tempFile);

// Replace the source file with the temporary file


remove("source.txt");
rename("temp.txt", "source.txt");

printf("The word '%s' has been removed from the file.\n", wordToRemove);

return 0;
}

Output :

Input File (source.txt):


This is a sample text file.
The program will remove a word.
Make sure to input the word correctly.

Execution:
Enter the word to remove: remove

Updated File (source.txt):


This is a sample text file.
The program will a word.
Make sure to input the word correctly.

Output Message:
The word 'remove' has been removed from the file.

80
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

Observations:

Purpose: Removes a specified word from source.txt and updates the file.
Steps:
1. Reads lines from source.txt.
2. Splits lines into words.
3. Writes all words except the target word to temp.txt.
4. Replaces source.txt with temp.txt.
Checks: Ensures files are opened successfully.
Output: Confirms word removal.

Learning/Interpretation:
1: How are words identified and removed from the file?
Answer : Words are split from each line using strtok(). Each word is compared with the target
word using strcmp(). Only unmatched words are written to the temporary file.

2: What happens if the specified word is not in the file?


Answer : If the specified word is not found, the program writes the original content to the
temporary file without modifications.

81
Course: DAIML Subject Code:24AI21P Subject: DSA Lab

3: Why is a temporary file used instead of modifying the original file?


Answer : A temporary file ensures the original file remains unchanged during the process,
providing a fallback in case of errors.

4: Can this program handle punctuation with words?


Answer : The program does not handle punctuation directly. Words with attached punctuation
(e.g., "word,") are treated as different from "word". Further processing can be added to handle
this.

5: How can the program be modified for case-insensitive word removal?


Answer : The program can be made case-insensitive by converting both the target word and each
token to lowercase using strlwr() before comparison.

Inference:

Date of Score: Write Score: Score: Total Score: Signature:


Completion Up Learning/ 5S/5 ------/15
(Neatness)/5 5

82

You might also like