Assignment I Template
Assignment I Template
Part- A
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.
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.
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.
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.
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
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 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.
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
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.
"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.
Part- B
1. Hello World: Print "Hello, World!" to the console
Code
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
Output
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;
return 0;
}
Output
Part- B
3. Prime Numbers: Determine whether a given number is prime.
Code
#include <stdio.h>
#include <math.h>
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;
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;
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
Part- B
7. Palindrome Check: Check if a given number or string is a palindrome.
Code
#include <stdio.h>
#include <string.h>
int main() {
FILE *inputFile, *outputFile;
char str[100];
// Close files
fclose(inputFile);
fclose(outputFile);
return 0;
}
Output
Part- B
8. Area of Shapes: Calculate the area of shapes like rectangle, triangle, and circle.
#include <stdio.h>
#include <math.h>
int main() {
int choice;
float length, width, base, height, radius, area;
FILE *input_file, *output_file;
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
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;
// Close files
fclose(inputFile);
fclose(outputFile);
return 0;
}
Output
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;
return 0;
}
Output
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];
// Close files
fclose(input_file);
fclose(output_file);
return 0;
}
Output
Part- B
12. Linear Search: Search for an element in an array using linear search.
Code
#include <stdio.h>
int main() {
FILE *inputFile, *outputFile;
int arr[100], n, key, index;
// Close files
fclose(inputFile);
fclose(outputFile);
return 0;
}
Output
Part- B
13. Binary Search: Search for an element in a sorted array using binary search.
#include <stdio.h>
int main() {
FILE *inputFile, *outputFile;
int arr[100], n, key, result;
// Close files
fclose(inputFile);
fclose(outputFile);
return 0;
}
Output
Part- B
14. Selection Sort: Sort an array using the selection sort algorithm.
Code
#include <stdio.h>
int main() {
FILE *inputFile, *outputFile;
int arr[100], n, i;
// Close files
fclose(inputFile);
fclose(outputFile);
return 0;
}
Output
Part- B
15. Bubble Sort: Sort an array using the bubble sort algorithm.
#include <stdio.h>
int main() {
FILE *inputFile, *outputFile;
int arr[100], n, i;
// Close files
fclose(inputFile);
fclose(outputFile);
return 0;
}
Output
Part- B
16. Insertion Sort: Sort an array using the insertion sort algorithm.
#include <stdio.h>
// 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;
// Close files
fclose(inputFile);
fclose(outputFile);
return 0;
}
Output
Part- B
17. Matrix Operations: Perform matrix addition, subtraction, multiplication, and transpose.
#include <stdio.h>
int main() {
FILE *inputFile, *outputFile;
int N, A[N][N], B[N][N], C[N][N];
// 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
Part- C
1.Linked List insert end
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
if (*head == NULL) {
*head = newNode;
return;
}
int main() {
FILE* inputFile = fopen("input.txt", "r"); // Open input file for reading
FILE* outputFile = fopen("output.txt", "w"); // Open output file for writing
fclose(inputFile);
fclose(outputFile);
return 0;
}
Output
Part- C
2. Stack Implementation using Linked List
#include <stdio.h>
#include <stdlib.h>
struct StackNode {
int data;
struct StackNode* next;
};
int main() {
FILE* inputFile = fopen("input.txt", "r"); // Open input file for reading
FILE* outputFile = fopen("output.txt", "w"); // Open output file for writing
fclose(inputFile);
fclose(outputFile);
return 0;
}
Output
Part- C
3. Queue Implementation using Arrays
#include <stdio.h>
#include <stdlib.h>
struct Queue {
int capacity;
int front, rear;
int* array;
};
int main() {
FILE* inputFile = fopen("input.txt", "r"); // Open input file for reading
FILE* outputFile = fopen("output.txt", "w"); // Open output file for writing
fclose(inputFile);
fclose(outputFile);
return 0;
}
Output
Part- C
struct Node {
int key;
struct Node* left;
struct Node* right;
};
int main() {
FILE* inputFile = fopen("input.txt", "r"); // Open input file for reading
FILE* outputFile = fopen("output.txt", "w"); // Open output file for writing
fclose(inputFile);
fclose(outputFile);
return 0;
}
Output
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;
};
newNode = newAdjListNode(src);
newNode->next = graph->array[dest].head;
graph->array[dest].head = newNode;
}
int main() {
FILE *inFile = fopen("input.txt", "r");
FILE *outFile = fopen("output.txt", "w");
int V;
fscanf(inFile, "%d", &V);
printGraph(graph, outFile);
fclose(inFile);
fclose(outFile);
return 0;
}
Output
Part- C
6.Insert front in singly circular linked list
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
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;
}
int main() {
FILE *inFile = fopen("input.txt", "r");
FILE *outFile = fopen("output.txt", "w");
fclose(inFile);
fclose(outFile);
return 0;
}
Output
Part- C
7.Delete end singly circular linked list.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
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;
}
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;
}
}
if (prev == NULL) {
*head_ref = NULL;
} else {
prev->next = temp->next;
}
free(temp);
}
int data;
while (fscanf(fp, "%d", &data) != EOF) {
insertEnd(head_ref, data);
}
fclose(fp);
}
fprintf(fp, "\n");
fclose(fp);
}
int main() {
struct Node* head = NULL;
readDataFromFile(&head, "data.txt");
Part- C
8. Delete Front singly circular linked list.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
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;
}
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;
}
}
free(temp);
}
// Function to read data from a file and insert nodes into the list
void readDataFromFile(struct Node** head_ref, const char* filename) {
int data;
while (fscanf(fp, "%d", &data) != EOF) {
insertEnd(head_ref, data); // Modify to insertFront if desired
}
fclose(fp);
}
fprintf(fp, "\n");
fclose(fp);
}
int main() {
struct Node* head = NULL;
Part- C
9.Delete at specific location
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
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;
}
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;
}
}
if (current == *head_ref) {
prev = (*head_ref);
while (prev->next != *head_ref)
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);
}
}
int main() {
FILE *inFile = fopen("input.txt", "r");
FILE *outFile = fopen("output.txt", "w");
deleteNode(&head, 2);
printf("List after deleting node with key 2: ");
printList(head, outFile);
fclose(inFile);
fclose(outFile);
return 0;
}
Output
Part- C
10.Insert Specific code
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
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;
}
}
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;
}
}
if (position == 1) {
insertFront(head_ref, new_data);
return;
}
new_node->data = new_data;
new_node->next = current->next;
current->next = new_node;
}
int main() {
FILE *inFile = fopen("input.txt", "r");
FILE *outFile = fopen("output.txt", "w");
fclose(inFile);
fclose(outFile);
return 0;
}
Output
Part- C
11.Display elements in linked list
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
int main() {
FILE *inFile = fopen("input.txt", "r");
FILE *outFile = fopen("output.txt", "w");
if (head == NULL) {
head = newNode;
current = head;
} else {
current->next = newNode;
current = current->next;
}
}
displayList(head, outFile);
fclose(inFile);
fclose(outFile);
return 0;
}
Output
Part- C
12.Merged two sorted Linked List
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
while (1) {
if (l1 == NULL) {
tail->next = l2;
break;
}
if (l2 == NULL) {
tail->next = l1;
break;
}
int main() {
FILE *inFile = fopen("input.txt", "r");
FILE *outFile = fopen("output.txt", "w");
newNode->data = data;
newNode->next = NULL;
if (l1 == NULL) {
l1 = newNode;
current = l1;
} else {
current->next = newNode;
current = current->next;
}
}
if (l2 == NULL) {
l2 = newNode;
current = l2;
} else {
current->next = newNode;
current = current->next;
}
}
fclose(inFile);
fclose(outFile);
return 0;
}
Output
Part- C
13.Reverse Linked List
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
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;
}
int main() {
FILE *inFile = fopen("input.txt", "r");
FILE *outFile = fopen("output.txt", "w");
int data;
while (fscanf(inFile, "%d", &data) != EOF) {
insertAtBeginning(data);
}
fclose(inFile);
fclose(outFile);
return 0;
}
Output
Part- C
14.Spilt the linked list
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
if (head == NULL)
return;
if (fast_ptr->next->next == head) {
fast_ptr = fast_ptr->next;
}
fast_ptr->next = head2;
slow_ptr->next = head1;
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
Part- C
15. Josephus Problem Using a Singly Circular Linked List
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
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;
}
}
}
int main() {
FILE *outFile = fopen("output.txt", "w");
fclose(outFile);
return 0;
}
Output
Part- C
16.Stack using array
#include <stdio.h>
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1;
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];
}
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
Part- C
17. Stack using Linked list
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
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;
}
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
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));
}
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];
}
int main() {
FILE *outFile = fopen("output.txt", "w");
free(stack);
fclose(outFile);
return 0;
}
Output
Part- C
19.Stack using static array
#include <stdio.h>
#define MAX_SIZE 5
int stack[MAX_SIZE];
int top = -1;
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];
}
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
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;
}
int main() {
FILE *outFile = fopen("output.txt", "w");
// Cleanup
free(stack->array);
free(stack);
fclose(outFile);
return 0;
}
Output
Part- C
21.Queue using array
#include <stdio.h>
#define MAX_SIZE 100
int queue[MAX_SIZE];
int front = -1, rear = -1;
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++;
}
int main() {
FILE *outFile = fopen("output.txt", "w");
enqueue(10);
enqueue(20);
enqueue(30);
display(outFile);
dequeue();
display(outFile);
fclose(outFile);
return 0;
}
Output
Part- C
22.Queue using linked list
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
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
Part- C
23. Queue using circular array
#include <stdio.h>
#define MAX_SIZE 100
int queue[MAX_SIZE];
int front = -1, rear = -1;
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
Part- C
24.Queue using structure with array
#include <stdio.h>
#include <stdlib.h>
struct Queue {
int items[MAX_SIZE];
int front;
int rear;
};
Queue* createQueue() {
Queue* queue = (Queue*)malloc(sizeof(Queue));
queue->front = -1;
queue->rear = -1;
return queue;
}
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
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;
};
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
Part- C
26.Circular queue
#include <stdio.h>
#define SIZE 5
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
Part- C
27.Double ended Queue
#include <stdio.h>
#define SIZE 5
int deque[SIZE];
int front = -1, rear = -1;
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;
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;
}
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
Part- C
28.Pirioty Queues
#include <stdio.h>
#define MAX 5
int pri_que[MAX];
int front, rear;
if (rear == -1)
front = -1;
return;
}
}
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);
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
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;
};
int main() {
struct Queue* q = createQueue();
FILE *input_file = fopen("input.txt", "r");
FILE *output_file = fopen("output.txt", "w");
int value;
while (!isEmpty(q)) {
fprintf(output_file, "%d ", dequeue(q));
}
fclose(input_file);
fclose(output_file);
return 0;
}
Output
Part- C
30.Pirority queues using structures
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
int priority;
struct node* next;
};
return temp;
}
int main() {
FILE *input_file = fopen("input.txt", "r");
FILE *output_file = fopen("output.txt", "w");
freopen("output.txt", "w", stdout);
while (!isEmpty(&pq)) {
printf("%d ", peek(&pq));
pop(&pq);
}
fclose(input_file);
fclose(output_file);
return 0;
}
Output
struct Node {
int data;
struct Node* next;
};
int main() {
FILE* inputFile = fopen("input.txt", "r"); // O(1)
FILE* outputFile = fopen("output.txt", "w"); // O(1)
fclose(inputFile); // O(1)
fclose(outputFile); // O(1)
return 0; // O(1)
}
Output
struct StackNode {
int data;
struct StackNode* next;
};
int main() {
FILE* inputFile = fopen("input.txt", "r"); // O(1)
FILE* outputFile = fopen("output.txt", "w"); // O(1)
fclose(inputFile); // O(1)
fclose(outputFile); // O(1)
return 0; // O(1)
}
Output
// 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)
// Close files
fclose(inputFile); // O(1)
fclose(outputFile); // O(1)
return 0; // O(1)
}
Output
struct Node {
int data;
struct Node* next;
};
free(temp); // O(1)
fclose(fp); // O(1)
}
int main() {
struct Node* head = NULL; // O(1)
printf("Singly Circular Linked List after reading from file: "); // O(1)
printList(head); // O(n)
return 0; // O(1)
}
Output
#define INITIAL_CAPACITY 10
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
}
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)
}
int main() {
FILE *outFile = fopen("output.txt", "w"); // O(1)
free(stack); // O(1)
fclose(outFile); // O(1)
return 0; // O(1)
}
Output