Print the reverse of a string program in c programming
February 19, 2023

Print the reverse of a string using Stack program in c

In this tutorial post we are going to write a Print the Reverse of a string program in c programming.

#include<stdio.h>
#include<conio.h>
#define MAXSTK 10

struct stack
{
    int data[MAXSTK];
    int top;
};


void rev(char []);
void push(struct stack *, int);
int pop(struct stack *);

void main()
{
    char str[10] = "";
    clrscr();
    printf("Enter a String: - ");
    gets(str);
    printf("Reverse of Entered String: - ");
    rev(str);
    getch();
}

void rev(char str[])
{
    struct stack s1;
    int i = 0;
    s1.top = -1;
    while(str[i] != '\0')
        push(&s1, str[i++]);
    while(s1.top != -1)
        printf("%c", pop(&s1));
}

void push(struct stack *p, int val)
{
    if(p->top == MAXSTK-1)
    {
        printf("Stack is Full. ");
        return;
    }
    p->top++;
    p->data[p->top] = val;
}

int pop(struct stack *p)
{
    int val;
    if(p->top == -1)
    {
        printf("Stack is Empty.");
        return NULL;
    }

    val = p->data[p->top];
    p->top--;
    return(val);
}