0% found this document useful (0 votes)
4 views22 pages

C Programming Assignment

The document provides answers to a C programming and Data Structures assignment, covering topics such as the history of C, identifiers, constants, algorithms, data types, storage classes, control structures, operators, and loops. Each section includes definitions, examples, and explanations of key concepts relevant to the subject matter. The document also includes sample C programs to demonstrate practical applications of the discussed topics.

Uploaded by

ahirawan7859
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views22 pages

C Programming Assignment

The document provides answers to a C programming and Data Structures assignment, covering topics such as the history of C, identifiers, constants, algorithms, data types, storage classes, control structures, operators, and loops. Each section includes definitions, examples, and explanations of key concepts relevant to the subject matter. The document also includes sample C programs to demonstrate practical applications of the discussed topics.

Uploaded by

ahirawan7859
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Answer all the questions in simple and easy langu...

1 message

<amitk917042@[Link]> Sat, Oct 25, 2025 at 10:43 PM


Draft

I see you have uploaded an image containing a list of questions from a C programming and Data Structures assignment. I can certainly help you by providing the answers to
these questions in a simple and easy-to-understand language.

Since I cannot directly generate a PDF file or output in an "A4 page format" with specific color formatting (black headings/questions, blue answers), I will provide the
content organized logically with clear headings and formatting that you can easily copy and paste into a word processor to apply the required PDF and color formatting
yourself.

Here are the answers, grouped by the units as they appear in your image.

M.C.A. $1^{st}$ SEM 2025-26 PROGRAMMING IN 'C' & DATA STRUCTURE ASSIGNMENT

UNIT I
1. Describe about History of C programming.

The C programming language was developed in the early 1970s by Dennis Ritchie at Bell Labs. It was created as an improvement on the B language (which was based on
BCPL) and was initially used to develop the UNIX operating system. C became popular because it is a powerful, efficient, and flexible language that combines the features of
a high-level language with the ability to manage low-level details, making it ideal for system programming and application development.

2. Describe about Identifiers and Keywords in C programming.


Identifiers are names given to programming elements like variables, functions, arrays, and structures. They are used to uniquely identify an element in a program.
Rules for Identifiers: They must start with an alphabet (A-Z, a-z) or an underscore ($\_$). Subsequent characters can be letters, digits (0-9), or underscores.
Keywords cannot be used as identifiers. Identifiers are case-sensitive (e.g., sum is different from Sum ).
Keywords are reserved words in the C language that have a fixed meaning to the compiler. They perform specific operations and cannot be used as variable names or
identifiers. Examples include int , void , if , else , while , for , return , etc. There are typically 32 keywords in standard C.

3. What do you mean by Constant and Variable? How it will be declare?


A Constant is a data value that cannot be changed during the execution of a program. They represent fixed values.
Declaration: Constants can be declared using the const keyword (e.g., const float PI = 3.14; ) or by using the preprocessor directive #define (e.g.,
#define PI 3.14 ).
A Variable is a named storage location in memory that holds a data value. The value stored in a variable can be changed during program execution.
Declaration: Variables are declared by specifying their data type followed by the variable name. (e.g., int age; or float salary = 50000.50; ).

4. What do you mean by Algorithm? Describe its properties. Define Flow chart.
An Algorithm is a finite set of well-defined, step-by-step instructions to solve a specific problem or perform a computation. It's essentially the blueprint or plan
before writing the actual program code.
Properties of an Algorithm:
Input: Zero or more quantities are externally supplied.
Output: At least one quantity is produced.
Definiteness: Each step is clear, precise, and unambiguous.
Finiteness: The algorithm must terminate after a finite number of steps.
Effectiveness: Each operation must be simple enough that it can, in principle, be done exactly and in a finite amount of time.
A Flow Chart is a diagrammatic representation of an algorithm or a process. It uses various standard symbols (like rectangles for processes, diamonds for decisions,
and ovals for start/end) connected by arrows to show the flow of control and logic.

5. Represent (140.125)$_{10}$ in Single Precision and Double Precision formats.

This question requires converting a decimal number to the IEEE 754 floating-point standard.

Decimal Number: $(140.125)_{10}$

Conversion Steps (Common for both):


1. Binary Conversion:
Integer part $(140)_{10} = (10001100)_2$
Fractional part $(0.125)_{10} = (0.001)_2$
Combined Binary: $(10001100.001)_2$
2. Normalization: Move the decimal point so that it is after the first '1'.
$1.0001100001 \times 2^7$
Exponent $(E)$ = $7$
Mantissa (M) = $0001100001$ (the bits after the leading '1')
Sign Bit (S) = $0$ (since $140.125$ is positive)

Single Precision (32-bit):


Sign: 1 bit (0 for positive)
Exponent: 8 bits
Mantissa (Fraction): 23 bits
Biased Exponent: $E_{bias} = 127 + E = 127 + 7 = 134$.
$(134)_{10} = (10000110)_2$
Mantissa (23 bits): $0001100001$ followed by 13 zeros to make 23 bits.
$00011000010000000000000$
Final Single Precision Representation (in binary):

$$\mathbf{0} \quad \mathbf{10000110} \quad \mathbf{00011000010000000000000}$$

Double Precision (64-bit):


Sign: 1 bit (0 for positive)
Exponent: 11 bits
Mantissa (Fraction): 52 bits
Biased Exponent: $E_{bias} = 1023 + E = 1023 + 7 = 1030$.
$(1030)_{10} = (10000000110)_2$
Mantissa (52 bits): $0001100001$ followed by 42 zeros to make 52 bits.
Final Double Precision Representation (in binary):

$$\mathbf{0} \quad \mathbf{10000000110} \quad \mathbf{0001100001} \underbrace{00\ldots0}_{42 \text{ zeros}}$$

6. What do you mean by Data Type? Describe about different Data Types in C programming.
A Data Type specifies the type of data a variable can hold (like an integer, a floating-point number, or a character) and also determines the amount of memory
allocated for it and the range of values it can store.
Different Data Types in C:
1. Primary/Basic Data Types:
int : Used to store whole numbers (integers) without any decimal points. (e.g., $10, -500$). Typically 2 or 4 bytes.
char : Used to store a single character (e.g., 'A', '7', '$'). Typically 1 byte.
float : Used to store single-precision floating-point numbers (numbers with decimals). (e.g., $3.14, 0.001$). Typically 4 bytes.
double : Used to store double-precision floating-point numbers. Provides greater precision and range than float . (e.g., $3.14159265$). Typically 8
bytes.
void : Means no value. Used to specify that a function returns no value or to declare a generic pointer.
2. Derived Data Types: Arrays, Pointers, Structures, Unions, etc. (These are constructed from the basic types).

7. What is storage class? Explain different storage class with suitable example.
A Storage Class in C defines the scope (visibility) and lifetime of a variable or a function. It also specifies where the variable will be stored (memory or CPU
registers) and its initial value.
Different Storage Classes:
1. auto (Automatic):
Scope: Local to the block/function in which it's defined.
Lifetime: Exists only within the function/block. It is destroyed when the block is exited.
Default: Variables declared inside a function without any storage class keyword are automatically auto .
Example: void func() { auto int x = 10; }
2. extern (External):
Scope: Global across all files in a program.
Lifetime: Exists as long as the program is running.
Usage: Declares a variable that is defined in another file or later in the same file. It tells the compiler the variable exists elsewhere.
Example: extern int total_count;
3. static :
Scope: Local to the block/function (if declared inside a function) OR local to the file (if declared globally).
Lifetime: Exists for the entire duration of the program. If local, its value is retained between function calls.
Example: void counter() { static int count = 0; count++; }
4. register :
Scope: Local to the block/function.
Lifetime: Exists only within the function/block.
Usage: Suggests to the compiler to store the variable in a CPU register for faster access. Used for variables that are accessed very frequently. The
compiler may ignore the request if registers are not available.
Example: register int i;

8. What is switch statement? Write the syntax and explain how it is different from if statement.
The switch statement is a multi-way branch selection control structure. It allows a program to execute a block of code based on the value of a single expression
(the switch expression). It is an alternative to a long sequence of if-else if-else statements.
Syntax:

switch (expression) {
case constant1:
// code to be executed if expression == constant1
break; // Used to exit the switch block
case constant2:
// code to be executed if expression == constant2
break;
// ... more cases
default:
// code to be executed if none of the cases match
}

Difference from if statement:

Feature switch Statement if Statement

Expression
Only works with integral (int, char, short) or enumerated expressions. Works with any type of expression (relational, logical, arithmetic).
Type

Condition Only checks for equality against multiple constant values. Can check for complex relational (>, <, <=), logical (&&,

More efficient for a large number of fixed values since the compiler Less efficient for a large number of conditions as it must evaluate each
Execution
can directly jump to the matching case. if or else if condition sequentially.

Uses the break statement to exit; without it, control "falls through" Execution automatically continues after the corresponding block is
Control Flow
to the next case. completed.

9. What do you mean by operator? Describe about all different type of operator. Explain operator precedence and associativity.
An Operator is a symbol that tells the compiler to perform specific mathematical, relational, or logical operations on one or more operands (variables or values).
(e.g., + , - , * , / , == , && ).
Different Types of Operators:
1. Arithmetic Operators: Perform mathematical calculations. (e.g., + (addition), - (subtraction), * (multiplication), / (division), % (modulus/remainder)).
2. Relational Operators: Compare two values and return a boolean result (true/1 or false/0). (e.g., == (equal to), != (not equal to), > (greater than), < (less
than), >= (greater than or equal to), <= (less than or equal to)).
3. Logical Operators: Combine or negate relational results. (e.g., && (AND), || (OR), ! (NOT)).
4. Assignment Operators: Assign a value to a variable. (e.g., = (simple assignment), += , -= , *= , etc. (compound assignment)).
5. Increment/Decrement Operators: Increase or decrease a variable's value by one. (e.g., ++ (increment), -- (decrement)).
6. Bitwise Operators: Perform operations on individual bits of data. (e.g., & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift)).
7. Conditional (Ternary) Operator: A shorthand for a simple if-else statement. (e.g., condition ? expression1 : expression2 ).
Operator Precedence:
It determines the order in which operators are evaluated in an expression that contains multiple operators.
For example, in $a + b * c$, the multiplication ( * ) has higher precedence than addition ( + ), so $b * c$ is calculated first. Parentheses () can be used to
override precedence.
Operator Associativity:
It determines the direction of evaluation (either left-to-right or right-to-left) for operators that have the same precedence.
For example, in $a / b * c$, division ( / ) and multiplication ( * ) have the same precedence. Since they are left-associative, the expression is evaluated as $(a
/ b) * c$. The assignment operator ( = ) is right-associative (e.g., $a = b = c$ is evaluated as $a = (b = c)$).

10. Write the difference between for, while and do while loops with suitable example.

All three are looping constructs that allow a block of code to be executed repeatedly.
Feature for Loop while Loop do-while Loop

Best used when the number of iterations is NOT known


Best used when the number of Similar to while , but guarantees the code
Purpose beforehand, and the loop continues as long as a condition
iterations is known beforehand. block executes at least once.
is true.

Condition Entry-controlled: Condition is Entry-controlled: Condition is checked at the start of the Exit-controlled: Condition is checked at the
Check checked at the start of the loop. loop. end of the loop.

May not execute at all if the Guaranteed to execute the loop body at least
Execution May not execute at all if the initial condition is false.
initial condition is false. once, even if the condition is false initially.

for (initialization; condition;


Syntax while (condition) { // body } do { // body } while (condition);
update) { // body }

for (int i = 1; i <= 5; i++) { int i = 6; do { printf("%d ", i++); } while (i <=
Example int i = 1; while (i <= 5) { printf("%d ", i++); }
printf("%d ", i); } 5); (Prints 6)

11. Write the difference between conditional statement and iterative statement with suitable example.
Conditional Statements (Selection/Decision Making):
Purpose: To select and execute a block of code based on whether a specified condition is true or false. The code block is executed at most once.
Keywords: if , else , else if , switch .
Example:

int a = 10;
if (a > 5) {
printf("A is greater than 5"); // Executed once
}

Iterative Statements (Looping/Repetition):


Purpose: To repeat the execution of a block of code multiple times until a specified termination condition is met.
Keywords: for , while , do-while .
Example:

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


printf("Loop %d\n", i); // Executed three times
}

12. Write a C program to find largest no. among given three numbers.
C

#include <stdio.h>

int main() {
int num1, num2, num3;

printf("Enter three numbers: ");


scanf("%d %d %d", &num1, &num2, &num3);

if (num1 >= num2 && num1 >= num3) {


printf("%d is the largest number.\n", num1);
} else if (num2 >= num1 && num2 >= num3) {
printf("%d is the largest number.\n", num2);
} else {
printf("%d is the largest number.\n", num3);
}

return 0;
}

13. Write a C program to find given number is even or odd.


C

#include <stdio.h>

int main() {
int num;

printf("Enter an integer: ");


scanf("%d", &num);

// An even number has a remainder of 0 when divided by 2


if (num % 2 == 0) {
printf("%d is an Even number.\n", num);
} else {
printf("%d is an Odd number.\n", num);
}

return 0;
}

14. Write a C program to find factorial of given number.

#include <stdio.h>

int main() {
int n, i;
long long factorial = 1; // Use long long for larger factorials

printf("Enter an integer to find its factorial: ");


scanf("%d", &n);

if (n < 0) {
printf("Factorial of negative numbers doesn't exist.\n");
} else {
for (i = 1; i <= n; ++i) {
factorial *= i;
}
printf("Factorial of %d = %lld\n", n, factorial);
}

return 0;
}

15. Write a C program to generate Fibonacci series.

#include <stdio.h>

int main() {
int i, n;
int t1 = 0, t2 = 1;
int nextTerm = t1 + t2;

printf("Enter the number of terms for the series: ");


scanf("%d", &n);

printf("Fibonacci Series: %d, %d, ", t1, t2);

for (i = 3; i <= n; ++i) {


printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}
printf("...\n");

return 0;
}

16. What is Function? Differentiate between function declaration, function call and function argument.
A Function is a self-contained block of statements that performs a specific, well-defined task. Functions help in breaking a large program into smaller, manageable,
and reusable modules.

Term Description

Function Declaration (or Informs the compiler about a function's name, return type, and parameters (arguments) before it's actually defined or used. It's
Prototype) usually placed at the start of the program or in a header file.

Function Call The act of executing the statements inside the function body. The program control jumps from the calling code to the called function.

The values or variables passed from the calling function to the called function. These are the inputs the function uses to perform its
Function Argument
task. In the function definition, these are called parameters.

Example:

int add(int a, int b); // <-- DECLARATION (Prototype)

int main() {
int x = 5, y = 3;
int sum = add(x, y); // <-- CALL, x and y are ARGUMENTS
return 0;
}

int add(int a, int b) { // <-- a and b are Parameters


return a + b;
}

17. Write a C program to find prime number or not.


C

#include <stdio.h>

int main() {
int n, i, flag = 0;

printf("Enter a positive integer: ");


scanf("%d", &n);

// 0 and 1 are not prime numbers


if (n == 0 || n == 1) {
flag = 1;
} else {
// Check for factors from 2 up to n/2 (or sqrt(n) for efficiency)
for (i = 2; i <= n / 2; ++i) {
if (n % i == 0) {
flag = 1; // Not a prime number
break;
}
}
}

if (flag == 0) {
printf("%d is a Prime number.\n", n);
} else {
printf("%d is NOT a Prime number.\n", n);
}

return 0;
}

18. Write a C program to convert binary no into decimal number.

#include <stdio.h>
#include <math.h> // For the pow() function

int main() {
long long binary;
int decimal = 0, remainder, power = 0;
printf("Enter a binary number: ");
scanf("%lld", &binary);

// Loop until the binary number becomes 0


while (binary != 0) {
remainder = binary % 10; // Get the last digit
// Add (last digit * 2^power) to decimal
decimal += remainder * pow(2, power);
binary /= 10; // Remove the last digit
power++; // Increment the power of 2
}

printf("Decimal equivalent: %d\n", decimal);

return 0;
}

19. Write a C program to find sum of all digits of a given number.

#include <stdio.h>

int main() {
int num, originalNum, sum = 0, remainder;

printf("Enter an integer: ");


scanf("%d", &num);

originalNum = num; // Store the original number for output

while (num != 0) {
remainder = num % 10; // Get the last digit
sum += remainder; // Add the digit to the sum
num /= 10; // Remove the last digit
}

printf("Sum of digits of %d is: %d\n", originalNum, sum);

return 0;
}

20. Write a C program to compute addition of two numbers using function.

#include <stdio.h>

// Function Declaration (Prototype)


int add_numbers(int a, int b);

int main() {
int n1, n2, result;

printf("Enter first number: ");


scanf("%d", &n1);
printf("Enter second number: ");
scanf("%d", &n2);

// Function Call
result = add_numbers(n1, n2);

printf("The sum is: %d\n", result);

return 0;
}

// Function Definition
int add_numbers(int a, int b) {
int sum = a + b;
return sum; // Return the sum
}

21. Write a C program to find power of number using function.


C

#include <stdio.h>

// Function Declaration (Prototype)


double power(double base, int exponent);

int main() {
double b, result;
int e;

printf("Enter base number: ");


scanf("%lf", &b);
printf("Enter exponent (a non-negative integer): ");
scanf("%d", &e);

// Function Call
result = power(b, e);

printf("%.2lf raised to the power %d is: %.2lf\n", b, e, result);

return 0;
}

// Function Definition
double power(double base, int exponent) {
double res = 1.0;
// Loop to multiply base by itself 'exponent' times
for (int i = 0; i < exponent; ++i) {
res *= base;
}
return res;
}

22. Write a C program to find factorial of number using recursion.

#include <stdio.h>

// Function Declaration (Prototype)


long long factorial(int n);

int main() {
int num;

printf("Enter a non-negative integer: ");


scanf("%d", &num);

if (num < 0) {
printf("Factorial of negative numbers doesn't exist.\n");
} else {
printf("Factorial of %d = %lld\n", num, factorial(num));
}

return 0;
}

// Function Definition using Recursion


long long factorial(int n) {
// Base Case: Factorial of 0 is 1
if (n == 0) {
return 1;
}
// Recursive Step: n! = n * (n-1)!
else {
return n * factorial(n - 1);
}
}

23. Write a C program to swap two numbers using call by value.

#include <stdio.h>
// Function Definition for swapping using Call by Value
void swap_by_value(int a, int b) {
int temp;
temp = a;
a = b;
b = temp;
// The changes to 'a' and 'b' (the copies) are lost after the function ends.
printf("\nInside function (Call by Value):\n");
printf("a = %d, b = %d\n", a, b);
}

int main() {
int n1 = 10, n2 = 20;

printf("Before swapping (main): n1 = %d, n2 = %d\n", n1, n2);

// Call by Value: Only copies of n1 and n2 are passed


swap_by_value(n1, n2);

// n1 and n2 in main() remain unchanged


printf("\nAfter swapping (main) [Call by Value]:\n");
printf("n1 = %d, n2 = %d\n", n1, n2);
// Output: n1=10, n2=20 (NO SWAP occurred in main)

return 0;
}

24. Write a C program to swap two numbers using call by reference.

#include <stdio.h>

// Function Definition for swapping using Call by Reference


// It accepts pointers (addresses) to the original variables
void swap_by_reference(int *ptr_a, int *ptr_b) {
int temp;
temp = *ptr_a; // temp = value at address ptr_a (e.g., 10)
*ptr_a = *ptr_b; // value at address ptr_a becomes value at ptr_b (e.g., 20)
*ptr_b = temp; // value at address ptr_b becomes temp (e.g., 10)
}

int main() {
int n1 = 10, n2 = 20;

printf("Before swapping (main): n1 = %d, n2 = %d\n", n1, n2);

// Call by Reference: Addresses of n1 and n2 are passed


swap_by_reference(&n1, &n2);

// n1 and n2 in main() are now swapped


printf("\nAfter swapping (main) [Call by Reference]:\n");
printf("n1 = %d, n2 = %d\n", n1, n2);
// Output: n1=20, n2=10 (SWAP occurred in main)

return 0;
}

UNIT II
1. What is an array? Describe the type of array. Write a C program to find even and odd numbers in array list.
An Array is a collection of homogeneous (same type) data elements stored in contiguous memory locations. These elements can be accessed using a common name and
an index (subscript). Arrays allow storing a large number of related values efficiently.
Type of Array:
1. One-Dimensional Array: A list of items that can be processed sequentially. It has only one index (subscript).
Example: int list[10]; (Stores 10 integers).
2. Two-Dimensional Array: A collection of items arranged in a matrix form (rows and columns). It requires two indices.
Example: int matrix[3][4]; (Stores a 3x4 matrix).
3. Multi-Dimensional Array: Arrays with three or more dimensions (e.g., $3\text{D}$ array for volume).
C Program to find Even and Odd numbers in an Array:

C
#include <stdio.h>

int main() {
int arr[5]; // Array to hold 5 elements
int i;

printf("Enter 5 integer elements:\n");


for (i = 0; i < 5; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &arr[i]);
}

printf("\nEven numbers in the array: ");


for (i = 0; i < 5; i++) {
if (arr[i] % 2 == 0) {
printf("%d ", arr[i]);
}
}

printf("\nOdd numbers in the array: ");


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

return 0;
}

2. Describe the merit and demerit of static and dynamic memory allocation technique? Explain dynamic memory allocation.
Static Memory Allocation: Memory is allocated at compile time. The size is fixed throughout the program execution.
Merit (Advantages):
Faster Access: Memory is allocated on the stack (for local variables) or data segment (for global/static variables), leading to fast access.
Simplicity: Management is handled automatically by the compiler.
Demerit (Disadvantages):
Fixed Size: Cannot change the memory size during runtime, which leads to memory wastage (if too large) or program failure (if too small).
Limited Size: Stack memory is typically small.
Dynamic Memory Allocation (DMA): Memory is allocated at run time (when the program is executing) from the Heap memory area. This allows programs to handle
data of varying sizes.
Merit (Advantages):
Flexibility: Programs can create complex data structures whose size is not known until runtime.
Efficiency: Allows for efficient use of memory by allocating only the amount needed.
Demerit (Disadvantages):
Slower Access: Memory is allocated on the heap, which is generally slower than stack/static allocation.
Complexity (Risk of Bugs): Programmers must explicitly deallocate memory using free() . Failure to do so causes memory leaks (lost memory).
Dynamic Memory Allocation in C: DMA is performed using four standard library functions from <stdlib.h> :
1. malloc() (Memory Allocation): Allocates a single block of requested memory bytes and returns a pointer to the start of the block. The memory is uninitialized
(contains garbage values).
ptr = (data_type *)malloc(size_in_bytes);
2. calloc() (Contiguous Allocation): Allocates memory for an array of elements and initializes all bits to zero.
ptr = (data_type *)calloc(num_elements, element_size_in_bytes);
3. realloc() (Re-allocation): Changes the size of the previously allocated memory block.
ptr = realloc(ptr, new_size_in_bytes);
4. free() : Deallocates the memory previously allocated by malloc() , calloc() , or realloc() , returning it to the system. This is crucial to prevent memory
leaks.
free(ptr);

3. What is purpose and usage of structure? Differentiate between structure and union explain with suitable example.
Purpose and Usage of Structure:
A Structure ( struct ) is a user-defined collection of heterogeneous (different type) data elements under a single name.
Purpose: It is used to represent a record, like a complete set of related information about an entity (e.g., an employee's name, ID, and salary).
Usage: Structures provide a way to group related data logically, making code more readable and maintainable.
Difference between Structure and Union:
Feature Structure (struct) Union (union)

Memory
All members are allocated their own separate memory space. All members share the same memory space.
Allocation

The size is the sum of the sizes of all its members (plus
Size The size is equal to the size of its largest member.
padding).

Only one member can store data at any given time. Changing one member's
Data Access All members can store data and be accessed simultaneously.
value overwrites the others.

"Has a" relationship. (e.g., A Book has a title, an author, and a


Concept "One of" relationship. (e.g., A value is either an integer or a float).
price).

struct Student { int id; char grade; }; Size $\approx$


Example union Data { int i; float f; }; Size = max(sizeof(int), sizeof(float))
sizeof(int) + sizeof(char)

4. What do you mean by pointer? Explain the role of address and indirection operator using suitable example.
A Pointer is a special type of variable that stores the memory address of another variable. It "points" to a memory location. Pointers are essential for dynamic
memory allocation, accessing arrays and strings efficiently, and implementing call-by-reference.
Role of Operators:

Operator Name Role Example

Address-of Operator (Reference


& Used to get the memory address of a variable. int *p = &x; (Reads: "p stores the address of x")
Operator)

Indirection Operator (Dereference Used to access the value stored at the address printf("%d", *p); (Reads: "Print the value at the address
*
Operator) held by a pointer. p is pointing to")

Suitable Example:

int var = 25; // An integer variable


int *ptr; // A pointer variable that can hold the address of an integer

ptr = &var; // 1. ADDRESS-OF operator (&): ptr now holds the memory address of 'var'

printf("Value of var: %d\n", var); // Output: 25


printf("Address of var: %p\n", &var); // Output: (e.g.) 0x7fff5fbff8ac
printf("Value of ptr (Address of var): %p\n", ptr); // Output: (e.g.) 0x7fff5fbff8ac
printf("Value AT address ptr holds (*ptr): %d\n", *ptr); // Output: 25

*ptr = 50; // 2. INDIRECTION operator (*): Change the value at the address ptr points to (i.e., var)

printf("New value of var: %d\n", var); // Output: 50 (var is changed)

5. Write a C program to find minimum and maximum number in given array list.
C

#include <stdio.h>

int main() {
int arr[] = {15, 27, 8, 42, 10};
int n = sizeof(arr) / sizeof(arr[0]); // Calculate number of elements
int i;

// Initialize min and max with the first element of the array
int min = arr[0];
int max = arr[0];

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


// Check for maximum
if (arr[i] > max) {
max = arr[i];
}

// Check for minimum


if (arr[i] < min) {
min = arr[i];
}
}

printf("The minimum number in the array is: %d\n", min);


printf("The maximum number in the array is: %d\n", max);

return 0;
}

6. Write a C program to compute addition of two Matrices.

#include <stdio.h>

int main() {
int A[3][3], B[3][3], C[3][3];
int i, j, rows = 3, cols = 3;

printf("Enter elements of Matrix A (3x3):\n");


for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("A[%d][%d]: ", i + 1, j + 1);
scanf("%d", &A[i][j]);
}
}

printf("Enter elements of Matrix B (3x3):\n");


for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("B[%d][%d]: ", i + 1, j + 1);
scanf("%d", &B[i][j]);
}
}

// Addition of matrices
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}

printf("\nResultant Matrix C (A + B):\n");


for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
printf("%d\t", C[i][j]);
}
printf("\n");
}

return 0;
}

7. Write a C program to compute Multiplication of two Matrices.

#include <stdio.h>

int main() {
// Assuming 3x2 matrix A and 2x3 matrix B, resulting in 3x3 matrix C
int A[3][2], B[2][3], C[3][3];
int r1 = 3, c1 = 2; // Dimensions of A
int r2 = 2, c2 = 3; // Dimensions of B. c1 must be equal to r2.
int i, j, k;

// Input for Matrix A (3x2)


printf("Enter elements of Matrix A (3x2):\n");
// ... (Input code similar to Q6 for A)

// Input for Matrix B (2x3)


printf("Enter elements of Matrix B (2x3):\n");
// ... (Input code similar to Q6 for B)

// Matrix Multiplication Logic: C[i][j] = sum(A[i][k] * B[k][j])


for (i = 0; i < r1; i++) { // rows of C (from A)
for (j = 0; j < c2; j++) { // columns of C (from B)
C[i][j] = 0; // Initialize element
for (k = 0; k < c1; k++) { // Inner loop over c1 (or r2)
C[i][j] += A[i][k] * B[k][j];
}
}
}

printf("\nResultant Matrix C (A x B):\n");


for (i = 0; i < r1; i++) {
for (j = 0; j < c2; j++) {
printf("%d\t", C[i][j]);
}
printf("\n");
}

return 0;
}

8. Write a C program to search a value in given array list using Binary Search.

Binary Search requires the array to be sorted.

#include <stdio.h>

int main() {
// Sorted array for Binary Search
int arr[] = {10, 20, 30, 40, 50, 60, 70, 80};
int n = 8; // Array size
int key, found = -1;
int low = 0, high = n - 1, mid;

printf("The sorted array is: ");


for (int i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n\nEnter the value to search: ");
scanf("%d", &key);

while (low <= high) {


mid = low + (high - low) / 2; // Calculate middle index

if (arr[mid] == key) {
found = mid; // Key found
break;
} else if (arr[mid] < key) {
low = mid + 1; // Key is in the upper half
} else {
high = mid - 1; // Key is in the lower half
}
}

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

return 0;
}

9. Write a C program to print the detail of students (Name, Roll no., Marks Percentage) using structure.

#include <stdio.h>

// Define a structure named Student


struct Student {
char name[50];
int roll_no;
float marks_percentage;
};

int main() {
struct Student s; // Declare a structure variable 's'

// Input data for the student


printf("Enter Student Name: ");
scanf("%s", [Link]); // Using %s without & for character arrays
printf("Enter Roll Number: ");
scanf("%d", &s.roll_no);
printf("Enter Marks Percentage: ");
scanf("%f", &s.marks_percentage);

// Print the student details


printf("\n--- Student Details ---\n");
printf("Name: %s\n", [Link]);
printf("Roll Number: %d\n", s.roll_no);
printf("Marks Percentage: %.2f%%\n", s.marks_percentage);

return 0;
}

10. Write a C program to print the detail of employee (Name, ID, and Salary) using Union.

#include <stdio.h>

// Define a Union named Employee


// NOTE: Only one member can be used at a time in memory
union Employee {
char name[50];
int id;
float salary;
};

int main() {
union Employee u;

// We can only store and retrieve ONE of the values correctly at a time.
// Demonstrating the size and shared memory:

printf("Size of Employee Union: %zu bytes (size of the largest member: name[50])\n", sizeof(u));

// Store Name:
printf("\nEnter Employee Name: ");
scanf("%s", [Link]);
printf("Employee Name: %s\n", [Link]); // Correct

// Store ID (This overwrites the 'name' data because memory is shared):


printf("Enter Employee ID: ");
scanf("%d", &[Link]);
printf("Employee ID: %d\n", [Link]); // Correct

// Store Salary (This overwrites the 'id' and 'name' data):


printf("Enter Employee Salary: ");
scanf("%f", &[Link]);
printf("Employee Salary: %.2f\n", [Link]); // Correct

// Accessing 'id' or 'name' here will show garbage or corrupted data


printf("ID after entering salary: %d (Garbage/Corrupted)\n", [Link]);

return 0;
}

11. Explain C-string format with suitable example.


A C-String (or character string) is a sequence of characters stored in a one-dimensional character array and is always terminated by a special character called the
null character ( \0 ). The null character marks the end of the string.
Format/Declaration: C-strings are typically declared in one of two ways:
1. Using a character array (most common):

char str1[15] = "Hello"; // The compiler automatically adds '\0'

2. Using a pointer to a character (read-only):

char *str2 = "World"; // Pointer points to the string literal

Memory Representation (Example for str1 = "Hello" ):


Index 0 1 2 3 4 5 ... 14

Value H e l l o \0 (Unused)

Suitable Example (using C-string standard library functions):

#include <stdio.h>
#include <string.h> // Standard library for string functions

int main() {
char s1[20] = "Apple";
char s2[20] = "Orange";

// 1. strlen() - Length of string


printf("Length of s1: %zu\n", strlen(s1)); // Output: 5

// 2. strcpy() - Copy string


strcpy(s2, s1);
printf("s2 after copy: %s\n", s2); // Output: Apple

// 3. strcmp() - Compare strings (returns 0 if equal)


if (strcmp(s1, s2) == 0) {
printf("s1 and s2 are equal.\n");
}

return 0;
}

12. Explain file stream format with suitable example.


In C, a File Stream (or just "stream") is an abstract concept that represents a flow of data, usually from a source (like a keyboard, a file, or a network connection)
to a destination (like a monitor, a file, or a network connection).
For file I/O, the stream acts as an interface between the program and the physical file. The program communicates with the stream, and the operating system
handles the reading/writing to the physical disk file.
A special pointer of type FILE* is used to manage the file stream and contains all necessary information to communicate with the file (like the current
reading/writing position).
File Stream Functions:
fopen() : Opens a file and associates it with a stream. Returns a FILE* pointer.
fputc() / fgetc() : Writes/Reads a single character.
fputs() / fgets() : Writes/Reads a string.
fprintf() / fscanf() : Writes/Reads formatted data (like printf and scanf ).
fwrite() / fread() : Writes/Reads blocks of binary data.
fclose() : Closes the file stream, flushing any buffers and releasing the resources.
Suitable Example (Writing to a file):

#include <stdio.h>

int main() {
FILE *file_pointer; // Declares the file stream pointer
char data[] = "This is a test line.";

// Open the file "[Link]" in write mode ("w")


file_pointer = fopen("[Link]", "w");

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

// Write the string to the file


fprintf(file_pointer, "%s\n", data);
printf("Data successfully written to file.\n");

// Close the file stream


fclose(file_pointer);

return 0;
}
13. Describe C program for directive and macros.
Preprocessor Directives:
These are instructions given to the C Preprocessor (a program run before the compiler) that begin with the # symbol. They are processed before the actual
compilation begins.
Purpose: They modify the source code file, such as including other files, defining constants, or conditional compilation.
Examples:
#include <stdio.h> : Inserts the content of the stdio.h header file.
#define PI 3.14159 : Defines a symbolic constant (a macro).
#ifdef DEBUG : Checks if a macro is defined.
Macros:
A Macro is a piece of code in a program that is given a name. When the preprocessor encounters a macro name, it replaces it with the actual piece of code
(text substitution).
Types:
1. Object-like Macros (Constants): Used for simple constant substitution (e.g., #define MAX_SIZE 100 ).
2. Function-like Macros (Mini-functions): Used for code substitution that takes arguments. They are generally faster than actual functions because they
avoid the overhead of a function call.
Example (Function-like Macro):

#include <stdio.h>

// Macro to find the maximum of two numbers


#define MAX(a, b) ((a) > (b) ? (a) : (b))

int main() {
int x = 10, y = 5;
int m = MAX(x, y); // Preprocessor replaces this with ((x) > (y) ? (x) : (y));
printf("Maximum is: %d\n", m);
return 0;
}

14. Describe about function for file handling. Define fprint() , fscanf() , fputs() , fgets() , fseek() , fgetc() , fputc() , fwrite() , fread() .

These are standard C library functions used for various operations on files (File Input/Output). They all operate on a file stream identified by a FILE* pointer.

Function Purpose

fprintf(FILE *fp, const char


Writes formatted output (like printf ) to the file stream pointed to by fp .
*format, ...)

fscanf(FILE *fp, const char


Reads formatted input (like scanf ) from the file stream pointed to by fp .
*format, ...)

fputs(const char *str, FILE *fp) Writes a string str to the file stream fp . It does not automatically add a newline character ( \n ).

Reads a line (up to n-1 characters) from the file stream fp and stores it in str . It stops reading after reading a
fgets(char *str, int n, FILE *fp)
newline or hitting EOF. The newline character is included in the string (if read).

fseek(FILE *fp, long offset, int Sets the file position indicator (the cursor) for the stream fp . offset is the number of bytes to move, and whence is
whence) the starting position ( SEEK_SET for start, SEEK_CUR for current, SEEK_END for end).

fgetc(FILE *fp) Reads and returns the next character from the file stream fp . Returns EOF (End Of File) if reading fails.

fputc(int char, FILE *fp) Writes the character specified by char (which is converted to an unsigned char ) to the file stream fp .

fwrite(const void *ptr, size_t size, Writes n items, each of size size bytes, from the block of memory pointed to by ptr to the file stream fp . Used for
size_t n, FILE *fp) binary I/O.

fread(void *ptr, size_t size, size_t Reads n items, each of size size bytes, from the file stream fp into the memory block pointed to by ptr . Used for
n, FILE *fp) binary I/O.

15. A two dimensional array defined as float a[4...7, -1...3] , requires 2 bytes of storage for each element.
1. Calculate the address of element $A[6, 2]$ given that the base address is $100$.
2. Determine the dimensions of the array for a $2\text{D}$ array $DATA[20][30]$ (size $4$ bytes/element). Base address $DATA[1500][20]$ is $2000$.

1. Calculate Address of $A[6, 2]$ (Row-Major Order assumed)


Array Definition: float a[4...7, -1...3]
Indices: $A[i, j]$, where $i \in [4, 7]$ and $j \in [-1, 3]$.
Element to find: $A[6, 2]$.
Base Address (BA): $100$
Element Size (W): 2 bytes
Lower Bound for Row ($L_1$): $4$
Upper Bound for Row ($U_1$): $7$
Lower Bound for Column ($L_2$): $-1$
Upper Bound for Column ($U_2$): $3$
Number of Columns ($N_2$): $U_2 - L_2 + 1 = 3 - (-1) + 1 = 5$ columns.
Formula for Row-Major Order:

$$\text{Address}(A[i, j]) = BA + W \times [N_2 \times (i - L_1) + (j - L_2)]$$


Substitution:

$$\text{Address}(A[6, 2]) = 100 + 2 \times [5 \times (6 - 4) + (2 - (-1))]$$


$$\text{Address}(A[6, 2]) = 100 + 2 \times [5 \times (2) + (3)]$$
$$\text{Address}(A[6, 2]) = 100 + 2 \times [10 + 3]$$
$$\text{Address}(A[6, 2]) = 100 + 2 \times [13]$$
$$\text{Address}(A[6, 2]) = 100 + 26 = \mathbf{126}$$

The address of element $A[6, 2]$ is $126$.

2. Determine the dimensions of the array $DATA[20][30]$


Array Definition (Size): $DATA[20][30]$ (It seems the question meant the array is declared as DATA[R][C] where $R=20$ and $C=30$, but the provided base
address notation is non-standard).
Standard Interpretation: If the array is declared as int DATA[R][C] , its dimensions are $R$ rows and $C$ columns.
Number of Rows ($R$): $20$
Number of Columns ($C$): $30$
Given Information Analysis:
Array Declaration (Assumed): $DATA[R][C]$ with $R=20, C=30$.
Size per element ($W$): 4 bytes.
Base Address $DATA[0][0]$: Not given, let's call it $BA$.
Address of $DATA[1500][20]$ is $2000$.
Error in Question: The array dimensions are given as $20 \times 30$. An index of $1500$ for the row ($i$) and $20$ for the column ($j$) is out of bounds for an
array declared as $DATA[20][30]$ (where maximum indices are $19$ and $29$).
Assuming the question meant $DATA[i_1][i_2]$ is the array name, and $20 \times 30$ is the total elements: This is still unclear.
Most Likely Answer (Direct Interpretation of Declaration):

The dimensions of the $2\text{D}$ array $DATA[20][30]$ are:

Number of Rows: 20
Number of Columns: 30
Part (b) Column-Major Formula (for $DATA[1, 2]$ if $BA=100$ and dimensions are $20 \times 30$): Since the $2\text{D}$ array problem is split into two parts,
let's also provide the calculation for the given non-standard address, assuming $DATA[1500][20]$ is $A[i, j]$ and $2000$ is the address of $A[1, 2]$ if the array
had $1500$ rows and $20$ columns and the index started at $1$.
Conclusion: Due to the significant index mismatch ($1500$ and $20$ for an $20 \times 30$ array), the only part of the question that can be answered
reliably is the dimensions based on the declaration.
Dimensions of $DATA[20][30]$: $20 \times 30$ (20 rows and 30 columns).

UNIT III
1. Define Data Structure?
A Data Structure is a particular way of organizing and storing data in a computer so that it can be accessed and modified efficiently. It provides a means to manage
large amounts of data effectively for specific operations (like search, insertion, and deletion). Examples include Arrays, Linked Lists, Stacks, Queues, Trees, and
Graphs.

2. Define Algorithm, Complexity, and Time-Space trade-off?


Algorithm: (See Unit I, Q4) A finite set of well-defined, step-by-step instructions to solve a specific problem.
Complexity (Algorithmic Complexity): A measure of the resources (time and space) required by an algorithm to run. It's typically expressed using Big O notation ($O$)
which describes the growth rate of the resource requirement as the input size ($n$) increases.
Time Complexity: Measures the amount of time an algorithm takes as a function of the input size ($n$).
Space Complexity: Measures the amount of memory space an algorithm requires as a function of the input size ($n$).
Time-Space Trade-off: The relationship where an algorithm can be designed to either run faster by using more memory (space) (time reduction at the cost of space)
or run using less memory by taking longer to execute (time) (space reduction at the cost of time). For example, pre-calculating and storing results in a table (more
space) to allow faster lookup (less time).
3. Write a C program to perform stack operation.

A Stack is a LIFO (Last-In, First-Out) data structure. The primary operations are Push (add element) and Pop (remove element).
C

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

#define MAX_SIZE 5 // Maximum size of the stack

int stack[MAX_SIZE];
int top = -1; // 'top' is the index of the last element, -1 means stack is empty

// Function to add an element to the stack


void push(int value) {
if (top == MAX_SIZE - 1) { // Check for Stack Overflow
printf("Stack Overflow! Cannot push %d.\n", value);
} else {
top++;
stack[top] = value;
printf("%d pushed to stack.\n", value);
}
}

// Function to remove an element from the stack


void pop() {
if (top == -1) { // Check for Stack Underflow
printf("Stack Underflow! Cannot pop.\n");
} else {
printf("%d popped from stack.\n", stack[top]);
top--; // Decrease top to remove the element
}
}

// Function to display stack elements


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

int main() {
push(10);
push(20);
push(30);
display();
pop();
display();
push(40);
push(50);
push(60); // Overflow attempt
display();
return 0;
}

4. $E * (F + G) / H + (I / J)$ write in Infix, Postfix, and Prefix form.

Form Expression

Infix (Standard human readable) $E * (F + G) / H + (I / J)$

Postfix (Reverse Polish Notation - RPN) $E F G + * H / I J / +$

Prefix (Polish Notation) $+ / * E + F G H / I J$

5. Describe about Towers of Hanoi and Types of recursion with suitable example.
Towers of Hanoi:
Description: A mathematical puzzle that involves three pegs (Source, Auxiliary/Helper, Destination) and a number of disks of different sizes. The objective is to
move the entire stack of disks from the Source peg to the Destination peg, following these rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the uppermost disk from one stack and placing it on top of another stack or an empty peg.
3. No disk may be placed on top of a smaller disk.
Solution: The minimum number of moves required for $n$ disks is $2^n - 1$. The puzzle is classically solved using a recursive algorithm.
Algorithm (for $n$ disks from Source to Dest via Aux):
1. Move $n-1$ disks from Source to Auxiliary (using Dest as helper).
2. Move the $n$-th (largest) disk from Source to Destination.
3. Move $n-1$ disks from Auxiliary to Destination (using Source as helper).
Types of Recursion: Recursion is a function calling itself.
1. Direct Recursion: A function calls itself directly from within its body.
Example: Factorial calculation.

int fact(int n) {
if (n <= 1) return 1;
return n * fact(n - 1); // Direct call
}

2. Indirect (Mutual) Recursion: Two or more functions call each other in a circular way.
Example: functionA calls functionB , and functionB calls functionA .
3. Tail Recursion: The recursive call is the very last operation performed by the function. This can sometimes be optimized by the compiler into an iterative loop,
saving stack space.
Example: A non-optimized factorial function.
4. Non-Tail Recursion (Head Recursion): The recursive call is not the last operation; some operation must be performed on the result of the recursive call.
(Factorial function given for Direct Recursion is non-tail).

6. Define Garbage Collection and Compaction? Describe about different types of queue operations?
Garbage Collection:
Definition: An automatic memory management process that is designed to reclaim memory space occupied by objects or variables that are no longer in use (i.e.,
no longer referenced by the program).
Goal: To prevent memory leaks and simplify memory management for the programmer. C does not have built-in garbage collection (it uses manual memory
management with malloc/free ), but languages like Java and Python do.
Compaction:
Definition: A memory management technique used to defragment the memory heap. It involves physically moving all the used blocks of memory together and
consolidating all the available free space into one large, contiguous block.
Goal: To eliminate external fragmentation (many small, unused holes in memory) so that large memory allocations can be satisfied.

7. Describe about different types of Queue Operations?

A Queue is a FIFO (First-In, First-Out) data structure. Operations are performed at two ends: the front (or head) for removal and the rear (or tail) for insertion.
1. Enqueue (Insertion):
Purpose: To add an element to the rear (or back) end of the queue.
Logic: Check if the queue is full (Overflow). If not, increment the rear pointer and insert the new element at that position.
2. Dequeue (Deletion):
Purpose: To remove an element from the front (or head) end of the queue.
Logic: Check if the queue is empty (Underflow). If not, retrieve the element at the front position and then increment the front pointer.
3. Peek / Front :
Purpose: To return the value of the front element without removing it.
Logic: Check if the queue is empty. If not, return the element at the front position.
4. isEmpty :
Purpose: To check if the queue contains any elements.
Logic: Returns true if the front pointer is ahead of the rear pointer, or if both are at their initial/empty state.
5. isFull :
Purpose: To check if the queue has reached its maximum capacity.
Logic: Returns true if the rear pointer has reached the maximum size limit of the underlying array.

8. Write a C program to perform Queue operation.


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

#define MAX_SIZE 5

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

// 1. Enqueue (Insertion)
void enqueue(int value) {
if (rear == MAX_SIZE - 1) { // Check if queue is full
printf("Queue Overflow! Cannot enqueue %d.\n", value);
} else {
if (front == -1) { // If queue was empty, set front to 0
front = 0;
}
rear++; // Move rear pointer
queue[rear] = value;
printf("%d enqueued to queue.\n", value);
}
}

// 2. Dequeue (Deletion)
void dequeue() {
if (front == -1 || front > rear) { // Check if queue is empty
printf("Queue Underflow! Cannot dequeue.\n");
front = rear = -1; // Reset queue if it was fully emptied
} else {
printf("%d dequeued from queue.\n", queue[front]);
front++; // Move front pointer
if (front > rear) { // Check if queue is now empty
front = rear = -1;
}
}
}

// Display queue elements


void display() {
if (front == -1) {
printf("Queue is empty.\n");
} else {
printf("Queue elements: ");
for (int i = front; i <= rear; i++) {
printf("%d ", queue[i]);
}
printf("\n");
}
}

int main() {
enqueue(10);
enqueue(20);
enqueue(30);
display(); // 10 20 30
dequeue(); // 10 dequeued
display(); // 20 30
enqueue(40);
enqueue(50);
enqueue(60); // Overflow attempt
dequeue(); // 20 dequeued
display(); // 30 40 50
return 0;
}

9. Describe about different types of link list?

A Linked List is a linear data structure where elements are not stored at contiguous memory locations. Instead, each element (node) is a separate object that contains the
actual data and a pointer (or link) to the next node in the sequence.
1. Singly Linked List (SLL):
Description: The most common type. Each node has two parts: the data and a single pointer that points to the next node. The last node's pointer is NULL.
Traversal: Can only be traversed in one direction (forward).
2. Doubly Linked List (DLL):
Description: Each node has three parts: the data, a pointer to the next node, and a pointer to the previous node.
Traversal: Can be traversed in both directions (forward and backward).
Overhead: Requires more memory per node due to the extra pointer.
3. Circular Linked List (CLL):
Description: A variation where the last node's pointer does not point to NULL but instead points back to the first node (the head).
Traversal: Traversal can start at any node and continue around the list. It requires a specific stop condition to prevent infinite looping.
Types: Can be singly circular or doubly circular.
10. Describe about different types of Deletion function of link list.

The deletion operation involves removing a node from the linked list and freeing the memory it occupied. The type of deletion refers to the location of the node being
removed.
1. Deletion from the Beginning (Head/Front):
Logic:
Store the address of the first node (Head).
Update the Head pointer to point to the second node (Head $\rightarrow$ next).
Free the memory of the original first node.
Complexity: $O(1)$ - Constant time, regardless of list size.
2. Deletion from the End (Tail/Rear):
Logic:
Traverse the list from the Head to find the second-to-last node.
Set the next pointer of the second-to-last node to NULL.
Free the memory of the original last node.
Complexity: $O(n)$ - Linear time, as the entire list must be traversed to find the predecessor of the last node. (For Doubly Linked Lists, this is $O(1)$).
3. Deletion from a Specific Position (or after a given node):
Logic:
Traverse the list to find the node just before the node to be deleted (the predecessor).
Store the address of the node to be deleted (the current node's next).
Update the predecessor's next pointer to skip the current node (i.e., predecessor $\rightarrow$ next = current $\rightarrow$ next $\rightarrow$ next).
Free the memory of the skipped node.
Complexity: $O(n)$ - Linear time, as traversal is required.

11. Describe about different types of Insertion function of Link List.

The insertion operation involves creating a new node and attaching it to the list at a specific location.
1. Insertion at the Beginning (Head/Front):
Logic:
Create a new node.
Set the new node's next pointer to point to the current Head of the list.
Update the Head pointer to point to the new node.
Complexity: $O(1)$ - Constant time.
2. Insertion at the End (Tail/Rear):
Logic:
Create a new node. Set the new node's next pointer to NULL.
Traverse the list from the Head to find the current last node.
Set the last node's next pointer to point to the new node.
Complexity: $O(n)$ - Linear time, as the list must be traversed. (For Doubly Linked Lists or a list with a dedicated Tail pointer, this is $O(1)$).
3. Insertion at a Specific Position (or after a given node):
Logic:
Create a new node.
Traverse the list to find the node after which the new node is to be inserted (the predecessor).
Set the new node's next pointer to point to the predecessor's next node.
Set the predecessor's next pointer to point to the new node.
Complexity: $O(n)$ - Linear time, as traversal is required.

12. Write the advantages and disadvantages of Link List?

Advantages of Linked Lists:


1. Dynamic Size: Linked lists can grow or shrink in size during runtime as memory is allocated dynamically using functions like malloc() . Unlike arrays, there is no
need to pre-allocate a fixed size.
2. Ease of Insertion and Deletion: Inserting a new node or deleting an existing node is highly efficient (often $O(1)$) if the location of the preceding node is known, as
it only requires changing a few pointer links.
3. Efficient Memory Utilization: Memory is allocated only when a node is needed, and free() can be used to reclaim it, leading to efficient use of heap space and no
risk of external fragmentation (unlike arrays with static allocation).

Disadvantages of Linked Lists:


1. Extra Memory for Pointers: Each node requires extra space to store the pointer(s) to the next (and possibly previous) node(s), resulting in increased memory overhead
compared to storing just the data in an array.
2. No Random Access: To access an element, you must start from the Head and sequentially traverse the list until the desired element is found. This makes direct access
(like array index $A[i]$) impossible. Accessing the $n$-th element takes $O(n)$ time.
3. Cache Locality: Due to non-contiguous memory allocation, linked list nodes may be scattered in memory. This leads to poor cache locality, making data access slower
than arrays, which are stored contiguously.

You might also like