๐ŸŒ
w3resource
w3resource.com โ€บ c-programming-exercises โ€บ stack โ€บ c-stack-exercise-4.php
C - Reverse a string using a stack
Write a C program that accepts a string and reverse it using a stack. ... #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_SIZE 100 // Global stack and top variable declaration char stack[MAX_SIZE]; int top = -1; // Function to push a character onto the stack void push(char data) { if (top == MAX_SIZE - 1) { printf("Overflow stack!\n"); return; } top++; stack[top] = data; } // Function to pop a character from the stack char pop() { if (top == -1) { printf("Empty Stack!\n"); return '\0'; } char data = stack[top]; top--; return data; } // Function to reverse a string using
๐ŸŒ
IncludeHelp
includehelp.com โ€บ c-programs โ€บ reverse-string-using-stack.aspx
C program to Reverse a String using STACK - Data Structure Programs
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*/ for(i=0;i<strlen(str);i++) pushChar(str[i]); for(i=0;i<strlen(str
๐ŸŒ
C# Corner
c-sharpcorner.com โ€บ code โ€บ 2800 โ€บ c-program-to-reverse-a-string-using-stack.aspx
C Program To Reverse a String using Stack
In a data structure stack allow you to access last data element that you inserted to stack,if you remove the last element of the stack,you will be able to access to next to last element.. We can use this method or operation to revers a string value.
๐ŸŒ
Techie Delight
techiedelight.com โ€บ home โ€บ stack โ€บ reverse a string using a stack data structure
Reverse a string using a stack data structure | Techie Delight
September 12, 2025 - This post will discuss how to reverse a string using the stack data structure in C/C++, Java, and Python using explicit stack and call stack.
๐ŸŒ
Hero Vired
herovired.com โ€บ learning-hub โ€บ blogs โ€บ reverse-a-string-in-c
C Program to Reverse a String Using for Loop and Recursion
... There are multiple ways to ... characters until reaching the middle. The other methods are using the strrev() function, using pointers, recursion, and stack......
๐ŸŒ
Cprogrammingcode
cprogrammingcode.com โ€บ 2014 โ€บ 05 โ€บ write-program-to-reverse-string-using.html
Programming Tutorials: Write a Program to Reverse a String Using Stack
Stack is a data structure in which an element that pushed last can be the first element to be popped. So, In this program we pushed all character of a string a stack and then we popped it.Delete
๐ŸŒ
CodezClub
codezclub.com โ€บ category: c programming โ€บ write a c program to reverse string using stack
Write a C Program To Reverse String using Stack - CodezClub
April 11, 2017 - /* C Program To Reverse String using Stack */ #include<stdio.h> #include<string.h> #include<stdlib.h> #define MAX 20 int top = -1; char stack[MAX]; char pop(); void push(char); int main() { char str[20]; unsigned int i; printf("Enter the string : " ); gets(str); /*Push characters of the string str on the stack */ for(i=0;i<strlen(str);i++) push(str[i]); /*Pop characters from the stack and store in string str */ for(i=0;i<strlen(str);i++) str[i]=pop(); printf("\nReversed string is : "); puts(str); return 0; }/*End of main()*/ void push(char item) { if(top == (MAX-1)) { printf("\nStack Overflow\n"); return; } stack[++top] =item; }/*End of push()*/ char pop() { if(top == -1) { printf("\nStack Underflow\n"); exit(1); } return stack[top--]; }/*End of pop()*/
๐ŸŒ
Codeamy
codeamy.in โ€บ home โ€บ cpp โ€บ c program to reverse a string using stack
C Program To Reverse a String using Stack
January 20, 2020 - In this tutorial, String reverse using stack in this program. I implemented the stack push, pop function. Then, Put each character from string to stack, and as we known stack is working on LIFO.
Find elsewhere
๐ŸŒ
IncludeHelp
includehelp.com โ€บ ds โ€บ reverse-a-string-using-stack.aspx
Reverse a string using stack
#include<stdio.h> #include<string.h> //define maximum up to 20 #define MAX 20 int top = -1; char stack[MAX]; /*Begin of push*/ char push(char item) { if (top == (MAX - 1)) printf("Stack Overflow\n"); else stack[++top] = item; } /*End of push*/ /*Begin of pop*/ char pop() { if (top == -1) printf("Stack Underflow\n"); else return stack[top--]; } /*End of pop*/ /*Begin of main*/ int main() { char str[20]; int i; printf("Enter the string : "); gets(str); for (i = 0; i < strlen(str); i++) push(str[i]); for (i = 0; i < strlen(str); i++) str[i] = pop(); printf("Reversed string is : "); puts(str); return 0; } /*End of main*/
๐ŸŒ
Filo
askfilo.com โ€บ government job exams india โ€บ smart solutions โ€บ write a c program that reverse a string using a stack.
Write a C program that reverse a string using a stack.... | Filo
January 15, 2026 - Write a C program that reverse a string using a stack. ... A stack is a Last-In-First-Out (LIFO) data structure. To reverse a string using a stack, we push each character of the string onto the stack, then pop them off one by one.
๐ŸŒ
WsCube Tech
wscubetech.com โ€บ resources โ€บ c-programming โ€บ programs โ€บ reverse-string
How to Reverse a String in C? (8 Programs)
October 23, 2025 - Learn How to Reverse a String in C with 8 programs, including loops, recursion, and functions. Easy-to-follow examples for beginners and experts!
Top answer
1 of 16
74

If you want to practice advanced features of C, how about pointers? We can toss in macros and xor-swap for fun too!

#include <string.h> // for strlen()

// reverse the given null-terminated string in place
void inplace_reverse(char * str)
{
  if (str)
  {
    char * end = str + strlen(str) - 1;

    // swap the values in the two given variables
    // XXX: fails when a and b refer to same memory location
#   define XOR_SWAP(a,b) do\
    {\
      a ^= b;\
      b ^= a;\
      a ^= b;\
    } while (0)

    // walk inwards from both ends of the string, 
    // swapping until we get to the middle
    while (str < end)
    {
      XOR_SWAP(*str, *end);
      str++;
      end--;
    }
#   undef XOR_SWAP
  }
}

A pointer (e.g. char *, read from right-to-left as a pointer to a char) is a data type in C that is used to refer to location in memory of another value. In this case, the location where a char is stored. We can dereference pointers by prefixing them with an *, which gives us the value stored at that location. So the value stored at str is *str.

We can do simple arithmetic with pointers. When we increment (or decrement) a pointer, we simply move it to refer to the next (or previous) memory location for that type of value. Incrementing pointers of different types may move the pointer by a different number of bytes because different values have different byte sizes in C.

Here, we use one pointer to refer to the first unprocessed char of the string (str) and another to refer to the last (end). We swap their values (*str and *end), and move the pointers inwards to the middle of the string. Once str >= end, either they both point to the same char, which means our original string had an odd length (and the middle char doesn't need to be reversed), or we've processed everything.

To do the swapping, I've defined a macro. Macros are text substitution done by the C preprocessor. They are very different from functions, and it's important to know the difference. When you call a function, the function operates on a copy of the values you give it. When you call a macro, it simply does a textual substitution - so the arguments you give it are used directly.

Since I only used the XOR_SWAP macro once, it was probably overkill to define it, but it made more clear what I was doing. After the C preprocessor expands the macro, the while loop looks like this:

    while (str < end)
    {
      do { *str ^= *end; *end ^= *str; *str ^= *end; } while (0);
      str++;
      end--;
    }

Note that the macro arguments show up once for each time they're used in the macro definition. This can be very useful - but can also break your code if used incorrectly. For example, if I had compressed the increment/decrement instructions and the macro call into a single line, like

      XOR_SWAP(*str++, *end--);

Then this would expand to

      do { *str++ ^= *end--; *end-- ^= *str++; *str++ ^= *end--; } while (0);

Which has triple the increment/decrement operations, and doesn't actually do the swap it's supposed to do.

While we're on the subject, you should know what xor (^) means. It's a basic arithmetic operation - like addition, subtraction, multiplication, division, except it's not usually taught in elementary school. It combines two integers bit by bit - like addition, but we don't care about the carry-overs. 1^1 = 0, 1^0 = 1, 0^1 = 1, 0^0 = 0.

A well known trick is to use xor to swap two values. This works because of three basic properties of xor: x ^ 0 = x, x ^ x = 0 and x ^ y = y ^ x for all values x and y. So say we have two variables a and b that are initially storing two values va and vb.

  // initially:
  // a == va
  // b == vb
  a ^= b;
  // now: a == va ^ vb
  b ^= a;
  // now: b == vb ^ (va ^ vb)
  //        == va ^ (vb ^ vb)
  //        == va ^ 0
  //        == va
  a ^= b;
  // now: a == (va ^ vb) ^ va
  //        == (va ^ va) ^ vb
  //        == 0 ^ vb
  //        == vb

So the values are swapped. This does have one bug - when a and b are the same variable:

  // initially:
  // a == va
  a ^= a;
  // now: a == va ^ va
  //        == 0
  a ^= a;
  // now: a == 0 ^ 0
  //        == 0
  a ^= a;
  // now: a == 0 ^ 0
  //        == 0

Since we str < end, this never happens in the above code, so we're okay.

While we're concerned about correctness we should check our edge cases. The if (str) line should make sure we weren't given a NULL pointer for string. What about the empty string ""? Well strlen("") == 0, so we'll initialize end as str - 1, which means that the while (str < end) condition is never true, so we don't do anything. Which is correct.

There's a bunch of C to explore. Have fun with it!

Update: mmw brings up a good point, which is you do have to be slightly careful how you invoke this, as it does operate in-place.

 char stack_string[] = "This string is copied onto the stack.";
 inplace_reverse(stack_string);

This works fine, since stack_string is an array, whose contents are initialized to the given string constant. However

 char * string_literal = "This string is part of the executable.";
 inplace_reverse(string_literal);

Will cause your code to flame and die at runtime. That's because string_literal merely points to the string that is stored as part of your executable - which is normally memory that you are not allowed to edit by the OS. In a happier world, your compiler would know this, and cough an error when you tried to compile, telling you that string_literal needs to be of type char const * since you can't modify the contents. However, this is not the world my compiler lives in.

There are some hacks you could try to make sure that some memory is on the stack or in the heap (and is therefore editable), but they're not necessarily portable, and it could be pretty ugly. However, I'm more than happy to throw responsibility for this to the function invoker. I've told them that this function does in place memory manipulation, it's their responsibility to give me an argument that allows that.

2 of 16
28

Just a rearrangement, and safety check. I also removed your non-used return type. I think this is a safe and clean as it gets:

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

void reverse_string(char *str)
{
    /* skip null */
    if (str == 0)
    {
        return;
    }

    /* skip empty string */
    if (*str == 0)
    {
        return;
    }

    /* get range */
    char *start = str;
    char *end = start + strlen(str) - 1; /* -1 for \0 */
    char temp;

    /* reverse */
    while (end > start)
    {
        /* swap */
        temp = *start;
        *start = *end;
        *end = temp;

        /* move */
        ++start;
        --end;
    }
}


int main(void)
{
    char s1[] = "Reverse me!";
    char s2[] = "abc";
    char s3[] = "ab";
    char s4[] = "a";
    char s5[] = "";

    reverse_string(0);

    reverse_string(s1);
    reverse_string(s2);
    reverse_string(s3);
    reverse_string(s4);
    reverse_string(s5);

    printf("%s\n", s1);
    printf("%s\n", s2);
    printf("%s\n", s3);
    printf("%s\n", s4);
    printf("%s\n", s5);

    return 0;
}

Edited so that end will not point to a possibly bad memory location when strlen is 0.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ dsa โ€บ stack-set-3-reverse-string-using-stack
Reverse a String using Stack - GeeksforGeeks
July 23, 2025 - One by one pop all characters from stack and put them back to string. ... #include <iostream> #include <stack> using namespace std; string reverse(string s) { stack<char> st; // Push all characters onto the stack for (char c : s) st.push(c); ...
๐ŸŒ
Unstop
unstop.com โ€บ home โ€บ blog โ€บ reverse a string in c in 10 different ways (+code examples)
Reverse A String In C In 10 Different Ways (+Code Examples)
September 13, 2024 - We then call the reverseString() function, passing the input string as an argument. This function uses a stack to reverse the original string.
๐ŸŒ
Quora
quora.com โ€บ How-do-you-write-a-C-program-to-reverse-a-string-using-a-stack-data-structure
How to write a C++ program to reverse a string using a stack data structure - Quora
Answer (1 of 2): Stack is a data structure that works in first in last out manner. if you want the reverse of a string, then iterate the string from beginning and store each character in the stack.
๐ŸŒ
Quora
quora.com โ€บ What-is-the-algorithm-to-reverse-a-string-using-a-stack
What is the algorithm to reverse a string using a stack? - Quora
Answer (1 of 2): Point at first char in string Loop thru characters till end of string Get next char Push char on stack Increment char ptr End loop Point at first char in string Loop thru chars in string Pop char off stack Put char to string Inc char pointer End loop It's a bit like r...
๐ŸŒ
YouTube
youtube.com โ€บ watch
Code With Me: Reversing a String in C with a Stack Using Test-Driven Development in CLion - YouTube
In this video, I develop the code to reverse a string in C using a stack. If you're an intermediate C programmer, this tutorial will help you refine your und...
Published ย  March 6, 2025