#include <stdio.
h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
// Define a stack structure
struct Stack {
int top;
char items[MAX_SIZE];
};
// Function prototypes
void push(struct Stack *s, char c);
char pop(struct Stack *s);
void reverseString(char *str);
int main() {
struct Stack stack;
stack.top = -1; // Initialize stack top
char str[MAX_SIZE];
printf("Enter a string: ");
fgets(str, MAX_SIZE, stdin);
// Remove newline character from input
str[strcspn(str, "\n")] = 0;
// Push each character of the string onto the stack
for (int i = 0; str[i] != '\0'; i++) {
push(&stack, str[i]);
}
// Pop each character from the stack to reverse the string
printf("Reversed string: ");
while (stack.top != -1) {
printf("%c", pop(&stack));
}
printf("\n");
return 0;
}
// Push a character onto the stack
void push(struct Stack *s, char c) {
if (s->top == MAX_SIZE - 1) {
printf("Stack Overflow\n");
exit(1);
}
s->items[++(s->top)] = c;
}
// Pop a character from the stack
char pop(struct Stack *s) {
if (s->top == -1) {
printf("Stack Underflow\n");
exit(1);
}
return s->items[(s->top)--];
}
This C program takes a string as input from the user, reverses the string using a stack, and then prints the
reversed string.
1. **Include necessary header files:** The program includes `stdio.h`, `stdlib.h`, and `string.h` for standard
input/output operations, dynamic memory allocation, and string manipulation functions respectively.
2. **Define constants:** The program defines a constant `MAX_SIZE` to specify the maximum size of the
stack and the input string.
3. **Define the stack structure:** The program defines a stack structure using a C struct. The stack
contains two members: `top` (to track the top of the stack) and `items` (an array to store the stack
elements).
4. **Function prototypes:** The program declares prototypes for three functions: `push`, `pop`, and
`reverseString`.
5. **Main function:**
- Declares a stack variable `stack` and initializes its top to -1.
- Declares a character array `str` to store the user input string.
- Reads a string from the user using `fgets` and removes the newline character at the end of the string.
- Iterates over each character of the input string and pushes it onto the stack using the `push` function.
- Prints the reversed string by popping each character from the stack.
6. **Push function:**
- Takes a pointer to a stack (`struct Stack *s`) and a character `c` as arguments.
- Checks if the stack is full (top equals `MAX_SIZE - 1`) and prints "Stack Overflow" message if so.
- Otherwise, increments the top of the stack and adds the character `c` to the stack.
7. **Pop function:**
- Takes a pointer to a stack (`struct Stack *s`) as an argument.
- Checks if the stack is empty (top equals -1) and prints "Stack Underflow" message if so.
- Otherwise, decrements the top of the stack and returns the character at that position.
The program demonstrates how to use a stack to reverse a string in C.