1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
/* www.troubleshootyourself.com Program to reverse String using Stack */ #include <stdio.h> #include <string.h> /* Set maximum number of charecters */ #define MAX 100 /* Stack variables */ int top=-1; int item; /* String array variable to store string char*/ char stack_string[MAX]; /* Function to push character */ void pushChar(char item); /* Function to pop character */ char popChar(void); /* Function to check whether stack is empty or not */ int isEmpty(void); /* Function to check whwther stack is full or not */ int isFull(void); int main() { char str[MAX]; int i; /* Read any string with spaces */ printf("Enter the string to reverse: "); scanf("%[^\n]s",str); for(i=0;i<strlen(str);i++) { pushChar(str[i]); } for(i=0;i<strlen(str);i++) { str[i]=popChar(); } printf("Reversed String is: %s\n",str); return 0; } /* Function to push character */ void pushChar(char item) { /*check for full*/ if(isFull()) { printf("\nStack is FULL !!!\n"); return; } /*increase top and push item in stack*/ top=top+1; stack_string[top]=item; } /* Function to pop character */ char popChar() { /*check for empty*/ if(isEmpty()) { printf("\nStack is EMPTY!!!\n"); return 0; } /*pop item and decrease top*/ item = stack_string[top]; top=top-1; return item; } /* Function to check whehter stack is empty or not. */ int isEmpty() { if(top==-1) { return 1; } else { return 0; } } /* Function th check whether stack is full or not */ int isFull() { if(top==MAX-1) { return 1; } else { return 0; } } |
Check and run the program here:
You can run the above program on codeboard editor and see the results. You are allowed to modify code and run. In the editor there is a menu at the top-right corner. Here you can see two buttons such as ‘Compile’ and ‘Run’.
Software engineer by profession, and owned troubleshotyourself channel. Enthusiastic blogger and love to write articles on computer technology and programming. Reach me at kiran.troubleshootyourself@gmail.com.