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

Assignment I Template

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Assignment I Template

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 79

School of Electronics and Communication Engineering

Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Name of the student Rohit Chandrashekhar Kuppelur


Roll No 264
USN 01FE22BEC095
Div B

Part- A

Variables and Data Types


1.What is the difference between a variable and a data type in C programming? Provide
examples to illustrate.
Ans: A variable can also be defined as an identifier which is used to store a value which
can user input or defined by the programmer.
Data type is defined built in data type in language that store fundamental information of
what type data it is.
2. Explain the concept of data types in C programming. Discuss the different types of data
types available in C.
Ans: The data types are the collection of data with fixed Byte of memory needed to store
data in memory space.
1. Primitive datatype:
a. Character
b. Integer
c. Float
d. Double
2. Derived data type
a. Signed
b. unsigned
c. Long double
3. User defined Type
3.How are variables declared and initialized in C programming? Provide examples of
variable declarations with different data types.
Ans: Variables are declared by specifying the data type followed by the variable name.
Optionally, variables can be initialized at the time of declaration by assigning a value to
them.
Here are some examples of variable declarations with different data types:

int num ; // Declaration of an integer variable


float pi = 3.14159; // Declaration and initialization of a floating-point variable
char letter = 'A' ; // Declaration and initialization of a character variable
double big Num = 123456.789;// Declaration and initialization of a double variable In these
examples, int, float, char, and double are data types. The variable names (num, pi, letter,
big Num) can be chosen by the programmer and must follow certain rules, such as starting
with a letter or underscore and not being a keyword.
Variables can also be declared without initialization:
int count; // Declaration of an integer variable without initialization
In this case, the variable count is declared but not initialized, meaning it will contain
garbage value until explicitly assigned a value.

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

4. Discuss the scope and lifetime of variables in C programming. What are global and local
variables?
Ans: Variables in C programming have scope and lifetime. Global variables are accessible
throughout the program and exist until the program terminates. Local variables are
accessible only within the function or block where they are declared and exist only until
the function or block ends.
5. Explain the concept of type casting in C programming. When is type casting necessary,
and how is it performed?
Ans: Type casting in C is the process of converting a value from one data type to another.
It's necessary when you need to perform operations involving different data types. It's done
by placing the desired data type in parentheses before the value or variable to be converted.
However, type casting should be used carefully to avoid data loss or unexpected behavior.

Operators:
1.Describe the purpose and usage of the ternary conditional operator? In C programming.
Provide an example demonstrating its usage.
Ans: The ternary conditional operator (?:) in C is used to evaluate a condition and return a
value based on whether the condition is true or false. It's a concise way to write simple
conditional expressions.
2. Discuss the bitwise operators available in C programming. Explain their usage with
suitable examples.
Ans: C provides several bitwise operators that allow you to perform operations at the bit
level. Here's a brief overview:
& (Bitwise AND): Sets each bit to 1 if both bits are 1. Example: 0b1100 & 0b1010 evaluates
to 0b1000.
| (Bitwise OR): Sets each bit to 1 if at least one of the bits is 1. Example: 0b1100 | 0b1010
evaluates to 0b1110.
^ (Bitwise XOR): Sets each bit to 1 if exactly one of the bits is 1. Example: 0b1100 ^ 0b1010
evaluates to 0b0110.
~ (Bitwise NOT): Flips the bits. Example: ~0b1100 evaluates to 0b0011.
<< (Left shift): Shifts the bits to the left by a specified number of positions. Example:
0b0011 << 2 evaluates to 0b1100.
>> (Right shift): Shifts the bits to the right by a specified number of positions. Example:
0b1100 >> 2 evaluates to 0b0011.
These operators are often used in low-level programming, such as in embedded systems
or when working with binary data.

3. Explain the difference between the postfix and prefix increment operators (++) in C
programming. Provide examples to illustrate.
Ans: The postfix increment operator (variable++) returns the current value of the variable
and then increments it. The prefix increment operator (++variable) increments the
variable first and then returns its new value.
4. What is the significance of the logical AND (&&) and logical OR (||) operators in C
programming? How are they used in conditional expressions?
Ans: The logical AND (&&) operator returns true if both conditions are true. The logical OR
(||) operator returns true if at least one condition is true. They are used to combine
conditions in conditional statements.

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

5. Discuss the concept of operator precedence and associativity in C programming.


Provide examples to demonstrate how they affect expression evaluation.
Ans: Operator precedence and associativity dictate the order in which operators are
evaluated in an expression. Precedence determines which operator is evaluated first,
while associativity defines the order of evaluation when multiple operators of the same
precedence appear in an expression.
Precedence: Operators with higher precedence are evaluated before operators with lower
precedence. For example, in the expression a + b * c, the multiplication (*) has higher
precedence than addition (+), so b * c is evaluated first, and then the result is added to a.
Associativity: When operators have the same precedence, associativity determines the
order of evaluation. For example, the addition operator (+) is left-associative, so in the
expression a + b + c, the leftmost + is evaluated first, and then the result is added to c. On
the other hand, the assignment operator (=) is right-associative, so in the expression a = b
= c, the rightmost = is evaluated first, and then the result is assigned to a.
Here's an example to demonstrate how precedence and associativity affect expression
evaluation:
#include <stdio.h>\
int main()
{
int a = 10, b = 5, c = 2;
int result = a + b * c; // Multiplication has higher precedence than addition
printf("Result: %d\n", result); // Output: 20
return 0;
}
In this example, b * c is evaluated first due to the higher precedence of the multiplication
operator, and then the result is added to a. If the addition operator had higher precedence
than the multiplication operator, the result would be 25 (a + (b * c)).

Control Structures
o Describe the purpose and usage of the switch statement in C programming. How does it
differ from the if-else statement?
Ans: The switch statement in C is used to select one of several code blocks to execute
based on the value of an expression. It provides a more structured alternative to using
multiple if-else statements. However, it can only be used with integral types and requires
explicit use of break statements to prevent fall-through behavior.
o Explain the concept of nested control structures in C programming. Provide an example
demonstrating nested if-else statements.
Ans: Nested control structures in C allow you to use one control structure inside another.
For example, you can have an if statement inside another if statement. They are useful for
handling complex decision-making or looping scenarios. However, excessive nesting can
make code hard to read and maintain.
o Discuss the role of the break and continue statements in loop control in C programming.
Provide examples to illustrate their usage.
Ans: break is used to exit a loop immediately, while continue is used to skip the rest of the
loop body for the current iteration and continue with the next iteration.

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

o What are the advantages of using the for loop over the while loop in C programming?
Provide examples comparing the two.
Ans: The for loop is more concise and readable compared to the while loop because it
combines initialization, condition, and increment/decrement in one line. It also limits the
scope of the loop control variable, making the code safer and easier to understand.
o Explain the concept of short-circuit evaluation in C programming. How does it affect the
evaluation of logical expressions in if statements?
Ans: Short-circuit evaluation in C means that the second operand of a logical AND (&&) or
logical OR (||) operator is not evaluated if the result can be determined by the first
operand alone. This behavior helps improve efficiency by avoiding unnecessary
evaluations.

Functions:
o Describe the purpose and structure of a function prototype in C programming. Why is it
necessary to declare function prototypes?
Ans: A function prototype in C programming serves as a declaration of a function before
its actual definition. It provides the compiler with information about the function's name,
return type, and parameters, allowing the compiler to perform type checking and
generate correct code when the function is called.
Function prototypes are necessary for several reasons:
Compile-Time Checking: Prototypes allow the compiler to check that the function is used
correctly (e.g., correct number and type of arguments) before the actual function
definition is seen. This helps catch errors early in the development process.
Linking: Prototypes are needed for the linker to resolve function calls to their actual
memory addresses. Without a prototype, the linker may not be able to correctly link
function calls.
Modular Programming: Prototypes allow you to define functions in separate files or
modules. By declaring the function prototype at the beginning of a file or in a header file,
you can use the function in other parts of your program before its actual definition is
encountered.
Documentation: Prototypes serve as documentation for the function, providing
information about its name, return type, and parameters. This can be useful for
understanding the function's purpose and how to use it.
In summary, function prototypes are necessary in C programming to enable compile-time
checking, linking, modular programming, and documentation of functions. They help
ensure that functions are used correctly and can be called from different parts of a
program.
o Explain the difference between call by value and call by reference in C programming.
Provide examples to illustrate both concepts.
Ans: Call by value passes a copy of the value to the function, so changes inside the
function do not affect the original variable. Call by reference passes the address of the
value, allowing the function to modify the original variable.
o Discuss the concept of recursion in C programming. Provide an example of a recursive
function and explain how it works.
Ans: Recursion in C is a technique where a function calls itself to solve a problem. It
requires a base case to stop the recursion. Example: calculating the factorial of a number.

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

o What is the significance of the return statement in C programming? How are values
returned from functions?
Ans: The return statement in C is used to exit a function and optionally return a value to
the calling function. It allows functions to provide results or data back to the calling code.
o Describe the role of function parameters and arguments in C programming. How are
function arguments passed to parameters?
Ans: Function parameters are variables in a function's definition that receive values when
the function is called. Function arguments are the actual values passed to a function when
it is called. Function arguments can be passed to parameters either by value or by
reference.

Arrays:
o Explain the concept of arrays in C programming. How are arrays declared and initialized?
Ans: Arrays in C are collections of elements of the same data type stored in contiguous
memory locations. They are declared using the syntax datatype arrayName[arraySize]; and
can be initialized at declaration using braces {}. Arrays are zero-indexed, and elements are
accessed using square brackets [] with the index inside.
o Discuss the difference between a one-dimensional array and a multidimensional array in
C programming. Provide examples of both.
Ans: A one-dimensional array in C is a linear collection of elements accessed using a single
index. A multidimensional array is an array of arrays, allowing for more complex data
structures. Accessing elements in a multidimensional array requires multiple indices.
o Describe the process of accessing array elements in C programming. How are array
indices used to access elements?
Ans: Array elements in C are accessed using indices inside square brackets. Arrays are
zero-indexed, so the first element is at index 0. Indices can be constants, variables, or
expressions that evaluate to integers.
o What is the significance of the null character ('\0') in C strings? How is it used to
determine the end of a string?
Ans: The null character ('\0') is used in C strings to mark the end of a string. It allows C to
represent strings of varying lengths without explicitly storing the length of the string.
Functions that operate on C strings use the null character to determine the end of the
string.
o Explain the concept of dynamic memory allocation for arrays in C programming. How
are dynamic arrays allocated and deallocated?
Ans: Dynamic memory allocation in C allows you to allocate memory for arrays at runtime
using malloc, calloc, and realloc. Memory is deallocated using free. It's important to
deallocate memory when no longer needed to avoid memory leaks.

Pointers:
o Describe the purpose and usage of pointers in C programming. How are pointers
declared and initialized?
Ans: Pointers in C store memory addresses and are used to indirectly access and
manipulate data. They are declared using the asterisk (*) symbol and initialized with the
address of a variable using the address-of operator (&). Pointers are used for dynamic
memory allocation, passing arguments by reference, and building data structures.

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Understanding pointers is essential for writing efficient and flexible C programs.


o Explain the concept of pointer arithmetic in C programming. Provide examples to
illustrate addition and subtraction operations on pointers.
Ans: Pointer arithmetic in C allows you to increment or decrement a pointer to move it to
the next or previous element of the array it points to. Adding an integer value to a pointer
increments it by that many elements of the data type, while subtracting decrements it. It's
important to stay within the bounds of the array to avoid undefined behavior.
o Discuss the difference between pass by value and pass by reference in function
arguments using pointers in C programming. Provide examples to illustrate both
approaches.
Ans: In C, pass by value involves passing a copy of the argument's value to the function,
while pass by reference involves passing the address of the argument using pointers. Pass
by value keeps the original data unchanged, while pass by reference allows modification
of the original data.
o Describe the concept of NULL pointers in C programming. How are NULL pointers used
and checked for in programs?
Ans: In C, a NULL pointer is a pointer that does not point to any memory location. It is
often used to indicate that a pointer is not currently pointing to a valid object. NULL
pointers are checked using the NULL macro or by comparing the pointer to NULL directly.
o Explain the role of pointers in dynamic memory allocation in C programming. How are
pointers used to allocate and deallocate memory dynamically?
Ans: Pointers are used in C for dynamic memory allocation using malloc, calloc, and realloc
functions. malloc allocates memory, calloc allocates and initializes to zero, realloc resizes
memory, and free deallocates memory. Dynamic memory allocation allows for flexible
memory management but requires careful handling to avoid memory leaks.

Strings:
o Discuss the concept of strings in C programming. How are strings represented and
manipulated in C?
Ans: Strings in C are arrays of characters terminated by a null character ('\0'). They are
manipulated using functions from <string.h> like strlen, strcpy, strcat, and strcmp.
Handling null characters is crucial to avoid buffer overflows and undefined behavior.
o Explain the difference between character arrays and string literals in C programming.
Provide examples to illustrate both concepts.
Ans:
Character arrays in C are arrays of characters that can be used to store strings. They are
declared like any other array but are terminated by a null character ('\0') to mark the end
of the string.
char str1[] = {'h', 'e', 'l', 'l', 'o', '\0'};
String literals, on the other hand, are sequences of characters enclosed in double quotes
("). They are automatically null-terminated by the compiler.
char *str2 = "hello";
The main difference is that character arrays can be modified, while string literals are read-
only. Modifying a string literal leads to undefined behavior.
str1[0] = 'H'; // Valid, changes 'h' to 'H'
str2[0] = 'H'; // Undefined behavior, trying to modify a string literal

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Character arrays are useful when you need to modify the string, while string literals are
used when you need a constant string that will not be modified.

o Describe common string manipulation functions available in the C standard library.


Provide examples of functions like strlen, strcpy, strcat, and strcmp.
Ans: The C standard library <string.h> provides functions for string manipulation:
strlen: Calculates the length of a string.
strcpy: Copies one string to another.
strcat: Concatenates two strings.
strcmp: Compares two strings.
strncmp: Compares two strings up to a specified number of characters.Top of Form

o Discuss the concept of string tokenization in C programming. How are strings split into
tokens using delimiter characters?
Ans: String tokenization in C involves breaking a string into tokens based on delimiter
characters. The strtok function from <string.h> is commonly used for this purpose. It
returns one token at a time and modifies the original string by replacing delimiters with '\
0'.
o Explain the importance of null-terminated strings in C programming. How does the null
character ('\0') signify the end of a string?
Ans: Null-terminated strings are fundamental in C programming because they allow
strings to be stored and manipulated efficiently. In C, a string is represented as an array of
characters terminated by a null character ('\0'). The null character serves as a sentinel
value that signifies the end of the string.
The importance of null-terminated strings lies in several key aspects:
String Length: The null character allows for an efficient way to determine the length of a
string. Functions like strlen can simply iterate through the characters of the string until
they encounter the null character, indicating the end of the string.
String Operations: String manipulation functions in C, such as strcpy, strcat, and strcmp,
rely on null-terminated strings. These functions operate on strings until they encounter
the null character, ensuring that they only process the intended portion of the string.
Memory Efficiency: Null-terminated strings allow for efficient memory usage. The null
character takes up only one byte of memory and does not require additional metadata to
store the length of the string, unlike in some other programming languages.
Compatibility: Many C library functions and system calls expect null-terminated strings.
Using null-terminated strings ensures compatibility with these functions and allows C
programs to interact effectively with the underlying operating system.
In summary, null-terminated strings are crucial in C programming as they provide a simple
and efficient way to represent and manipulate strings, enabling a wide range of string
operations and ensuring compatibility with standard library functions.

Structures and Unions:

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

o Describe the purpose and usage of structures in C programming. How are structures
declared and accessed?
Ans: Structures in C allow you to group different types of data under a single name. They
are declared using the struct keyword, and their members are accessed using the dot (.)
operator. Structures are used to create complex data structures and improve code
readability and maintainability.
o Discuss the concept of structure members in C programming. How are individual
members of a structure accessed and modified?
Ans:
Structure members in C are individual components of a structure that hold data. They are
accessed and modified using the dot (.) operator. Structure members allow you to
organize related data together and improve code readability and maintainability.
o Explain the difference between structures and unions in C programming. When would
you choose one over the other?
Ans: Structures allocate memory for each member individually, allowing you to store and
access different types of data together. Unions allocate enough memory to hold the
largest member and share the same memory location for all members, allowing you to
store different types of data in the same memory location. Structures are used when you
need to access multiple members simultaneously, while unions are used when you need
to store different types of data in the same memory location.
o Describe the concept of nested structures in C programming. How are structures within
structures defined and accessed?
Ans:
Nested structures in C allow you to define structures within other structures. They are
accessed using the dot (.) operator to navigate through the levels of nesting. Nested
structures are useful for organizing related data into a single structure, especially when
some data is logically grouped together.
o Discuss the concept of typedef in C programming. How is typedef used to define custom
data types, including structures and unions?
Ans: typedef in C is used to create aliases for existing data types or to define new data
types, such as structures and unions, for improved code readability and maintainability. It
allows you to define custom names for types, making your code more understandable and
easier to maintain.

File Handling:
o Explain the concept of file handling in C programming. How are files opened, read from,
and written to using standard file handling functions?
Ans: File handling in C involves opening a file using fopen(), reading from it with fscanf() or
fgets(), writing to it with fprintf() or fputs(), and closing it using fclose(). Always check for
errors when using these functions.
o Describe the role of file pointers in C programming. How are file pointers used to
navigate and manipulate files?
Ans: File pointers in C programming are variables used to keep track of the current
position in a file. They are essential for navigating and manipulating files. Here's a brief
overview of their role:
Opening Files: File pointers are used to open files for reading, writing, or both. The fopen

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

function returns a file pointer that points to the beginning of the file.
Navigating Files: File pointers are moved within a file using functions like fseek and
rewind. fseek allows you to move the pointer to a specific location in the file, while rewind
moves the pointer to the beginning of the file.
Reading and Writing: File pointers are used with functions like fread, fwrite, fprintf, and
fscanf to read from and write to files. These functions use the file pointer to determine
where to read from or write to in the file.
Closing Files: File pointers are used to close files with the fclose function. Closing a file
pointer releases the resources associated with the file and prevents further operations on
the file.
In short, file pointers are crucial for managing files in C, allowing you to navigate, read
from, and write to files efficiently.

o Discuss the difference between text files and binary files in C programming. How are
they opened and processed differently?
Ans: In C programming, text files and binary files are opened and processed differently
due to their distinct internal representations and intended uses.
Text Files: Text files are files that contain plain text characters. Each character is
represented by its ASCII or Unicode value. Text files are human-readable and typically
used for storing textual data like source code, configuration files, and documents.
Opening Text Files: Text files are opened using the fopen() function with the mode "r" for
reading, "w" for writing (creating a new file or overwriting an existing one), or "a" for
appending to an existing file.
Processing Text Files: Text files are processed character by character using functions like
fgetc() for reading a character, fputc() for writing a character, fgets() for reading a line, and
fputs() for writing a line. Text files are often processed until an end-of-file (EOF) marker is
reached.
Binary Files: Binary files contain data in a format that is not human-readable. They can
store any type of data, including integers, floats, structures, and images. Binary files
preserve the exact byte representation of the data.
Opening Binary Files: Binary files are opened using the fopen() function with the mode
"rb" for reading, "wb" for writing (creating a new file or overwriting an existing one), or
"ab" for appending to an existing file in binary mode.
Processing Binary Files: Binary files are processed using functions like fread() for reading a
block of data, fwrite() for writing a block of data, and fseek() for moving the file position
indicator. The data in binary files is processed based on the size and format of the data
being read or written.

o Explain the purpose of file modes in C programming. Provide examples of different file
modes like "r", "w", "a", etc.
Ans: File modes in C specify how a file should be opened and used. Here's a brief
summary:
"r": Read mode. Opens a file for reading. File must exist.
"w": Write mode. Opens a file for writing. If the file exists, its contents are overwritten. If
not, a new file is created.
"a": Append mode. Opens a file for appending. Data is written to the end of the file
without overwriting existing content. If the file does not exist, a new file is created.

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

"r+": Read and write mode. Opens a file for both reading and writing. File must exist.
"w+": Write and read mode. Opens a file for reading and writing. If the file exists, its
contents are overwritten. If not, a new file is created.
"a+": Append and read mode. Opens a file for reading and appending. Data can be written
to the end of the file, and existing content can be read. If the file does not exist, a new file
is created.
Binary modes ("rb", "wb", "ab", "r+b", "w+b", "a+b") are also available for working with
binary files.
o Describe error handling techniques in file operations in C programming. How are errors
detected and handled when working with files?
Ans: Error handling in file operations involves checking return values of file-related
functions for success or failure, using perror() to print error messages, and handling errors
gracefully by cleaning up resources and exiting the program if necessary.

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
1. Hello World: Print "Hello, World!" to the console
Code
#include <stdio.h>

int main() {
printf("Hello, World!\n");
return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
2. Factorial: Calculate the factorial of a given number.
#include <stdio.h>

int main() {
int number, i;
unsigned long long factorial = 1;
FILE *input_file, *output_file;

input_file = fopen("input.txt", "r");


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

output_file = fopen("output.txt", "w");


if (output_file == NULL) {
printf("Error opening output file.\n");
fclose(input_file);
return 1;
}

fscanf(input_file, "%d", &number);


if (number < 0) {
fprintf(output_file, "Error: Factorial of a negative number doesn't exist.\n");
} else {
for (i = 1; i <= number; ++i) {
factorial *= i;
}
fprintf(output_file, "Factorial of %d = %llu\n", number, factorial);
}
fclose(input_file);
fclose(output_file);

return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
3. Prime Numbers: Determine whether a given number is prime.
Code
#include <stdio.h>
#include <math.h>

int isPrime(int num) {


if (num <= 1) {
return 0; // 0 and 1 are not prime
}
int i;
for (i = 2; i <= sqrt(num); ++i) {
if (num % i == 0) {
return 0; // not prime
}
}
return 1;
}
int main() {
int number;
FILE *input_file, *output_file;
input_file = fopen("input.txt", "r");
if (input_file == NULL) {
return 1;
}
output_file = fopen("output.txt", "w");
if (output_file == NULL) {
fclose(input_file);
return 1;
}
fscanf(input_file, "%d", &number);
if (isPrime(number)) {
fprintf(output_file, "%d is a prime number.", number);
} else {
fprintf(output_file, "%d is not a prime number.", number);
}
fclose(input_file);
fclose(output_file);
return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
4. Fibonacci Series: Generate the Fibonacci series up to a certain limit.
Code
#include <stdio.h>

int main() {
int limit, first = 0, second = 1, next;
FILE *input_file, *output_file;

input_file = fopen("input.txt", "r");


if (input_file == NULL) {
return 1;
}

output_file = fopen("output.txt", "w");


if (output_file == NULL) {
fclose(input_file);
return 1;
}

fscanf(input_file, "%d", &limit);

fprintf(output_file, "Fibonacci Series up to %d terms: \n", limit);


fprintf(output_file, "%d, %d, ", first, second);

next = first + second;


while (next <= limit) {
fprintf(output_file, "%d, ", next);
first = second;
second = next;
next = first + second;
}
fclose(input_file);
fclose(output_file);
return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
5. Sum of Digits: Calculate the sum of digits of a given number.
Code
#include <stdio.h>

int main() {
int number, digit, sum = 0;
FILE *inputFile, *outputFile;

inputFile = fopen("input.txt", "r");


outputFile = fopen("output.txt", "w");

if (inputFile == NULL || outputFile == NULL) {


printf("Error opening files!\n");
return 1;
}

fscanf(inputFile, "%d", &number);

while (number > 0) {


digit = number % 10;
sum += digit;
number /= 10;
}

fprintf(outputFile, "Sum of digits: %d\n", sum);


fclose(inputFile);
fclose(outputFile);
return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
6. Reverse a Number: Reverse the digits of a given number
Code
#include <stdio.h>
int main() {
int number, reversedNumber = 0, remainder;
FILE *input_file, *output_file;
// Open input file for reading
input_file = fopen("input.txt", "r");
if (input_file == NULL) {
return 1;
}
// Open output file for writing
output_file = fopen("output.txt", "w");
if (output_file == NULL) {
fclose(input_file);
return 1;
}
// Read number from input file
fscanf(input_file, "%d", &number);
// Reverse the number
while (number != 0) {
remainder = number % 10;
reversedNumber = reversedNumber * 10 + remainder;
number /= 10;
}
// Print the reversed number to output file
fprintf(output_file, "Reversed number: %d", reversedNumber);
// Close files
fclose(input_file);
fclose(output_file);
return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
7. Palindrome Check: Check if a given number or string is a palindrome.
Code
#include <stdio.h>
#include <string.h>

int isPalindrome(char *str) {


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

while (end > start) {


if (str[start++] != str[end--]) {
return 0; // Not a palindrome
}
}
return 1; // Palindrome
}

int main() {
FILE *inputFile, *outputFile;
char str[100];

// Open input and output files


inputFile = fopen("input.txt", "r");
outputFile = fopen("output.txt", "w");

// Check if files opened successfully


if (inputFile == NULL || outputFile == NULL) {
printf("Error opening files!\n");
return 1;
}

// Read string from input file


fscanf(inputFile, "%s", str);

// Check if string is palindrome


if (isPalindrome(str)) {
fprintf(outputFile, "%s is a palindrome.\n", str);
} else {
fprintf(outputFile, "%s is not a palindrome.\n", str);
}

// Close files
fclose(inputFile);
fclose(outputFile);

return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
8. Area of Shapes: Calculate the area of shapes like rectangle, triangle, and circle.
#include <stdio.h>
#include <math.h>

float rectangleArea(float length, float width) {


return length * width;
}

float triangleArea(float base, float height) {


return 0.5 * base * height;
}

float circleArea(float radius) {


return M_PI * radius * radius;
}

int main() {
int choice;
float length, width, base, height, radius, area;
FILE *input_file, *output_file;

// Open input file for reading


input_file = fopen("input.txt", "r");
if (input_file == NULL) {
return 1;
}

// Open output file for writing


output_file = fopen("output.txt", "w");
if (output_file == NULL) {
fclose(input_file);
return 1;
}

// Read choice from input file


fscanf(input_file, "%d", &choice);

switch (choice) {
case 1:
// Read length and width from input file
fscanf(input_file, "%f %f", &length, &width);
area = rectangleArea(length, width);
fprintf(output_file, "Area of the rectangle: %.2f\n", area);
break;
case 2:
// Read base and height from input file
fscanf(input_file, "%f %f", &base, &height);
area = triangleArea(base, height);
fprintf(output_file, "Area of the triangle: %.2f\n", area);
break;
case 3:
// Read radius from input file
fscanf(input_file, "%f", &radius);
area = circleArea(radius);
fprintf(output_file, "Area of the circle: %.2f\n", area);
break;
default:
fprintf(output_file, "Invalid choice.\n");
}

// Close files
fclose(input_file);
fclose(output_file);

return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
9. Simple Calculator: Implement a basic calculator with arithmetic operations.
Code
#include <stdio.h>

int main() {
char operator;
double num1, num2, result;
FILE *inputFile, *outputFile;

// Open input and output files


inputFile = fopen("input.txt", "r");
outputFile = fopen("output.txt", "w");

// Check if files opened successfully


if (inputFile == NULL || outputFile == NULL) {
printf("Error opening files!\n");
return 1;
}

// Read operator and operands from input file


fscanf(inputFile, "%c %lf %lf", &operator, &num1, &num2);

// Perform operation based on operator


switch (operator) {
case '+':
result = num1 + num2;
fprintf(outputFile, "Result: %.2lf\n", result);
break;
case '-':
result = num1 - num2;
fprintf(outputFile, "Result: %.2lf\n", result);
break;
case '*':
result = num1 * num2;
fprintf(outputFile, "Result: %.2lf\n", result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
fprintf(outputFile, "Result: %.2lf\n", result);
} else {
fprintf(outputFile, "Error: Division by zero\n");
}
break;
default:
fprintf(outputFile, "Error: Invalid operator\n");
}

// Close files
fclose(inputFile);
fclose(outputFile);

return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
10. Array Operations: Perform operations like finding the largest/smallest element,
sum, and average of an array.
Code
#include <stdio.h>

int main() {
int arr[100], n, i;
int sum = 0, largest, smallest;

// Input the number of elements in the array


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

// Input array elements


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

// Find the largest and smallest elements


largest = smallest = arr[0];
for (i = 1; i < n; i++) {
if (arr[i] > largest) {
largest = arr[i];
}
if (arr[i] < smallest) {
smallest = arr[i];
}
}

// Calculate the average


double average = (double)sum / n;

// Output the results


printf("Sum: %d\n", sum);
printf("Average: %.2lf\n", average);
printf("Largest element: %d\n", largest);
printf("Smallest element: %d\n", smallest);

return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
11. String Operations: Manipulate strings such as concatenation, copying, and
comparison.
Code
#include <stdio.h>
#include <string.h>

int main() {
char str1[100], str2[100], str3[200];

FILE *input_file, *output_file;

// Open input file for reading


input_file = fopen("input.txt", "r");
if (input_file == NULL) {
return 1;
}

// Open output file for writing


output_file = fopen("output.txt", "w");
if (output_file == NULL) {
fclose(input_file);
return 1;
}

// Read two strings from input file


fscanf(input_file, "%s %s", str1, str2);

// Concatenate str2 to str1


strcat(str1, str2);
fprintf(output_file, "Concatenated string: %s\n", str1);

// Copy str1 to str3


strcpy(str3, str1);
fprintf(output_file, "Copied string: %s\n", str3);

// Compare str1 and str2


int result = strcmp(str1, str2);
if (result == 0) {
fprintf(output_file, "Strings are equal.\n");
} else {
fprintf(output_file, "Strings are not equal.\n");
}

// Close files
fclose(input_file);
fclose(output_file);

return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
12. Linear Search: Search for an element in an array using linear search.
Code
#include <stdio.h>

int linearSearch(int arr[], int n, int key) {


for (int i = 0; i < n; i++) {
if (arr[i] == key) {
return i; // Element found, return its index
}
}
return -1; // Element not found
}

int main() {
FILE *inputFile, *outputFile;
int arr[100], n, key, index;

// Open input and output files


inputFile = fopen("input.txt", "r");
outputFile = fopen("output.txt", "w");

// Check if files opened successfully


if (inputFile == NULL || outputFile == NULL) {
printf("Error opening files!\n");
return 1;
}

// Read the number of elements from the input file


fscanf(inputFile, "%d", &n);

// Read array elements from the input file


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

// Read the element to search for from the input file


fscanf(inputFile, "%d", &key);

// Perform linear search


index = linearSearch(arr, n, key);

// Write search result to the output file


if (index != -1) {
fprintf(outputFile, "Element found at index %d.\n", index);
} else {
fprintf(outputFile, "Element not found.\n");
}

// Close files
fclose(inputFile);
fclose(outputFile);

return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
13. Binary Search: Search for an element in a sorted array using binary search.
#include <stdio.h>

int binarySearch(int arr[], int n, int key) {


int low = 0, high = n - 1;

while (low <= high) {


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

// If the element is present at the middle


if (arr[mid] == key) {
return mid;
}

// If the element is smaller, ignore the right half


else if (arr[mid] > key) {
high = mid - 1;
}

// If the element is larger, ignore the left half


else {
low = mid + 1;
}
}

// Element not found


return -1;
}

int main() {
FILE *inputFile, *outputFile;
int arr[100], n, key, result;

// Open input and output files


inputFile = fopen("input.txt", "r");
outputFile = fopen("output.txt", "w");

// Check if files opened successfully


if (inputFile == NULL || outputFile == NULL) {
printf("Error opening files!\n");
return 1;
}

// Read the number of elements from the input file


fscanf(inputFile, "%d", &n);

// Read array elements from the input file


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

// Read the element to search for from the input file


fscanf(inputFile, "%d", &key);

// Ensure the array is sorted for binary search (optional)


// You can add code here to sort the array if needed

// Perform binary search


result = binarySearch(arr, n, key);

// Write search result to the output file


if (result != -1) {
fprintf(outputFile, "Element found at index %d.\n", result);
} else {
fprintf(outputFile, "Element not found.\n");
}

// Close files
fclose(inputFile);
fclose(outputFile);

return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
14. Selection Sort: Sort an array using the selection sort algorithm.
Code
#include <stdio.h>

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


int i, j, minIndex, temp;
for (i = 0; i < n - 1; i++) {
minIndex = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element of the unsorted subarray
temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}

int main() {
FILE *inputFile, *outputFile;
int arr[100], n, i;

// Open input and output files


inputFile = fopen("input.txt", "r");
outputFile = fopen("output.txt", "w");

// Check if files opened successfully


if (inputFile == NULL || outputFile == NULL) {
printf("Error opening files!\n");
return 1;
}

// Read the number of elements from the input file


fscanf(inputFile, "%d", &n);

// Read array elements from the input file


for (i = 0; i < n; i++) {
fscanf(inputFile, "%d", &arr[i]);
}

// Sort the array using selection sort


selectionSort(arr, n);

// Print the sorted array to the output file


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

// Close files
fclose(inputFile);
fclose(outputFile);

return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
15. Bubble Sort: Sort an array using the bubble sort algorithm.
#include <stdio.h>

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


int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j + 1]
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

int main() {
FILE *inputFile, *outputFile;
int arr[100], n, i;

// Open input and output files


inputFile = fopen("input.txt", "r");
outputFile = fopen("output.txt", "w");

// Check if files opened successfully


if (inputFile == NULL || outputFile == NULL) {
printf("Error opening files!\n");
return 1;
}

// Read the number of elements from the input file


fscanf(inputFile, "%d", &n);

// Read array elements from the input file


for (i = 0; i < n; i++) {
fscanf(inputFile, "%d", &arr[i]);
}

// Sort the array using bubble sort


bubbleSort(arr, n);

// Print the sorted array to the output file


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

// Close files
fclose(inputFile);
fclose(outputFile);

return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
16. Insertion Sort: Sort an array using the insertion sort algorithm.
#include <stdio.h>

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


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

// Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

int main() {
FILE *inputFile, *outputFile;
int arr[100], n, i;

// Open input and output files


inputFile = fopen("input.txt", "r");
outputFile = fopen("output.txt", "w");

// Check if files opened successfully


if (inputFile == NULL || outputFile == NULL) {
printf("Error opening files!\n");
return 1;
}

// Read the number of elements from the input file


fscanf(inputFile, "%d", &n);

// Read array elements from the input file


for (i = 0; i < n; i++) {
fscanf(inputFile, "%d", &arr[i]);
}

// Sort the array using insertion sort


insertionSort(arr, n);

// Print the sorted array to the output file


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

// Close files
fclose(inputFile);
fclose(outputFile);

return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- B
17. Matrix Operations: Perform matrix addition, subtraction, multiplication, and transpose.
#include <stdio.h>

#define N 3 // Size of the square matrices

void addMatrices(int A[][N], int B[][N], int C[][N]) {


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
}

void subtractMatrices(int A[][N], int B[][N], int C[][N]) {


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
C[i][j] = A[i][j] - B[i][j];
}
}
}

void multiplyMatrices(int A[][N], int B[][N], int C[][N]) {


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
C[i][j] = 0;
for (int k = 0; k < N; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
}

void transposeMatrix(int A[][N], int C[][N]) {


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
C[i][j] = A[j][i];
}
}
}

void displayMatrix(int A[][N], FILE* outputFile) {


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
fprintf(outputFile, "%d ", A[i][j]);
}
fprintf(outputFile, "\n");
}
}

int main() {
FILE *inputFile, *outputFile;
int N, A[N][N], B[N][N], C[N][N];

// Open input and output files


inputFile = fopen("input.txt", "r");
outputFile = fopen("output.txt", "w");

// Check if files opened successfully


if (inputFile == NULL || outputFile == NULL) {
printf("Error opening files!\n");
return 1;
}

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

// Read matrix dimensions (N) from the input file


fscanf(inputFile, "%d", &N);

// Read matrix A from the input file


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
fscanf(inputFile, "%d", &A[i][j]);
}
}

// Read matrix B from the input file


for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
fscanf(inputFile, "%d", &B[i][j]);
}
}

// Addition
addMatrices(A, B, C);
fprintf(outputFile, "Addition Result:\n");
displayMatrix(C, outputFile);

// Subtraction
subtractMatrices(A, B, C);
fprintf(outputFile, "Subtraction Result:\n");
displayMatrix(C, outputFile);

// Multiplication
multiplyMatrices(A, B, C);
fprintf(outputFile, "Multiplication Result:\n");
displayMatrix(C, outputFile);

// Transpose
transposeMatrix(A, C);
fprintf(outputFile, "Transpose of A:\n");
displayMatrix(C, outputFile);

// Close files
fclose(inputFile);
fclose(outputFile);

return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
1.Linked List insert end
#include <stdio.h>
#include <stdlib.h>

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

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


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = newData;
newNode->next = NULL;

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

struct Node* last = *head;


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

void printListToFile(struct Node* head, FILE* outputFile) {


struct Node* temp = head;
while (temp != NULL) {
fprintf(outputFile, "%d ", temp->data);
temp = temp->next;
}
fprintf(outputFile, "\n"); // Add a newline at the end
}

int main() {
FILE* inputFile = fopen("input.txt", "r"); // Open input file for reading
FILE* outputFile = fopen("output.txt", "w"); // Open output file for writing

if (inputFile == NULL || outputFile == NULL) {


printf("Error opening files!\n");
return 1;
}

struct Node* head = NULL;


int num;

// Read integers from the input file until EOF (End-Of-File)


while (fscanf(inputFile, "%d", &num) != EOF) {
insertAtEnd(&head, num);
}

printListToFile(head, outputFile); // Print the linked list to the output file

fclose(inputFile);
fclose(outputFile);

return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
2. Stack Implementation using Linked List
#include <stdio.h>
#include <stdlib.h>

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

struct StackNode* newNode(int data) {


struct StackNode* stackNode = (struct StackNode*)malloc(sizeof(struct StackNode));
stackNode->data = data;
stackNode->next = NULL;
return stackNode;
}

int isEmpty(struct StackNode* root) {


return !root;
}

void push(struct StackNode** root, int data) {


struct StackNode* stackNode = newNode(data);
stackNode->next = *root;
*root = stackNode;
}

int pop(struct StackNode** root) {


if (isEmpty(*root)) {
printf("Stack Underflow\n");
return INT_MIN;
}
struct StackNode* temp = *root;
*root = (*root)->next;
int popped = temp->data;
free(temp);
return popped;
}

int peek(struct StackNode* root) {


if (isEmpty(root)) {
printf("Stack is Empty\n");
return INT_MIN;
}
return root->data;
}

void printStackToFile(struct StackNode* root, FILE* outputFile) {


if (isEmpty(root)) {
fprintf(outputFile, "Stack is Empty\n");
return;
}

struct StackNode* temp = root;


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

int main() {
FILE* inputFile = fopen("input.txt", "r"); // Open input file for reading
FILE* outputFile = fopen("output.txt", "w"); // Open output file for writing

if (inputFile == NULL || outputFile == NULL) {


printf("Error opening files!\n");
return 1;
}

struct StackNode* root = NULL;


int num;

// Read integers from the input file until EOF (End-Of-File)


while (fscanf(inputFile, "%d", &num) != EOF) {
push(&root, num);
}

printStackToFile(root, outputFile); // Print the stack to the output file

fclose(inputFile);
fclose(outputFile);

return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
3. Queue Implementation using Arrays
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 1000 // Adjust this as needed

struct Queue {
int capacity;
int front, rear;
int* array;
};

struct Queue* createQueue(unsigned capacity) {


struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->capacity = capacity;
queue->front = queue->size = 0;
queue->rear = capacity - 1;
queue->array = (int*)malloc(queue->capacity * sizeof(int));
return queue;
}

int isFull(struct Queue* queue) {


return (queue->size == queue->capacity);
}

int isEmpty(struct Queue* queue) {


return (queue->size == 0);
}

void enqueue(struct Queue* queue, int item) {


if (isFull(queue)) {
printf("Queue Overflow\n");
return;
}
queue->rear = (queue->rear + 1) % queue->capacity;
queue->array[queue->rear] = item;
queue->size = queue->size + 1;
}

int dequeue(struct Queue* queue) {


if (isEmpty(queue)) {
printf("Queue Underflow\n");
return -1;
}
int item = queue->array[queue->front];
queue->front = (queue->front + 1) % queue->capacity;
queue->size = queue->size - 1;
return item;
}

void printQueueToFile(struct Queue* queue, FILE* outputFile) {


if (isEmpty(queue)) {
fprintf(outputFile, "Queue is Empty\n");
return;
}

for (int i = queue->front; i < queue->front + queue->size; i++) {


fprintf(outputFile, "%d ", queue->array[i % queue->capacity]);
}
fprintf(outputFile, "\n");
}

int main() {
FILE* inputFile = fopen("input.txt", "r"); // Open input file for reading
FILE* outputFile = fopen("output.txt", "w"); // Open output file for writing

if (inputFile == NULL || outputFile == NULL) {


printf("Error opening files!\n");
return 1;
}

struct Queue* queue = createQueue(MAX_SIZE);


int num;

// Read integers from the input file until EOF (End-Of-File)


while (fscanf(inputFile, "%d", &num) != EOF) {
enqueue(queue, num);
}

printQueueToFile(queue, outputFile); // Print the queue contents to the output file

fclose(inputFile);
fclose(outputFile);

return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C

4. Binary Search Tree (BST) Insertion


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

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

struct Node* newNode(int item) {


struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}

struct Node* insert(struct Node* node, int key) {


if (node == NULL) return newNode(key);
if (key < node->key) node->left = insert(node->left, key);
else if (key > node->key) node->right = insert(node->right, key);
return node;
}

void inOrderTraversal(struct Node* root, FILE* outputFile) {


if (root != NULL) {
inOrderTraversal(root->left, outputFile);
fprintf(outputFile, "%d ", root->key);
inOrderTraversal(root->right, outputFile);
}
}

int main() {
FILE* inputFile = fopen("input.txt", "r"); // Open input file for reading
FILE* outputFile = fopen("output.txt", "w"); // Open output file for writing

if (inputFile == NULL || outputFile == NULL) {


printf("Error opening files!\n");
return 1;
}

struct Node* root = NULL;


int num;

// Read integers from the input file until EOF (End-Of-File)


while (fscanf(inputFile, "%d", &num) != EOF) {
root = insert(root, num);
}

fprintf(outputFile, "Inorder traversal: ");


inOrderTraversal(root, outputFile);
fprintf(outputFile, "\n"); // Add a newline at the end

fclose(inputFile);
fclose(outputFile);

return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
5. Graph Representation using Adjacency List
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct AdjListNode {
int dest;
struct AdjListNode* next;
};

struct AdjList {
struct AdjListNode* head;
};

struct Graph {
int V;
struct AdjList* array;
};

struct AdjListNode* newAdjListNode(int dest) {


struct AdjListNode* newNode = (struct AdjListNode*)malloc(sizeof(struct AdjListNode));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}

struct Graph* createGraph(int V) {


struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->V = V;
graph->array = (struct AdjList*)malloc(V * sizeof(struct AdjList));
for (int i = 0; i < V; ++i)
graph->array[i].head = NULL;
return graph;
}

void addEdge(struct Graph* graph, int src, int dest) {


struct AdjListNode* newNode = newAdjListNode(dest);
newNode->next = graph->array[src].head;
graph->array[src].head = newNode;

newNode = newAdjListNode(src);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
}

void printGraph(struct Graph* graph, FILE *outFile) {


for (int v = 0; v < graph->V; ++v) {
struct AdjListNode* pCrawl = graph->array[v].head;
fprintf(outFile, "\n Adjacency list of vertex %d\n head ", v);
while (pCrawl) {
fprintf(outFile, "-> %d", pCrawl->dest);
pCrawl = pCrawl->next;
}
fprintf(outFile, "\n");
}
}

int main() {
FILE *inFile = fopen("input.txt", "r");
FILE *outFile = fopen("output.txt", "w");

int V;
fscanf(inFile, "%d", &V);

struct Graph* graph = createGraph(V);

int src, dest;


while (fscanf(inFile, "%d %d", &src, &dest) != EOF) {
addEdge(graph, src, dest);
}

printGraph(graph, outFile);

fclose(inFile);
fclose(outFile);

return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
6.Insert front in singly circular linked list
#include <stdio.h>
#include <stdlib.h>

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

void insertFront(struct Node** head_ref, int new_data) {


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref;

new_node->data = new_data;

if (*head_ref == NULL) {
new_node->next = new_node;
} else {
while (last->next != *head_ref) {
last = last->next;
}
new_node->next = *head_ref;
last->next = new_node;
}

*head_ref = new_node;
}

void printList(struct Node* head, FILE *outFile) {


struct Node* temp = head;
if (head != NULL) {
do {
fprintf(outFile, "%d ", temp->data);
temp = temp->next;
} while (temp != head);
}
fprintf(outFile, "\n");
}

int main() {
FILE *inFile = fopen("input.txt", "r");
FILE *outFile = fopen("output.txt", "w");

struct Node* head = NULL;


int data;
while (fscanf(inFile, "%d", &data) != EOF) {
insertFront(&head, data);
}

printf("Singly Circular Linked List: ");


printList(head, outFile);

fclose(inFile);
fclose(outFile);

return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
7.Delete end singly circular linked list.
#include <stdio.h>
#include <stdlib.h>

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

void insertFront(struct Node** head_ref, int new_data) {


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref;

new_node->data = new_data;

if (*head_ref == NULL) {
new_node->next = new_node;
} else {
while (last->next != *head_ref) {
last = last->next;
}
new_node->next = *head_ref;
last->next = new_node;
}

*head_ref = new_node;
}

void insertEnd(struct Node** head_ref, int new_data) {


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref;

new_node->data = new_data;
new_node->next = *head_ref;

if (*head_ref == NULL) {
*head_ref = new_node;
} else {
while (last->next != *head_ref) {
last = last->next;
}
last->next = new_node;
}
}

void deleteEnd(struct Node** head_ref) {


if (*head_ref == NULL) {
return;
}

struct Node* temp = *head_ref;


struct Node* prev = NULL;

while (temp->next != *head_ref) {


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

if (prev == NULL) {
*head_ref = NULL;
} else {
prev->next = temp->next;
}

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

free(temp);
}

void readDataFromFile(struct Node** head_ref, const char* filename) {


FILE* fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error opening file\n");
return;
}

int data;
while (fscanf(fp, "%d", &data) != EOF) {
insertEnd(head_ref, data);
}

fclose(fp);
}

void printListToFile(struct Node* head, const char* filename) {


FILE* fp = fopen(filename, "w");
if (fp == NULL) {
printf("Error opening file\n");
return;
}

struct Node* temp = head;


if (head != NULL) {
do {
fprintf(fp, "%d ", temp->data);
temp = temp->next;
} while (temp != head);
}

fprintf(fp, "\n");
fclose(fp);
}

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

readDataFromFile(&head, "data.txt");

printf("Singly Circular Linked List after reading from file: ");


printList(head);
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
8. Delete Front singly circular linked list.
#include <stdio.h>
#include <stdlib.h>

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

// Function to insert a node at the front of the list


void insertFront(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref;

new_node->data = new_data;

if (*head_ref == NULL) {
new_node->next = new_node;
} else {
while (last->next != *head_ref) {
last = last->next;
}
new_node->next = *head_ref;
last->next = new_node;
}

*head_ref = new_node;
}

// Function to insert a node at the end of the list


void insertEnd(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref;

new_node->data = new_data;
new_node->next = *head_ref;

if (*head_ref == NULL) {
*head_ref = new_node;
} else {
while (last->next != *head_ref) {
last = last->next;
}
last->next = new_node;
}
}

// Function to delete a node from the front of the list


void deleteFront(struct Node** head_ref) {
if (*head_ref == NULL) {
return;
}

struct Node* temp = *head_ref;


struct Node* last = *head_ref;

if (*head_ref == last) { // Handle single-node case


*head_ref = NULL;
} else {
while (last->next != *head_ref) {
last = last->next;
}
*head_ref = (*head_ref)->next;
last->next = *head_ref;
}

free(temp);
}

// Function to read data from a file and insert nodes into the list
void readDataFromFile(struct Node** head_ref, const char* filename) {

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

FILE* fp = fopen(filename, "r");


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

int data;
while (fscanf(fp, "%d", &data) != EOF) {
insertEnd(head_ref, data); // Modify to insertFront if desired
}

fclose(fp);
}

// Function to print the list contents to a file


void printListToFile(struct Node* head, const char* filename) {
FILE* fp = fopen(filename, "w");
if (fp == NULL) {
printf("Error opening file\n");
return;
}

struct Node* temp = head;


if (head != NULL) {
do {
fprintf(fp, "%d ", temp->data);
temp = temp->next;
} while (temp != head);
}

fprintf(fp, "\n");
fclose(fp);
}

// Function to print the list to the console


void printList(struct Node* head) {
struct Node* temp = head;
if (head != NULL) {
do {
printf("%d ", temp->data);
temp = temp->next;
} while (temp != head);
}
printf("\n");
}

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

// Read data from a file (example: "data.txt")


readDataFromFile(&head, "data.txt");

printf("Singly Circular Linked List after reading from file: ");


printList(head);
return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
9.Delete at specific location
#include <stdio.h>
#include <stdlib.h>

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

void insertFront(struct Node** head_ref, int new_data) {


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref;

new_node->data = new_data;

if (*head_ref == NULL) {
new_node->next = new_node;
} else {
while (last->next != *head_ref) {
last = last->next;
}
new_node->next = *head_ref;
last->next = new_node;
}

*head_ref = new_node;
}

void insertEnd(struct Node** head_ref, int new_data) {


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref;

new_node->data = new_data;
new_node->next = *head_ref;

if (*head_ref == NULL) {
*head_ref = new_node;
} else {
while (last->next != *head_ref) {
last = last->next;
}
last->next = new_node;
}
}

void deleteNode(struct Node** head_ref, int key) {


if (*head_ref == NULL) {
return;
}

struct Node* current = *head_ref, *prev = NULL;


while (current->data != key) {
if (current->next == *head_ref) {
printf("Key not found in the list.\n");
return;
}
prev = current;
current = current->next;
}

if (current->next == *head_ref && prev == NULL) {


*head_ref = NULL;
free(current);
return;
}

if (current == *head_ref) {
prev = (*head_ref);
while (prev->next != *head_ref)

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

prev = prev->next;
*head_ref = (*head_ref)->next;
prev->next = *head_ref;
free(current);
} else if (current->next == *head_ref) {
prev->next = *head_ref;
free(current);
} else {
prev->next = current->next;
free(current);
}
}

void printList(struct Node* head, FILE *outFile) {


struct Node* temp = head;
if (head != NULL) {
do {
fprintf(outFile, "%d ", temp->data);
temp = temp->next;
} while (temp != head);
}
fprintf(outFile, "\n");
}

int main() {
FILE *inFile = fopen("input.txt", "r");
FILE *outFile = fopen("output.txt", "w");

struct Node* head = NULL;


int new_data;
while (fscanf(inFile, "%d", &new_data) != EOF) {
insertEnd(&head, new_data);
}

printf("Initial List: ");


printList(head, outFile);

deleteNode(&head, 2);
printf("List after deleting node with key 2: ");
printList(head, outFile);

fclose(inFile);
fclose(outFile);

return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
10.Insert Specific code
#include <stdio.h>
#include <stdlib.h>

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

void insertFront(struct Node** head_ref, int new_data) {


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref;

new_node->data = new_data;

if (*head_ref == NULL) {
new_node->next = new_node;
*head_ref = new_node;
} else {
while (last->next != *head_ref) {
last = last->next;
}
new_node->next = *head_ref;
last->next = new_node;
*head_ref = new_node;
}
}

void insertEnd(struct Node** head_ref, int new_data) {


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
struct Node* last = *head_ref;

new_node->data = new_data;

if (*head_ref == NULL) {
new_node->next = new_node;
*head_ref = new_node;
} else {
while (last->next != *head_ref) {
last = last->next;
}
last->next = new_node;
new_node->next = *head_ref;
}
}

void insertAtPosition(struct Node** head_ref, int position, int new_data) {


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

if (position == 1) {
insertFront(head_ref, new_data);
return;
}

struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));


struct Node* current = *head_ref;
int count = 1;

new_node->data = new_data;

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

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


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

if (count < position - 1) {


printf("Position is greater than the number of nodes\n");
return;
}

new_node->next = current->next;
current->next = new_node;
}

void printList(struct Node* head, FILE *outFile) {


struct Node* temp = head;
if (head != NULL) {
do {
fprintf(outFile, "%d ", temp->data);
temp = temp->next;
} while (temp != head);
}
fprintf(outFile, "\n");
}

int main() {
FILE *inFile = fopen("input.txt", "r");
FILE *outFile = fopen("output.txt", "w");

struct Node* head = NULL;


int new_data, position;
char action;

while (fscanf(inFile, "%c %d %d", &action, &position, &new_data) != EOF) {


if (action == 'F') {
insertFront(&head, new_data);
} else if (action == 'E') {
insertEnd(&head, new_data);
} else if (action == 'P') {
insertAtPosition(&head, position, new_data);
}
}

printf("Singly Circular Linked List: ");


printList(head, outFile);

fclose(inFile);
fclose(outFile);

return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
11.Display elements in linked list
#include <stdio.h>
#include <stdlib.h>

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

void displayList(struct Node* head, FILE* outFile) {


struct Node* temp = head;
while (temp != NULL) {
fprintf(outFile, "%d -> ", temp->data);
temp = temp->next;
}
fprintf(outFile, "NULL\n");
}

int main() {
FILE *inFile = fopen("input.txt", "r");
FILE *outFile = fopen("output.txt", "w");

struct Node* head = NULL;


struct Node* current = NULL;
int data;

while (fscanf(inFile, "%d", &data) != EOF) {


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

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

displayList(head, outFile);

fclose(inFile);
fclose(outFile);

return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
12.Merged two sorted Linked List
#include <stdio.h>
#include <stdlib.h>

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

struct Node* mergeLists(struct Node* l1, struct Node* l2) {


struct Node dummy;
struct Node* tail = &dummy;
dummy.next = NULL;

while (1) {
if (l1 == NULL) {
tail->next = l2;
break;
}
if (l2 == NULL) {
tail->next = l1;
break;
}

if (l1->data <= l2->data) {


tail->next = l1;
l1 = l1->next;
} else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
return dummy.next;
}

void display(struct Node* head, FILE* outFile) {


struct Node* temp = head;
while (temp != NULL) {
fprintf(outFile, "%d ", temp->data);
temp = temp->next;
}
fprintf(outFile, "\n");
}

int main() {
FILE *inFile = fopen("input.txt", "r");
FILE *outFile = fopen("output.txt", "w");

struct Node* l1 = NULL;


struct Node* l2 = NULL;
struct Node* current = NULL;
int data;

// Read data for l1


while (fscanf(inFile, "%d", &data) != EOF) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

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

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

// Read data for l2


while (fscanf(inFile, "%d", &data) != EOF) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;

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

struct Node* mergedList = mergeLists(l1, l2);


display(mergedList, outFile);

fclose(inFile);
fclose(outFile);

return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
13.Reverse Linked List
#include <stdio.h>
#include <stdlib.h>

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

struct Node* head = NULL;

void insertAtBeginning(int data) {


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

void reverse() {
struct Node *prev, *current, *next;
prev = NULL;
current = head;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
}

void display(FILE* outFile) {


struct Node* temp = head;
while (temp != NULL) {
fprintf(outFile, "%d ", temp->data);
temp = temp->next;
}
fprintf(outFile, "\n");
}

int main() {
FILE *inFile = fopen("input.txt", "r");
FILE *outFile = fopen("output.txt", "w");

int data;
while (fscanf(inFile, "%d", &data) != EOF) {
insertAtBeginning(data);
}

printf("Original list: ");


display(outFile);
reverse();
printf("Reversed list: ");
display(outFile);

fclose(inFile);
fclose(outFile);
return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
14.Spilt the linked list
#include <stdio.h>
#include <stdlib.h>

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

struct Node* head = NULL;

void insertAtEnd(int data) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
struct Node* temp = head;
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
head->next = head;
return;
}
while (temp->next != head) {
temp = temp->next;
}
temp->next = newNode;
newNode->next = head;
}

void splitCircularList(FILE* outFile) {


struct Node *slow_ptr = head, *fast_ptr = head;

if (head == NULL)
return;

while (fast_ptr->next != head && fast_ptr->next->next != head) {


fast_ptr = fast_ptr->next->next;
slow_ptr = slow_ptr->next;
}

if (fast_ptr->next->next == head) {
fast_ptr = fast_ptr->next;
}

struct Node* head1 = head;


struct Node* head2 = slow_ptr->next;

fast_ptr->next = head2;

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

slow_ptr->next = head1;

struct Node* temp = head1;


do {
fprintf(outFile, "%d ", temp->data);
temp = temp->next;
} while (temp != head1);
fprintf(outFile, "\n");

temp = head2;
do {
fprintf(outFile, "%d ", temp->data);
temp = temp->next;
} while (temp != head2);
fprintf(outFile, "\n");
}

int main() {
FILE *outFile = fopen("output.txt", "w");

insertAtEnd(1);
insertAtEnd(2);
insertAtEnd(3);
insertAtEnd(4);
insertAtEnd(5);
insertAtEnd(6);
insertAtEnd(7);
insertAtEnd(8);

splitCircularList(outFile);

fclose(outFile);

return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
15. Josephus Problem Using a Singly Circular Linked List
#include <stdio.h>
#include <stdlib.h>

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

struct Node* head = NULL;

void createCircularList(int n) {
for (int i = 1; i <= n; i++) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = i;
if (head == NULL) {
head = newNode;
head->next = head;
} else {
struct Node* temp = head;
while (temp->next != head) {
temp = temp->next;
}
temp->next = newNode;
newNode->next = head;
}
}
}

void josephus(int k, FILE* outFile) {


struct Node *prev = head, *current = head;
while (prev->next != prev) {
for (int i = 1; i < k; i++) {
prev = current;
current = current->next;
}
prev->next = current->next;
fprintf(outFile, "%d ", current->data);
free(current);
current = prev->next;
}
head = NULL;
}

int main() {
FILE *outFile = fopen("output.txt", "w");

int n = 7; // Number of people


int k = 3; // Elimination interval
createCircularList(n);
josephus(k, outFile);

fclose(outFile);
return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
16.Stack using array
#include <stdio.h>
#define MAX_SIZE 100

int stack[MAX_SIZE];
int top = -1;

void push(int value) {


if (top == MAX_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = value;
}

int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}

int peek() {
if (top == -1) {
printf("Stack is empty\n");
return -1;
}
return stack[top];
}

void display(FILE* outFile) {


if (top == -1) {
fprintf(outFile, "Stack is empty\n");
return;
}
fprintf(outFile, "Stack: ");
for (int i = 0; i <= top; i++) {
fprintf(outFile, "%d ", stack[i]);
}
fprintf(outFile, "\n");
}

int main() {
FILE *outFile = fopen("output.txt", "w");

push(1);
push(2);
push(3);
push(4);
display(outFile);
fprintf(outFile, "Peek: %d\n", peek());
fprintf(outFile, "Pop: %d\n", pop());
display(outFile);

fclose(outFile);
return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
17. Stack using Linked list
#include <stdio.h>
#include <stdlib.h>

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

struct Node* top = NULL;

void push(int value) {


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

int pop() {
if (top == NULL) {
printf("Stack Underflow\n");
return -1;
}
struct Node* temp = top;
int poppedValue = temp->data;
top = top->next;
free(temp);
return poppedValue;
}

int peek() {
if (top == NULL) {
printf("Stack is empty\n");
return -1;
}
return top->data;
}

void display(FILE* outFile) {


if (top == NULL) {
fprintf(outFile, "Stack is empty\n");
return;
}
fprintf(outFile, "Stack: ");
struct Node* temp = top;
while (temp != NULL) {
fprintf(outFile, "%d ", temp->data);
temp = temp->next;
}
fprintf(outFile, "\n");
}

int main() {
FILE *outFile = fopen("output.txt", "w");

push(1);
push(2);
push(3);
push(4);
display(outFile);
fprintf(outFile, "Peek: %d\n", peek());
fprintf(outFile, "Pop: %d\n", pop());
display(outFile);

fclose(outFile);
return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
18. Stack using Dynamic array
#include <stdio.h>
#include <stdlib.h>

#define INITIAL_CAPACITY 10

int* stack;
int top = -1;
int capacity = INITIAL_CAPACITY;

void resize() {
capacity *= 2;
stack = (int*)realloc(stack, capacity * sizeof(int));
}

void push(int value) {


if (top == capacity - 1) {
resize();
}
stack[++top] = value;
}

int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}

int peek() {
if (top == -1) {
printf("Stack is empty\n");
return -1;
}
return stack[top];
}

void display(FILE* outFile) {


if (top == -1) {
fprintf(outFile, "Stack is empty\n");
return;
}
fprintf(outFile, "Stack: ");
for (int i = 0; i <= top; i++) {
fprintf(outFile, "%d ", stack[i]);
}
fprintf(outFile, "\n");
}

int main() {
FILE *outFile = fopen("output.txt", "w");

stack = (int*)malloc(capacity * sizeof(int));


push(1);
push(2);
push(3);
push(4);
display(outFile);
fprintf(outFile, "Peek: %d\n", peek());
fprintf(outFile, "Pop: %d\n", pop());
display(outFile);

free(stack);
fclose(outFile);
return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
19.Stack using static array
#include <stdio.h>
#define MAX_SIZE 5

int stack[MAX_SIZE];
int top = -1;

void push(int value) {


if (top == MAX_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = value;
}

int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}

int peek() {
if (top == -1) {
printf("Stack is empty\n");
return -1;
}
return stack[top];
}

void display(FILE* outFile) {


if (top == -1) {
fprintf(outFile, "Stack is empty\n");
return;
}
fprintf(outFile, "Stack: ");
for (int i = 0; i <= top; i++) {
fprintf(outFile, "%d ", stack[i]);
}
fprintf(outFile, "\n");
}

int main() {
FILE *outFile = fopen("output.txt", "w");

push(1);
push(2);
push(3);
push(4);
push(5);
push(6); // This will cause a stack overflow
display(outFile);
fprintf(outFile, "Peek: %d\n", peek());
fprintf(outFile, "Pop: %d\n", pop());
display(outFile);

fclose(outFile);
return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
20. stack in C using a dynamic array with a custom Stack struct:
#include <stdio.h>
#include <stdlib.h>

#define INITIAL_CAPACITY 10

typedef struct {
int* array;
int top;
int capacity;
} Stack;

Stack* createStack() {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->array = (int*)malloc(INITIAL_CAPACITY * sizeof(int));
stack->top = -1;
stack->capacity = INITIAL_CAPACITY;
return stack;
}

void resize(Stack* stack) {


stack->capacity *= 2;
stack->array = (int*)realloc(stack->array, stack->capacity * sizeof(int));
}

void push(Stack* stack, int value) {


if (stack->top == stack->capacity - 1) {
resize(stack);
}
stack->array[++stack->top] = value;
}

int pop(Stack* stack) {


if (stack->top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack->array[stack->top--];
}

int peek(Stack* stack) {


if (stack->top == -1) {
printf("Stack is empty\n");
return -1;
}
return stack->array[stack->top];
}

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

void display(Stack* stack, FILE* outFile) {


if (stack->top == -1) {
fprintf(outFile, "Stack is empty\n");
return;
}
fprintf(outFile, "Stack: ");
for (int i = 0; i <= stack->top; i++) {
fprintf(outFile, "%d ", stack->array[i]);
}
fprintf(outFile, "\n");
}

int main() {
FILE *outFile = fopen("output.txt", "w");

Stack* stack = createStack();


push(stack, 1);
push(stack, 2);
push(stack, 3);
push(stack, 4);
display(stack, outFile);
fprintf(outFile, "Peek: %d\n", peek(stack));
fprintf(outFile, "Pop: %d\n", pop(stack));
display(stack, outFile);

// Cleanup
free(stack->array);
free(stack);
fclose(outFile);
return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
21.Queue using array
#include <stdio.h>
#define MAX_SIZE 100

int queue[MAX_SIZE];
int front = -1, rear = -1;

void enqueue(int value) {


if (rear == MAX_SIZE - 1) {
printf("Queue is full\n");
return;
}
if (front == -1)
front = 0;
rear++;
queue[rear] = value;
}

void dequeue() {
if (front == -1) {
printf("Queue is empty\n");
return;
}
printf("Dequeued element: %d\n", queue[front]);
if (front == rear)
front = rear = -1;
else
front++;
}

void display(FILE* outFile) {


if (front == -1) {
fprintf(outFile, "Queue is empty\n");
return;
}
fprintf(outFile, "Queue elements: ");
for (int i = front; i <= rear; i++)
fprintf(outFile, "%d ", queue[i]);
fprintf(outFile, "\n");
}

int main() {
FILE *outFile = fopen("output.txt", "w");

enqueue(10);
enqueue(20);
enqueue(30);
display(outFile);
dequeue();
display(outFile);

fclose(outFile);
return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
22.Queue using linked list
#include <stdio.h>
#include <stdlib.h>

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

struct Node* front = NULL;


struct Node* rear = NULL;

void enqueue(int value) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if (rear == NULL) {
front = rear = newNode;
return;
}
rear->next = newNode;
rear = newNode;
}

void dequeue(FILE* outFile) {


if (front == NULL) {
fprintf(outFile, "Queue is empty\n");
return;
}
struct Node* temp = front;
front = front->next;
if (front == NULL)
rear = NULL;
fprintf(outFile, "Dequeued element: %d\n", temp->data);
free(temp);
}

void display(FILE* outFile) {


if (front == NULL) {
fprintf(outFile, "Queue is empty\n");
return;
}
struct Node* temp = front;
fprintf(outFile, "Queue elements: ");
while (temp != NULL) {
fprintf(outFile, "%d ", temp->data);
temp = temp->next;
}
fprintf(outFile, "\n");
}

int main() {
FILE *outFile = fopen("output.txt", "w");

enqueue(10);
enqueue(20);
enqueue(30);
display(outFile);
dequeue(outFile);
display(outFile);

fclose(outFile);
return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
23. Queue using circular array
#include <stdio.h>
#define MAX_SIZE 100

int queue[MAX_SIZE];
int front = -1, rear = -1;

void enqueue(int value) {


if ((front == 0 && rear == MAX_SIZE - 1) || (rear == (front - 1) % (MAX_SIZE - 1))) {
printf("Queue is full\n");
return;
}
else if (front == -1) {
front = rear = 0;
queue[rear] = value;
}
else if (rear == MAX_SIZE - 1 && front != 0) {
rear = 0;
queue[rear] = value;
}
else {
rear++;
queue[rear] = value;
}
}

void dequeue() {
if (front == -1) {
printf("Queue is empty\n");
return;
}
int data = queue[front];
queue[front] = -1;
if (front == rear)
front = rear = -1;
else if (front == MAX_SIZE - 1)
front = 0;
else
front++;
printf("Dequeued element: %d\n", data);
}

void display() {
FILE *outFile = fopen("output.txt", "a");
if (front == -1) {
fprintf(outFile, "Queue is empty\n");
fclose(outFile);
return;
}
fprintf(outFile, "Queue elements: ");
if (rear >= front) {
for (int i = front; i <= rear; i++)
fprintf(outFile, "%d ", queue[i]);
}
else {
for (int i = front; i < MAX_SIZE; i++)
fprintf(outFile, "%d ", queue[i]);
for (int i = 0; i <= rear; i++)
fprintf(outFile, "%d ", queue[i]);
}
fprintf(outFile, "\n");
fclose(outFile);
}

int main() {
freopen("output.txt", "w", stdout);

enqueue(10);
enqueue(20);
enqueue(30);
display();
dequeue();
display();

return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
24.Queue using structure with array
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

struct Queue {
int items[MAX_SIZE];
int front;
int rear;
};

typedef struct Queue Queue;

Queue* createQueue() {
Queue* queue = (Queue*)malloc(sizeof(Queue));
queue->front = -1;
queue->rear = -1;
return queue;
}

int isEmpty(Queue* queue) {


return queue->rear == -1;
}

void enqueue(Queue* queue, int value) {


if (queue->rear == MAX_SIZE - 1)
fprintf(stdout, "Queue is full\n");
else {
if (queue->front == -1)
queue->front = 0;
queue->rear++;
queue->items[queue->rear] = value;
}
}

int dequeue(Queue* queue) {


int item;
if (isEmpty(queue)) {
fprintf(stdout, "Queue is empty\n");
return -1;
}
else {
item = queue->items[queue->front];
queue->front++;
if (queue->front > queue->rear) {
queue->front = queue->rear = -1;
}
return item;
}
}

void display(Queue* queue) {


if (isEmpty(queue))
fprintf(stdout, "Queue is empty\n");
else {
fprintf(stdout, "Queue elements: ");
for (int i = queue->front; i <= queue->rear; i++)
fprintf(stdout, "%d ", queue->items[i]);
fprintf(stdout, "\n");
}
}

int main() {
FILE *outFile = fopen("output.txt", "w");
freopen("output.txt", "w", stdout);
Queue* queue = createQueue();

enqueue(queue, 10);
enqueue(queue, 20);
enqueue(queue, 30);
display(queue);

dequeue(queue);
display(queue);

fclose(outFile);
return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
25.Title of the program
#include <stdio.h>
#include <stdlib.h>

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

struct Queue {
struct Node* front, * rear;
};

struct Queue* createQueue() {


struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue));
queue->front = queue->rear = NULL;
return queue;
}

void enqueue(struct Queue* queue, int value) {


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = NULL;
if (queue->rear == NULL) {
queue->front = queue->rear = newNode;
return;
}
queue->rear->next = newNode;
queue->rear = newNode;
}

void dequeue(struct Queue* queue) {


if (queue->front == NULL) {
fprintf(stdout, "Queue is empty\n");
return;
}
struct Node* temp = queue->front;
queue->front = queue->front->next;
if (queue->front == NULL)
queue->rear = NULL;
fprintf(stdout, "Dequeued element: %d\n", temp->data);
free(temp);
}

void display(struct Queue* queue) {


if (queue->front == NULL) {
fprintf(stdout, "Queue is empty\n");
return;
}
struct Node* temp = queue->front;
fprintf(stdout, "Queue elements: ");
while (temp != NULL) {
fprintf(stdout, "%d ", temp->data);
temp = temp->next;
}
fprintf(stdout, "\n");
}

int main() {
FILE *outFile = fopen("output.txt", "w");
freopen("output.txt", "w", stdout);
struct Queue* queue = createQueue();

enqueue(queue, 10);
enqueue(queue, 20);
enqueue(queue, 30);
display(queue);

dequeue(queue);
display(queue);

fclose(outFile);
return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
26.Circular queue
#include <stdio.h>
#define SIZE 5

int front = -1, rear = -1;


int queue[SIZE];

void enqueue(int value) {


if ((front == 0 && rear == SIZE - 1) || (rear == front - 1))
fprintf(stdout, "\nQueue is Full!!");
else {
if (front == -1) front = 0;
rear = (rear + 1) % SIZE;
queue[rear] = value;
}
}

void dequeue() {
if (front == -1)
fprintf(stdout, "\nQueue is Empty!!");
else {
fprintf(stdout, "\nDeleted Element : %d", queue[front]);
if (front == rear) {
front = -1;
rear = -1;
} else {
front = (front + 1) % SIZE;
}
}
}

void display() {
if (front == -1)
fprintf(stdout, "\nQueue is Empty!!!");
else {
int i = front;
fprintf(stdout, "\nQueue elements are: ");
if (front <= rear) {
while (i <= rear)
fprintf(stdout, "%d ", queue[i++]);
} else {
while (i <= SIZE - 1)
fprintf(stdout, "%d ", queue[i++]);
i = 0;
while (i <= rear)
fprintf(stdout, "%d ", queue[i++]);
}
}
}

int main() {
FILE *outFile = fopen("output.txt", "w");
freopen("output.txt", "w", stdout);

enqueue(1);
enqueue(2);
enqueue(3);
enqueue(4);
display();
dequeue();
display();
enqueue(5);
display();
enqueue(6);
enqueue(7);
enqueue(8);
display();

fclose(outFile);
return 0;
}

Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
27.Double ended Queue
#include <stdio.h>
#define SIZE 5

int deque[SIZE];
int front = -1, rear = -1;

void insert_front(int key) {


if ((front == 0 && rear == SIZE - 1) || (front == rear + 1))
fprintf(stdout, "\nDeque is Full");
else {
if (front == -1) {
front = 0;
rear = 0;
} else if (front == 0)
front = SIZE - 1;
else
front = front - 1;
deque[front] = key;
}
}

void insert_rear(int key) {


if ((front == 0 && rear == SIZE - 1) || (front == rear + 1))
fprintf(stdout, "\nDeque is Full");
else {
if (front == -1) {
front = 0;
rear = 0;
} else if (rear == SIZE - 1)
rear = 0;
else
rear = rear + 1;
deque[rear] = key;
}
}

void delete_front() {
if (front == -1)
fprintf(stdout, "\nDeque is Empty");
else {
fprintf(stdout, "\nDeleted element: %d", deque[front]);
if (front == rear) {
front = -1;
rear = -1;
} else if (front == SIZE - 1)
front = 0;
else
front = front + 1;
}
}

void delete_rear() {
if (front == -1)
fprintf(stdout, "\nDeque is Empty");
else {
fprintf(stdout, "\nDeleted element: %d", deque[rear]);
if (front == rear) {
front = -1;
rear = -1;
} else if (rear == 0)
rear = SIZE - 1;
else
rear = rear - 1;
}
}

void display() {
int i = front;

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

if (front == -1)
fprintf(stdout, "\nDeque is Empty");
else {
fprintf(stdout, "\nDeque elements are: ");
if (front <= rear) {
while (i <= rear)
fprintf(stdout, "%d ", deque[i++]);
} else {
while (i <= SIZE - 1)
fprintf(stdout, "%d ", deque[i++]);
i = 0;
while (i <= rear)
fprintf(stdout, "%d ", deque[i++]);
}
}
}

int main() {
FILE *inputFile = fopen("input.txt", "r");
FILE *outputFile = fopen("output.txt", "w");
if (inputFile == NULL || outputFile == NULL) {
printf("Error opening files.\n");
return 1;
}

freopen("output.txt", "w", stdout);

int key;
char operation;
while (fscanf(inputFile, "%c %d", &operation, &key) != EOF) {
switch (operation) {
case 'F':
insert_front(key);
break;
case 'R':
insert_rear(key);
break;
case 'D':
delete_front();
break;
case 'E':
delete_rear();
break;
default:
printf("\nInvalid operation\n");
}
}

display();

fclose(inputFile);
fclose(outputFile);
return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
28.Pirioty Queues
#include <stdio.h>
#define MAX 5

int pri_que[MAX];
int front, rear;

void insert_by_priority(int data) {


int i, j;
if (rear == MAX - 1)
fprintf(stdout, "\nQueue is full!!");
else if (front == -1 && rear == -1) {
front++;
rear++;
pri_que[rear] = data;
} else {
rear++;
pri_que[rear] = data;
for (i = front; i <= rear; i++) {
for (j = i + 1; j <= rear; j++) {
if (pri_que[i] > pri_que[j]) {
int temp = pri_que[i];
pri_que[i] = pri_que[j];
pri_que[j] = temp;
}
}
}
}
}

void delete_by_priority(int data) {


int i;
if (front == -1 && rear == -1)
fprintf(stdout, "\nQueue is empty!!");
else {
for (i = front; i <= rear; i++) {
if (data == pri_que[i]) {
for (; i < rear; i++)
pri_que[i] = pri_que[i + 1];
pri_que[i] = -99;
rear--;

if (rear == -1)
front = -1;
return;
}

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

}
fprintf(stdout, "\nElement %d not found in queue!!", data);
}
}

void display_pqueue() {
if (front == -1 && rear == -1)
fprintf(stdout, "\nQueue is empty!!");
else {
fprintf(stdout, "\nQueue is: ");
for (; front <= rear; front++)
fprintf(stdout, "%d ", pri_que[front]);
front = 0;
}
}

int main() {
FILE *outFile = fopen("output.txt", "w");
freopen("output.txt", "w", stdout);

front = rear = -1;

insert_by_priority(3);
insert_by_priority(1);
insert_by_priority(7);
insert_by_priority(5);
display_pqueue();
delete_by_priority(3);
display_pqueue();
delete_by_priority(9);
display_pqueue();

fclose(outFile);
return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
29.Circular queues using structures
#include <stdio.h>
#include <stdlib.h>

#define SIZE 5

struct Queue {
int items[SIZE];
int front;
int rear;
};

struct Queue* createQueue() {


struct Queue* q = (struct Queue*)malloc(sizeof(struct Queue));
q->front = -1;
q->rear = -1;
return q;
}

int isFull(struct Queue* q) {


if ((q->front == 0 && q->rear == SIZE - 1) || (q->front == q->rear + 1))
return 1;
return 0;
}

int isEmpty(struct Queue* q) {


if (q->front == -1)
return 1;
return 0;
}

void enqueue(struct Queue* q, int value) {


if (isFull(q))
printf("\nQueue is full");
else {
if (q->front == -1)
q->front = 0;
q->rear = (q->rear + 1) % SIZE;
q->items[q->rear] = value;
}
}

int dequeue(struct Queue* q) {


int item;
if (isEmpty(q)) {
printf("\nQueue is empty");
item = -1;
} else {
item = q->items[q->front];
if (q->front == q->rear) {
q->front = -1;
q->rear = -1;
} else {

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

q->front = (q->front + 1) % SIZE;


}
}
return item;
}

void display(struct Queue* q) {


int i;
if (isEmpty(q))
printf("\nQueue is empty");
else {
printf("\nFront -> %d ", q->front);
printf("\nItems -> ");
for (i = q->front; i != q->rear; i = (i + 1) % SIZE)
printf("%d ", q->items[i]);
printf("%d ", q->items[i]);
printf("\nRear -> %d", q->rear);
}
}

int main() {
struct Queue* q = createQueue();
FILE *input_file = fopen("input.txt", "r");
FILE *output_file = fopen("output.txt", "w");
int value;

while (fscanf(input_file, "%d", &value) != EOF) {


enqueue(q, value);
}

while (!isEmpty(q)) {
fprintf(output_file, "%d ", dequeue(q));
}

fclose(input_file);
fclose(output_file);
return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Part- C
30.Pirority queues using structures
#include <stdio.h>
#include <stdlib.h>

struct node {
int data;
int priority;
struct node* next;
};

struct node* newNode(int d, int p) {


struct node* temp = (struct node*)malloc(sizeof(struct node));
temp->data = d;
temp->priority = p;
temp->next = NULL;

return temp;
}

int peek(struct node** head) {


return (*head)->data;
}

void pop(struct node** head) {


struct node* temp = *head;
(*head) = (*head)->next;
free(temp);
}

void push(struct node** head, int d, int p) {


struct node* start = (*head);

struct node* temp = newNode(d, p);

if ((*head) == NULL || (*head)->priority > p) {


temp->next = *head;
(*head) = temp;
} else {
while (start->next != NULL && start->next->priority < p) {
start = start->next;
}
temp->next = start->next;
start->next = temp;
}
}

int isEmpty(struct node** head) {

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

return (*head) == NULL;


}

int main() {
FILE *input_file = fopen("input.txt", "r");
FILE *output_file = fopen("output.txt", "w");
freopen("output.txt", "w", stdout);

struct node* pq = NULL;


int data, priority;

while (fscanf(input_file, "%d %d", &data, &priority) != EOF) {


push(&pq, data, priority);
}

while (!isEmpty(&pq)) {
printf("%d ", peek(&pq));
pop(&pq);
}

fclose(input_file);
fclose(output_file);
return 0;
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

Time Complexity O(n)


1.Linked List insert end
#include <stdio.h>
#include <stdlib.h>

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

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


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // O(1)
newNode->data = newData; // O(1)
newNode->next = NULL; // O(1)

if (*head == NULL) { // O(1)


*head = newNode; // O(1)
return; // O(1)
}

struct Node* last = *head; // O(1)


while (last->next != NULL) { // O(n)
last = last->next; // O(1)
}
last->next = newNode; // O(1)
}

void printListToFile(struct Node* head, FILE* outputFile) {


struct Node* temp = head; // O(1)
while (temp != NULL) { // O(n)
fprintf(outputFile, "%d ", temp->data); // O(1)
temp = temp->next; // O(1)
}
fprintf(outputFile, "\n"); // O(1)
}

int main() {
FILE* inputFile = fopen("input.txt", "r"); // O(1)
FILE* outputFile = fopen("output.txt", "w"); // O(1)

if (inputFile == NULL || outputFile == NULL) { // O(1)


printf("Error opening files!\n"); // O(1)
return 1; // O(1)
}

struct Node* head = NULL; // O(1)


int num; // O(1)

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

while (fscanf(inputFile, "%d", &num) != EOF) { // O(n)


insertAtEnd(&head, num); // O(n)
}

printListToFile(head, outputFile); // O(n)

fclose(inputFile); // O(1)
fclose(outputFile); // O(1)

return 0; // O(1)
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

2. Stack Implementation using Linked List


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

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

struct StackNode* newNode(int data) { // O(1)


struct StackNode* stackNode = (struct StackNode*)malloc(sizeof(struct StackNode)); // O(1)
stackNode->data = data; // O(1)
stackNode->next = NULL; // O(1)
return stackNode; // O(1)
}

int isEmpty(struct StackNode* root) { // O(1)


return !root; // O(1)
}

void push(struct StackNode** root, int data) { // O(1)


struct StackNode* stackNode = newNode(data); // O(1)
stackNode->next = *root; // O(1)
*root = stackNode; // O(1)
}

int pop(struct StackNode** root) { // O(1)


if (isEmpty(*root)) { // O(1)
printf("Stack Underflow\n"); // O(1)
return INT_MIN; // O(1)
}
struct StackNode* temp = *root; // O(1)
*root = (*root)->next; // O(1)
int popped = temp->data; // O(1)
free(temp); // O(1)
return popped; // O(1)
}

int peek(struct StackNode* root) { // O(1)


if (isEmpty(root)) { // O(1)
printf("Stack is Empty\n"); // O(1)
return INT_MIN; // O(1)
}
return root->data; // O(1)
}

void printStackToFile(struct StackNode* root, FILE* outputFile) { // O(n)


if (isEmpty(root)) { // O(1)
fprintf(outputFile, "Stack is Empty\n"); // O(1)
return; // O(1)
}

struct StackNode* temp = root; // O(1)

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

while (temp != NULL) { // O(n)


fprintf(outputFile, "%d ", temp->data); // O(1)
temp = temp->next; // O(1)
}
fprintf(outputFile, "\n"); // O(1)
}

int main() {
FILE* inputFile = fopen("input.txt", "r"); // O(1)
FILE* outputFile = fopen("output.txt", "w"); // O(1)

if (inputFile == NULL || outputFile == NULL) { // O(1)


printf("Error opening files!\n"); // O(1)
return 1; // O(1)
}

struct StackNode* root = NULL; // O(1)


int num; // O(1)

while (fscanf(inputFile, "%d", &num) != EOF) { // O(n)


push(&root, num); // O(1)
}

printStackToFile(root, outputFile); // O(n)

fclose(inputFile); // O(1)
fclose(outputFile); // O(1)

return 0; // O(1)
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

3.Insertion Sort: Sort an array using the insertion sort algorithm.


#include <stdio.h>

void insertionSort(int arr[], int n) { // O(n^2)


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

// Move elements of arr[0..i-1], that are greater than key, to one position ahead of their
current position
while (j >= 0 && arr[j] > key) { // O(n) worst case, O(1) best case
arr[j + 1] = arr[j]; // O(1)
j = j - 1; // O(1)
}
arr[j + 1] = key; // O(1)
}
}

int main() {
FILE *inputFile, *outputFile; // O(1)
int arr[100], n, i; // O(1)

// Open input and output files


inputFile = fopen("input.txt", "r"); // O(1)
outputFile = fopen("output.txt", "w"); // O(1)

// Check if files opened successfully


if (inputFile == NULL || outputFile == NULL) { // O(1)
printf("Error opening files!\n"); // O(1)
return 1; // O(1)
}

// Read the number of elements from the input file


fscanf(inputFile, "%d", &n); // O(1)

// Read array elements from the input file


for (i = 0; i < n; i++) { // O(n)
fscanf(inputFile, "%d", &arr[i]); // O(1)
}

// Sort the array using insertion sort


insertionSort(arr, n); // O(n^2)

// Print the sorted array to the output file


fprintf(outputFile, "Sorted array: "); // O(1)
for (i = 0; i < n; i++) { // O(n)
fprintf(outputFile, "%d ", arr[i]); // O(1)
}
fprintf(outputFile, "\n"); // O(1)

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

// Close files
fclose(inputFile); // O(1)
fclose(outputFile); // O(1)

return 0; // O(1)
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

4.Delete end singly circular linked list.


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

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

void insertFront(struct Node** head_ref, int new_data) { // O(1)


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // O(1)
struct Node* last = *head_ref; // O(1)

new_node->data = new_data; // O(1)

if (*head_ref == NULL) { // O(1)


new_node->next = new_node; // O(1)
} else {
while (last->next != *head_ref) { // O(n)
last = last->next; // O(1)
}
new_node->next = *head_ref; // O(1)
last->next = new_node; // O(1)
}

*head_ref = new_node; // O(1)


}

void insertEnd(struct Node** head_ref, int new_data) { // O(1)


struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // O(1)
struct Node* last = *head_ref; // O(1)

new_node->data = new_data; // O(1)

if (*head_ref == NULL) { // O(1)


new_node->next = new_node; // O(1)
*head_ref = new_node; // O(1)
} else {
while (last->next != *head_ref) { // O(n)
last = last->next; // O(1)
}
last->next = new_node; // O(1)
new_node->next = *head_ref; // O(1)
}
}

void deleteEnd(struct Node** head_ref) { // O(1)


if (*head_ref == NULL) { // O(1)
return; // O(1)
}

struct Node* temp = *head_ref; // O(1)


struct Node* prev = NULL; // O(1)

while (temp->next != *head_ref) { // O(n)


prev = temp; // O(1)
temp = temp->next; // O(1)
}

if (prev == NULL) { // O(1)


*head_ref = NULL; // O(1)
} else {
prev->next = temp->next; // O(1)
}

free(temp); // O(1)

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

void readDataFromFile(struct Node** head_ref, const char* filename) { // O(n)


FILE* fp = fopen(filename, "r"); // O(1)
if (fp == NULL) { // O(1)
printf("Error opening file\n"); // O(1)
return; // O(1)
}

int data; // O(1)


while (fscanf(fp, "%d", &data) != EOF) { // O(m)
insertEnd(head_ref, data); // O(n)
}

fclose(fp); // O(1)
}

void printList(struct Node* head) { // O(n)


struct Node* temp = head; // O(1)

if (head != NULL) { // O(1)


do {
printf("%d ", temp->data); // O(1)
temp = temp->next; // O(1)
} while (temp != head); // O(n)
}
printf("\n"); // O(1)
}

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

readDataFromFile(&head, "data.txt"); // O(n)

printf("Singly Circular Linked List after reading from file: "); // O(1)
printList(head); // O(n)

return 0; // O(1)
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

18. Stack using Dynamic array


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

#define INITIAL_CAPACITY 10

int* stack; // O(1)


int top = -1; // O(1)
int capacity = INITIAL_CAPACITY; // O(1)

void resize() {
capacity *= 2; // O(1)
stack = (int*)realloc(stack, capacity * sizeof(int)); // O(n), where n is the number of elements in the stack
}

void push(int value) {


if (top == capacity - 1) { // O(1)
resize(); // O(n), where n is the number of elements in the stack
}
stack[++top] = value; // O(1)
}

int pop() {
if (top == -1) { // O(1)
printf("Stack Underflow\n"); // O(1)
return -1; // O(1)
}
return stack[top--]; // O(1)
}

int peek() {
if (top == -1) { // O(1)
printf("Stack is empty\n"); // O(1)
return -1; // O(1)
}
return stack[top]; // O(1)
}

void display(FILE* outFile) {


if (top == -1) { // O(1)
fprintf(outFile, "Stack is empty\n"); // O(1)
return; // O(1)
}
fprintf(outFile, "Stack: "); // O(1)
for (int i = 0; i <= top; i++) { // O(n), where n is the number of elements in the stack
fprintf(outFile, "%d ", stack[i]); // O(1)
}
fprintf(outFile, "\n"); // O(1)
}

int main() {
FILE *outFile = fopen("output.txt", "w"); // O(1)

stack = (int*)malloc(capacity * sizeof(int)); // O(1)


push(1); // O(1)
push(2); // O(1)
push(3); // O(1)
push(4); // O(1)
display(outFile); // O(n), where n is the number of elements in the stack

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA
School of Electronics and Communication Engineering
Data Structure Applications (DSA) Course. [21EECF201/ 20EEIP216/ 23EVTF203]

fprintf(outFile, "Peek: %d\n", peek()); // O(1)


fprintf(outFile, "Pop: %d\n", pop()); // O(1)
display(outFile); // O(n), where n is the number of elements in the stack

free(stack); // O(1)
fclose(outFile); // O(1)
return 0; // O(1)
}
Output

School of Electronics and Communication Engineering,


KLE Technological University, BVB Campus, Hubballi-580031, Karnataka, INDIA

You might also like