Sunday 12 November 2017

C Program to Check String is Palindrome using Stack


Code:

#include   stdio.h
#include   stdlib.h
#include   string.h
#define MAX 50

int top = -1, front = 0;
int stack[MAX];
void push(char);
void pop();

void main()
{
    int i, choice;
    char s[MAX], b;
    while (1)
    {
        printf("1-enter string\n2-exit\n");
        printf("enter your choice\n");
        scanf("%d", &choice);
        switch (choice)
        {
        case 1:
            printf("Enter the String\n");
            scanf("%s", s);
            for (i = 0;s[i] != '\0';i++)
            {
                b = s[i];
                push(b);
            }
            for (i = 0;i < (strlen(s) / 2);i++)
            {
                if (stack[top] == stack[front])
                {
                    pop();
                    front++;
                }
                else
                {
                    printf("%s is not a palindrome\n", s);
                    break; 
                }
            }
            if ((strlen(s) / 2)  =  =  front)
                printf("%s is palindrome\n",  s);
            front  =  0;
            top  =  -1;
            break;
        case 2:
            exit(0);
        default:
            printf("enter correct choice\n");
        }
    }
}

/* to push a character into stack */
void push(char a)
{
    top++;
    stack[top]  =  a;
}

/* to delete an element in stack */
void pop()
{
    top--;
}


Output:

1-enter string
2-exit
enter your choice
1
Enter the String
madam
madam is palindrome
1-enter string
2-exit
enter your choice
1
Enter the String
ugesh
ugesh is not a palindrome
1-enter string
2-exit
enter your choice
1
Enter the String
abccba
abccba is palindrome
1-enter string
2-exit
enter your choice
1
Enter the String
abdbca
abdbca is not a palindrome
1-enter string
2-exit
enter your choice
2



More C Programs:













100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...