DSAMANUAL
DSAMANUAL
Lab Manual
Diploma
in
Artificial Intelligence
& Machine Learning(DAIML)
Semester 2
i OS Installation on VM/Partition
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.
Stack
Stack Implementation:
a. C program to implement stack operations.
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
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
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
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
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.
iv
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
1.1 On Windows :
1.Open your web browser and navigate to the official Python website:
https://www.codeblocks.org/downloads/
5
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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
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
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
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
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 = # // Initialize pointer with the address of 'num'
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:
18
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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
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
Inference:
22
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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
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.
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:
26
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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
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
// 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
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:
30
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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
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
32
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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.
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:
35
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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 :
Equipment/Components :
# Equipment/Components Specification
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;
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.
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.
Inference:
40
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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
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
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;
42
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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
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.
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:
45
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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
Procedure :
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");
Output :
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).
49
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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:
50
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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
Procedure :
51
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
Algorithm :
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.
54
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
Inference:
55
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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
Procedure :
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
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.
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
Inference:
60
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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
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>
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
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:
65
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
Inference:
66
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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
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 :
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");
// Close files
fclose(file1);
fclose(file2);
// Print result
if (isIdentical) {
69
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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:
Learning/Interpretation:
Inference:
71
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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
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;
return 0;
}
74
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
Output :
Hello, World!
This is a test file.
Hello, World!
This is a test file.
Output Message:
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.
Inference:
76
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
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().
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 :
Flow Chart:
78
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
Code :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *sourceFile, *tempFile;
char line[MAX_LINE_SIZE];
char wordToRemove[50];
char *token;
79
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
printf("The word '%s' has been removed from the file.\n", wordToRemove);
return 0;
}
Output :
Execution:
Enter the word to remove: remove
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.
81
Course: DAIML Subject Code:24AI21P Subject: DSA Lab
Inference:
82