C Program to Reverse a String using Recursion and Iteration

This C Program reverse the string using both recursion and iteration.

Here is source code of the C Program to reverse the string using both recursion and iteration. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. /*
  2.  *  C Program to Reverse the String using Both Recursion and Iteration
  3.  */
  4. #include <stdio.h>
  5. #include <string.h>
  6.  
  7. /* Function Prototype */
  8. void disp_str1_rec(char *);
  9.  
  10. void main()
  11. {
  12.     char str1[100], *ptr;
  13.     int len1 = 0, i;
  14.     char ch;
  15.     printf("Enter the string:\n");
  16.     scanf("%[^\n]s", str1);
  17.     ptr = str1;
  18.     len1 = strlen(str1);
  19.     printf("Using iteration:\n");
  20.     for (i = len1 - 1; i >= 0;i--)        /* Iterative loop */
  21.     {
  22.  
  23.         ch = str1[i];
  24.         printf("%c", ch);
  25.     }
  26.     printf("Using recurssion:\n");
  27.     disp_str1_rec(ptr);
  28. }
  29.  
  30. /* Code to reverse the string using Recursion */
  31. void disp_str1_rec(char *stng)
  32. {
  33.     char ch;
  34.     if (*stng != '\0')
  35.     {
  36.         ch = *stng;
  37.         stng++;
  38.         disp_str1_rec(stng);
  39.         printf("%c", ch);
  40.     }
  41.     else
  42.     return;
  43. }

$ cc string21.c
$ a.out
Enter the string:
welcome to sanfoundry's c programming class
 
Using iteration:
ssalc gnimmargorp c s'yrdnuofnas ot emoclew
Using recurssion:
ssalc gnimmargorp c s'yrdnuofnas ot emoclewi

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at programming examples on all topics, go to C Programming Examples.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.