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

No comments:

Post a Comment

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() ...