C Program to Check Palindrome Using Stack
A Palindrome is a string that reads the same forward and backward, like "radar" or "level". Using a stack, we can easily check if a string is a palindrome because stacks follow LIFO (Last In First Out), allowing us to reverse the string easily.
📝 Problem Statement
Q1. A) Write a ‘C’ program which accepts a string and checks whether the string is a Palindrome or not using stack (Static / Dynamic implementation of Stack).
💡 Logic (Student-Friendly Steps)
- Accept the string from the user.
- Use a stack (array for static implementation) to store each character.
- Push all characters of the string onto the stack.
- Pop characters from the stack one by one and compare with the original string.
- If all characters match → the string is a palindrome.
- Otherwise → it is not a palindrome.
💻 Source Code (Static Stack Implementation)
#include <stdio.h>
#include <string.h>
#define MAX 100
char stack[MAX];
int top = -1;
// Function to push character into stack
void push(char ch)
{
if(top < MAX - 1)
{
top++;
stack[top] = ch;
}
}
// Function to pop character from stack
char pop()
{
if(top >= 0)
return stack[top--];
return '\0'; // Empty stack
}
int main()
{
char str[MAX];
int i, len, flag = 1;
char ch;
printf("Enter a string: ");
scanf("%s", str);
len = strlen(str);
// Push all characters to stack
for(i = 0; i < len; i++)
{
push(str[i]);
}
// Compare characters while popping
for(i = 0; i < len; i++)
{
ch = pop();
if(str[i] != ch)
{
flag = 0;
break;
}
}
if(flag)
printf("The string is a Palindrome.\n");
else
printf("The string is not a Palindrome.\n");
return 0;
}
🖥️ Sample Output
Enter a string: radar
The string is a Palindrome.
Enter a string: hello
The string is not a Palindrome.
🎓 Viva Questions with Answers
1. What is a palindrome?
A palindrome is a string that reads the same forwards and backwards.
2. Why do we use a stack to check palindrome?
A stack reverses the string due to its LIFO property, making it easy to compare.
3. What is the top variable in stack?
top points to the last inserted element in the stack.
4. What is the time complexity of this program?
O(n), where n is the length of the string.
5. Can we implement stack using linked list?
Yes, dynamic stack can be implemented using linked list.
