C Programming Assignment
C Programming Assignment
1 message
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.
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.
This question requires converting a decimal number to the IEEE 754 floating-point standard.
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
}
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
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 (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
}
12. Write a C program to find largest no. among given three numbers.
C
#include <stdio.h>
int main() {
int num1, num2, num3;
return 0;
}
#include <stdio.h>
int main() {
int num;
return 0;
}
#include <stdio.h>
int main() {
int n, i;
long long factorial = 1; // Use long long for larger factorials
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;
}
#include <stdio.h>
int main() {
int i, n;
int t1 = 0, t2 = 1;
int nextTerm = t1 + t2;
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 main() {
int x = 5, y = 3;
int sum = add(x, y); // <-- CALL, x and y are ARGUMENTS
return 0;
}
#include <stdio.h>
int main() {
int n, i, flag = 0;
if (flag == 0) {
printf("%d is a Prime number.\n", n);
} else {
printf("%d is NOT a Prime number.\n", n);
}
return 0;
}
#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);
return 0;
}
#include <stdio.h>
int main() {
int num, originalNum, sum = 0, remainder;
while (num != 0) {
remainder = num % 10; // Get the last digit
sum += remainder; // Add the digit to the sum
num /= 10; // Remove the last digit
}
return 0;
}
#include <stdio.h>
int main() {
int n1, n2, result;
// Function Call
result = add_numbers(n1, n2);
return 0;
}
// Function Definition
int add_numbers(int a, int b) {
int sum = a + b;
return sum; // Return the sum
}
#include <stdio.h>
int main() {
double b, result;
int e;
// Function Call
result = power(b, e);
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;
}
#include <stdio.h>
int main() {
int 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;
}
#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;
return 0;
}
#include <stdio.h>
int main() {
int n1 = 10, n2 = 20;
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;
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.
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:
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:
ptr = &var; // 1. ADDRESS-OF operator (&): ptr now holds the memory address of 'var'
*ptr = 50; // 2. INDIRECTION operator (*): Change the value at the address ptr points to (i.e., var)
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];
return 0;
}
#include <stdio.h>
int main() {
int A[3][3], B[3][3], C[3][3];
int i, j, rows = 3, cols = 3;
// Addition of matrices
for (i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
return 0;
}
#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;
return 0;
}
8. Write a C program to search a value in given array list using Binary Search.
#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;
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>
int main() {
struct Student s; // Declare a structure variable 's'
return 0;
}
10. Write a C program to print the detail of employee (Name, ID, and Salary) using Union.
#include <stdio.h>
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
return 0;
}
Value H e l l o \0 (Unused)
#include <stdio.h>
#include <string.h> // Standard library for string functions
int main() {
char s1[20] = "Apple";
char s2[20] = "Orange";
return 0;
}
#include <stdio.h>
int main() {
FILE *file_pointer; // Declares the file stream pointer
char data[] = "This is a test line.";
if (file_pointer == NULL) {
printf("Error opening file.\n");
return 1;
}
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>
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
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$.
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.
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>
int stack[MAX_SIZE];
int top = -1; // 'top' is the index of the last element, -1 means stack is empty
int main() {
push(10);
push(20);
push(30);
display();
pop();
display();
push(40);
push(50);
push(60); // Overflow attempt
display();
return 0;
}
Form Expression
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.
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.
#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;
}
}
}
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;
}
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.
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.