Sunday, 17 August 2025

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display()

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display()

queue_implementation.c
#include <stdio.h>
#define MAX 5   // size of the queue

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

// Function to insert an element in queue
void insert(int val) {
    if(rear == MAX - 1) {
        printf("Queue Overflow! Cannot insert %d\n", val);
    } else {
        if(front == -1) front = 0;   // first insertion
        rear++;
        queue[rear] = val;
        printf("%d inserted into the queue.\n", val);
    }
}

// Function to delete an element from queue
void delete() {
    if(front == -1 || front > rear) {
        printf("Queue Underflow! No elements to delete.\n");
    } else {
        printf("%d deleted from the queue.\n", queue[front]);
        front++;
    }
}

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

// Main function to demonstrate queue
int main() {
    insert(10);
    insert(20);
    insert(30);
    display();

    delete();
    display();

    insert(40);
    insert(50);
    insert(60); // should give overflow
    display();

    delete();
    delete();
    delete();
    delete(); // should give underflow
    display();

    return 0;
}

✅ Step-by-Step Explanation

🔹 Queue Structure

  • queue[MAX]: Array to store elements
  • front: Points to first element (initialized to -1)
  • rear: Points to last element (initialized to -1)

🔹 Insert Operation

void insert(int val) {
    if(rear == MAX - 1) {
        printf("Queue Overflow! Cannot insert %d\n", val);
    } else {
        if(front == -1) front = 0;
        rear++;
        queue[rear] = val;
    }
}
  • Overflow check: If rear == MAX-1, queue is full
  • First insertion: Sets front to 0 when inserting first element
  • Normal insertion: Increments rear and adds element

🔹 Delete Operation

void delete() {
    if(front == -1 || front > rear) {
        printf("Queue Underflow! No elements to delete.\n");
    } else {
        printf("%d deleted from the queue.\n", queue[front]);
        front++;
    }
}
  • Underflow check: If front == -1 or front > rear, queue is empty
  • Normal deletion: Removes element at front and increments front pointer

🔹 Display Operation

void display() {
    if(front == -1 || front > rear) {
        printf("Queue is empty.\n");
    } else {
        printf("Queue elements: ");
        for(int i = front; i <= rear; i++) {
            printf("%d ", queue[i]);
        }
        printf("\n");
    }
}
  • Displays all elements from front to rear
  • Shows empty message if queue is empty

🖨️ Example Run (Sample Output)

10 inserted into the queue.
20 inserted into the queue.
30 inserted into the queue.
Queue elements: 10 20 30
10 deleted from the queue.
Queue elements: 20 30
40 inserted into the queue.
50 inserted into the queue.
Queue Overflow! Cannot insert 60
Queue elements: 20 30 40 50
20 deleted from the queue.
30 deleted from the queue.
40 deleted from the queue.
50 deleted from the queue.
Queue Underflow! No elements to delete.
Queue is empty.

📌 Key Concepts Covered

FIFO Principle
First-In-First-Out behavior of queues
Array Implementation
Using array with front and rear pointers
Overflow/Underflow
Handling queue full and empty conditions
Basic Operations
Insert (enqueue), Delete (dequeue), and Display
Pointer Management
Proper handling of front and rear pointers

Write a program to find Minimum and Maximum numbers from the given array using Recursion.

Write a program to find Minimum and Maximum numbers from the given array using Recursion.

min_max_recursion.c
#include <stdio.h>

// Recursive function to find maximum
int findMax(int arr[], int n) {
    if(n == 1) 
        return arr[0];   // base case
    
    int maxRest = findMax(arr, n - 1); // recursion on n-1 elements
    
    return (arr[n - 1] > maxRest) ? arr[n - 1] : maxRest;
}

// Recursive function to find minimum
int findMin(int arr[], int n) {
    if(n == 1) 
        return arr[0];   // base case
    
    int minRest = findMin(arr, n - 1); // recursion on n-1 elements
    
    return (arr[n - 1] < minRest) ? arr[n - 1] : minRest;
}

int main() {
    int n, i;
    printf("Enter size of array: ");
    scanf("%d", &n);

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

    int max = findMax(arr, n);
    int min = findMin(arr, n);

    printf("Maximum element = %d\n", max);
    printf("Minimum element = %d\n", min);

    return 0;
}

✅ Step-by-Step Explanation

🔹 1. Input Array

  • User enters array size and elements
  • Example: arr = [5, 8, 2, 9, 1]

🔹 2. Recursive Max Function

int findMax(int arr[], int n) {
    if(n == 1) return arr[0];
    int maxRest = findMax(arr, n - 1);
    return (arr[n - 1] > maxRest) ? arr[n - 1] : maxRest;
}
  • Base case: When only one element remains, return it
  • Recursive case: Compare current element with max of remaining elements
  • Example: For [5,8,2,9,1], compares 1 with max of [5,8,2,9], etc.

🔹 3. Recursive Min Function

int findMin(int arr[], int n) {
    if(n == 1) return arr[0];
    int minRest = findMin(arr, n - 1);
    return (arr[n - 1] < minRest) ? arr[n - 1] : minRest;
}
  • Same logic as max function but compares for smaller values
  • Example: For [5,8,2,9,1], compares 1 with min of [5,8,2,9], etc.

🔹 4. Result Output

  • Prints the final minimum and maximum values
  • Example output: Maximum = 9, Minimum = 1

🖨️ Example Run

Input:

Enter size of array: 5
Enter 5 elements: 5 8 2 9 1

Output:

Maximum element = 9
Minimum element = 1

📌 Key Concepts Covered

Recursion
Functions calling themselves with smaller subproblems
Base Case
Termination condition for recursive calls
Divide & Conquer
Breaking problem into smaller subproblems (n-1 elements)
Comparison Logic
Ternary operator used to compare elements
Array Processing
Handling array elements recursively

Write a program to find the factorial of a given integer number using stack.

Write a program to find the factorial of a given integer number using stack.

factorial_stack.c
#include <stdio.h>
#define MAX 100

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

// Function to push an element
void push(int val) {
    if(top == MAX - 1) {
        printf("Stack Overflow\n");
    } else {
        stack[++top] = val;
    }
}

// Function to pop an element
int pop() {
    if(top == -1) {
        printf("Stack Underflow\n");
        return -1;
    } else {
        return stack[top--];
    }
}

int main() {
    int n, i;
    long long fact = 1;

    printf("Enter a positive integer: ");
    scanf("%d", &n);

    if(n < 0) {
        printf("Factorial is not defined for negative numbers.\n");
        return 0;
    }

    // Step 1: Push all numbers from n to 1
    for(i = n; i >= 1; i--) {
        push(i);
    }

    // Step 2: Pop all numbers and multiply
    while(top != -1) {
        fact *= pop();
    }

    printf("Factorial of %d is %lld\n", n, fact);

    return 0;
}

✅ Step-by-Step Explanation

🔹 1. Input Validation

if(n < 0) {
    printf("Factorial is not defined for negative numbers.\n");
    return 0;
}
  • Checks for negative input immediately
  • Exits program if input is invalid

🔹 2. Push Numbers to Stack

for(i = n; i >= 1; i--) {
    push(i);
}
  • Pushes numbers from n down to 1 onto the stack
  • Example: n=5 → stack becomes [5,4,3,2,1]

🔹 3. Pop and Multiply

while(top != -1) {
    fact *= pop();
}
  • Pops each number and multiplies with the running product
  • LIFO property ensures correct multiplication order
  • Example: 1 × 2 × 3 × 4 × 5 = 120

🔹 4. Result Output

  • Prints the final factorial result
  • Uses %lld format specifier for long long to handle large numbers

🖨️ Example Runs

Example 1:

Enter a positive integer: 5
Factorial of 5 is 120

Example 2:

Enter a positive integer: 7
Factorial of 7 is 5040

📌 Key Concepts Covered

Stack Operations
Implementation of push/pop functions with error checking
LIFO Principle
Last-In-First-Out behavior used for multiplication order
Factorial Algorithm
n! = n × (n-1) × ... × 1 implemented using stack
Input Validation
Handling edge case for negative numbers
Data Types
Using long long to handle large factorial results

Write a program to find the power of a given number using stack.

Write a program to find the power of a given number using stack.

stack_exponent.c
#include <stdio.h>
#define MAX 100

// Stack structure
int stack[MAX];
int top = -1;

// Function to push an element onto stack
void push(int val) {
    if(top == MAX - 1) {
        printf("Stack Overflow\n");
    } else {
        top++;
        stack[top] = val;
    }
}

// Function to pop an element from stack
int pop() {
    if(top == -1) {
        printf("Stack Underflow\n");
        return -1;
    } else {
        int val = stack[top];
        top--;
        return val;
    }
}

int main() {
    int base, exp, i;
    long long result = 1;

    printf("Enter base number: ");
    scanf("%d", &base);
    printf("Enter exponent: ");
    scanf("%d", &exp);

    // Step 1: Push 'base' onto stack 'exp' times
    for(i = 0; i < exp; i++) {
        push(base);
    }

    // Step 2: Pop elements and multiply
    for(i = 0; i < exp; i++) {
        result *= pop();
    }

    printf("%d^%d = %lld\n", base, exp, result);

    return 0;
}

✅ Step-by-Step Explanation

🔹 1. Stack Implementation

  • Array stack[MAX] stores elements
  • Integer top tracks the top position
  • push() adds elements with overflow check
  • pop() removes elements with underflow check

🔹 2. Push Phase

for(i = 0; i < exp; i++) {
    push(base);
}
  • Pushes the base number onto stack 'exp' times
  • Example: base=3, exp=4 → stack becomes [3,3,3,3]

🔹 3. Pop and Multiply Phase

for(i = 0; i < exp; i++) {
    result *= pop();
}
  • Pops each element and multiplies with result
  • LIFO property ensures correct multiplication order
  • Example: 3 × 3 × 3 × 3 = 81

🔹 4. Result Output

  • Prints the final exponentiation result
  • Uses %lld format specifier for long long result

🖨️ Example Runs

Example 1:

Enter base number: 2
Enter exponent: 5
2^5 = 32

Example 2:

Enter base number: 3
Enter exponent: 4
3^4 = 81

📌 Key Concepts Covered

Stack Operations
LIFO principle implemented with push/pop functions
Exponentiation
Calculating powers through repeated multiplication
Error Handling
Stack overflow/underflow detection
Data Types
Using long long for larger results
Algorithm Design
Creative use of stack for arithmetic operations

Write a program to find the Smallest Common Divisor of a given number.

Write a program to find the Smallest Common Divisor of a given number.

smallest_divisor.c
#include <stdio.h>

int main() {
    int n, i;

    printf("Enter a number: ");
    scanf("%d", &n);

    if(n <= 1) {
        printf("Smallest divisor is not defined for %d\n", n);
    } else {
        for(i = 2; i <= n; i++) {
            if(n % i == 0) {
                printf("Smallest divisor of %d is %d\n", n, i);
                break;   // stop at the first divisor found
            }
        }
    }

    return 0;
}

✅ Step-by-Step Explanation

🔹 1. Input a number

  • User enters a number (example: n = 28)
  • scanf() reads the integer input

🔹 2. Check for valid input

if(n <= 1) {
    printf("Smallest divisor is not defined for %d\n", n);
}
  • Numbers ≤ 1 don't have proper divisors
  • Program handles this edge case immediately

🔹 3. Find smallest divisor

for(i = 2; i <= n; i++) {
    if(n % i == 0) {
        printf("Smallest divisor of %d is %d\n", n, i);
        break;
    }
}
  • Loop starts from 2 (first possible proper divisor)
  • Modulo operator % checks divisibility
  • break exits loop after first divisor found

🖨️ Example Runs

Composite Number Example:

Enter a number: 28
Smallest divisor of 28 is 2

Prime Number Example:

Enter a number: 37
Smallest divisor of 37 is 37

(37 is prime, so its smallest divisor is itself)

📌 Key Concepts Covered

For Loop
Iterates from 2 to n to check possible divisors
Modulo Operator %
Tests if n is divisible by current number (n % i == 0)
Break Statement
Exits loop immediately after finding first divisor
Edge Case Handling
Special handling for numbers ≤ 1
Prime Number Logic
If no divisors found before n, the number is prime

Write a program to find GCD of two numbers.

Write a program to find GCD of two numbers.

gcd_calculator.c
#include <stdio.h>

int main() {
    int a, b, i, gcd;

    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);

    // Find the minimum of a and b
    int min = (a < b) ? a : b;

    for(i = 1; i <= min; i++) {
        if(a % i == 0 && b % i == 0) {
            gcd = i;
        }
    }

    printf("GCD of %d and %d is %d\n", a, b, gcd);

    return 0;
}

✅ Step-by-Step Explanation

🔹 1. Input

  • User enters two numbers (say a = 48, b = 18)
  • scanf() reads both integers from standard input

🔹 2. Find the smaller number

  • GCD can never be greater than the smaller number
  • Ternary operator (a < b) ? a : b determines the minimum

🔹 3. Check common divisors

for(i = 1; i <= min; i++) {
    if(a % i == 0 && b % i == 0) {
        gcd = i;
    }
}
  • Loop from 1 to the smaller number
  • Modulo operator % checks divisibility
  • When both numbers are divisible by i, update gcd

🔹 4. Output

  • After the loop ends, gcd holds the largest common divisor
  • printf() displays the final result

🖨️ Example Run

Input:

Enter two numbers: 48 18

Output:

GCD of 48 and 18 is 6

📌 Key Concepts Covered

Loop (for)
To check all possible divisors from 1 to the smaller number
Modulo operator %
To test divisibility of both numbers by the current index
Decision making (if)
Conditional statement to update GCD when common divisor found
Basic I/O
scanf() for input and printf() for output
Ternary operator
Compact conditional to find minimum of two numbers

Friday, 1 August 2025

Write a program to print strings in reverse order using stack.

Write a program to print strings in reverse order using stack. C

reverse_string_stack.c
#include <stdio.h>
#include <string.h>
#define MAX 100

// Stack structure
char stack[MAX];
int top = -1;

// Push operation
void push(char ch) {
    if (top >= MAX - 1)
        printf("Stack Overflow\n");
    else
        stack[++top] = ch;
}

// Pop operation
char pop() {
    if (top == -1) {
        printf("Stack Underflow\n");
        return '\0';
    } else {
        return stack[top--];
    }
}

int main() {
    char str[MAX];
    int i;

    printf("Enter a string: ");
    fgets(str, MAX, stdin);
    str[strcspn(str, "\n")] = '\0'; // remove newline if present

    // Push all characters to stack
    for (i = 0; str[i] != '\0'; i++) {
        push(str[i]);
    }

    // Pop all characters to print in reverse
    printf("Reversed string: ");
    while (top != -1) {
        printf("%c", pop());
    }

    printf("\n");
    return 0;
}

🪜 Step-by-Step Explanation

🔹 1. User Input

fgets(str, MAX, stdin);
str[strcspn(str, "\n")] = '\0';
  • fgets() reads a complete string including spaces
  • MAX limits input size to prevent buffer overflow
  • strcspn() removes the trailing newline character

🔹 2. Push Characters onto Stack

for (i = 0; str[i] != '\0'; i++) {
    push(str[i]);
}
  • Iterates through each character of the string
  • Pushes each character onto the stack using push()
  • Last character ends up at the top of the stack
  • Stack grows with each character pushed

🔹 3. Pop Characters to Reverse

while (top != -1) {
    printf("%c", pop());
}
  • Continues until stack is empty (top == -1)
  • Pops characters from stack using pop()
  • Prints each character immediately
  • Due to LIFO (Last In First Out), characters print in reverse order

Visualization of Stack Operations

Pushing "hello":

Push 'h' → ['h']
Push 'e' → ['h','e']
Push 'l' → ['h','e','l']
Push 'l' → ['h','e','l','l']
Push 'o' → ['h','e','l','l','o']

Popping for reversal:

Pop → 'o' (stack: ['h','e','l','l'])
Pop → 'l' (stack: ['h','e','l'])
Pop → 'l' (stack: ['h','e'])
Pop → 'e' (stack: ['h'])
Pop → 'h' (stack: [])

🖨️ Sample Output

Input:

Enter a string: hello

Output:

Reversed string: olleh

📌 Key Concepts Covered

Stack
LIFO (Last In First Out) data structure where last element pushed is first popped
Push and Pop
Basic stack operations used to insert and remove elements
Manual Stack in C
Implemented using an array and top variable to track position
String Reversal
Natural result of stack's LIFO behavior when popping elements
Buffer Safety
fgets() used instead of scanf() for safe string input

Total Pageviews

Search This Blog

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display()

Write a program which performs the following operations using a simple queue. : insert() -> delete() -> display() ...