Reverse A String using Stack C Program

By | November 27, 2015

C Program To Reverse A String using Stack Implementation

Learn How To Reverse a String using Stack as the Data Structure in C Programming. This Program Code takes in a Stack Array and Reverses it using a For Loop. A String is nothing but an Array of Characters. It is important that we should know How A For Loop Works before getting further with this C Program Code. You can also Reverse a String using Array in C Programming.

A Stack works on the Last In First Out (LIFO) principle. It has only one End called TOP where Insertion and Deletion Operations are done. The Element which is Inserted First usually gets deleted or removed at last. A Stack is an example of Linear Data Structure in which all the elements are arranged in a linear order.

A Stack Data Structure is implemented in real world situations also. It is useful for Conversion of an Infix Expression to Post – fix Expression and also for Evaluating Expressions.

Example

Reverse of CodingAlpha = ahplAgnidoC

Must Read: C Program Code To Reverse a  Number

C Program To Reverse a String using Stack Data Structure

#include<stdio.h>
#include<string.h>

#define MAX 20

int element;
int top = -1;
char stack_array[MAX];
void push(char element);
int isEmpty();
int isFull();
char pop();

void main()
{
        char stack_string[30];
        int count;
        printf("Enter A String:\t");
        scanf("%s", stack_string);
        for(count = 0; count < strlen(stack_string); count++)
        {
                push(stack_string[count]);
        }
        for(count = 0; count < strlen(stack_string); count++)
        {
                stack_string[count] = pop();
        }
        printf("%s", stack_string);
        printf("\n");
}

void push(char element)
{
        if(isFull())
        {
                printf("\nStack Overflow\n");
        }
        else
        {
                top = top + 1;
                stack_array[top] = element;
        }
}

char pop()
{
        if(isEmpty())
        {
                printf("\nStack Underflow\n");
                return 1;
        }
        else
        {
                element = stack_array[top];
                top = top - 1;
                return element;
        }
}

int isEmpty()
{
        if(top == -1)
                return 1;
        else
                return 0;
}

int isFull()
{
        if(top == MAX-1)
                return 1;
        else
                return 0;
}

Must Read: C Program To Reverse an Array of Integers

 

Output

C Program Code To Reverse a String using Stack

If you have any compilation errors or doubts in this C Program To Reverse an Array using Stack Data Structure, let us know about in the Comment Section below.

3 thoughts on “Reverse A String using Stack C Program

Let's Discuss