Write a program to print strings in reverse order using stack. C
🪜 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