Home » Data structure programs using C

C program to Reverse a String using STACK

Reverse String using STACK in C - This program will read a string and reverse the string using Stack push and pop operations in C programming Language.

Reversing string is an operation of Stack by using Stack we can reverse any string, here we implemented a program in C - this will reverse given string using Stack.

The logic behind to implement this program:

  1. Read a string.
  2. Push all characters until NULL is not found - Characters will be stored in stack variable.
  3. Pop all characters until NULL is not found - As we know stack is a LIFO technique, so last character will be pushed first and finally we will get reversed string in a variable in which we store inputted string.

Reverse String using Stack using C program

/*C program to Reverse String using STACK*/

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

#define MAX 100	/*maximum no. of characters*/

/*stack variables*/
int top=-1;
int item;

/*string declaration*/
char stack_string[MAX];

/*function to push character (item)*/
void pushChar(char item);

/*function to pop character (item)*/
char popChar(void);

/*function to check stack is empty or not*/
int isEmpty(void);

/*function to check stack is full or not*/
int isFull(void);
int main()
    char str[MAX];
    int i;
    printf("Input a string: ");
    scanf("%[^\n]s",str); /*read string with spaces*/
    /*gets(str);-can be used to read string with spaces*/

    printf("Reversed String is: %s\n",str);
    return 0;
/*function definition of pushChar*/
void pushChar(char item)
    /*check for full*/
        printf("\nStack is FULL !!!\n");
    /*increase top and push item in stack*/
/*function definition of popChar*/
 char popChar()
    /*check for empty*/
        printf("\nStack is EMPTY!!!\n");
        return 0;

    /*pop item and decrease top*/
    item = stack_string[top];
    return item;
/*function definition of isEmpty*/
int isEmpty()
        return 1;
        return 0;

/*function definition of isFull*/ 
int isFull()
        return 1;
        return 0;


Input a string: Hello World!
Reversed String is: !dlroW olleH

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.