Thursday, June 23, 2016

Chapter 15 Recursion

/*
* C Program to Reverse the String using Recursion
* Borrowed from here: http://www.sanfoundry.com/c-program-reverse-string-using-recursion-2/
* It reverses the entire string.
* Challange: Modify it to reverse each work
*/
#include 
#include 
#define MAX_NAME_SZ 256
void reverse(char[], int, int);
int main()
{
 char str1[MAX_NAME_SZ];
 int size;

 printf("Enter a string to reverse: ");
 fgets(str1, sizeof(char) * MAX_NAME_SZ-1, stdin);

 size = strlen(str1);
 reverse(str1, 0, size - 1);
 printf("The string after reversing is: %s\n", str1);
 return 0;
}

void reverse(char str1[], int index, int size)
{
 char temp;
 temp = str1[index];
 str1[index] = str1[size - index];
 str1[size - index] = temp;
 if (index == size / 2)
 {
  return;
 }
 reverse(str1, index + 1, size);
}

No comments: