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.

*create an empty stack
*one by one push all characters of string to stack
*one by one pop all characters from stack and put them back to string.
  1. #include <stdio.h>  
  2. #include <string.h>  
  3.   
  4. #define max 100  
  5. int top,stack[max];  
  6.   
  7. void push(char x){  
  8.   
  9.       // Push(Inserting Element in stack) operation  
  10.       if(top == max-1){  
  11.           printf("stack overflow");  
  12.       }  else {  
  13.           stack[++top]=x;  
  14.       }  
  15.   
  16. }  
  17.   
  18. void pop(){  
  19.     // Pop (Removing element from stack)  
  20.       printf("%c",stack[top--]);  
  21. }  
  22.   
  23.   
  24. main()  
  25. {  
  26.    char str[]="sri lanka";  
  27.    int len = strlen(str);  
  28.    int i;  
  29.   
  30.    for(i=0;i<len;i++)  
  31.         push(str[i]);  
  32.   
  33.    for(i=0;i<len;i++)  
  34.       pop();