A Program to Reverse String Without Recursion

In this example, we are giving a program to reverse a string without the recursion.


Program to to reverse a string without the recursion:

  1. #include <stdio.h>
  2. #include <string.h>
  3. void reverse(char*, int, int);
  4. int main() {
  5. char str[100];
  6. //input string
  7. gets(str);
  8. reverse(str, 0, strlen(str) - 1);
  9. printf("%s\n",str);
  10. return 0;
  11. }
  12. void reverse(char*a, int start, int end) {
  13. char x;
  14. // recursive condition
  15. if(start >= end)
  16. return;
  17. // simple swapping
  18. x = *(a+start);
  19. *(a+start) = *(a+end);
  20. *(a+end) = x;
  21. // recursive function
  22. reverse(a, ++start, --end);
  23. }

Output:

Input a string: abc
Reverse of the string: cba