L-11 MCS 275 Fri 2 Feb 2001

Below are the listings for the programs we discussed in class. Make sure you understand the writing/printing functions. The ones that return strings and integers are more advanced.

The importance of this lecture is that you see the difference between the function void write_reverse (char s[], int i) and the function void print_reverse (int n) . While both problems look very similar, the types of recursion are quite different. On strings we have a "true" recursion, while on numbers, we have "tail" recursion, which can be easily converted into an iteration.

/* L-11 MCS 275 reversing characters in string and digits in number */

#include <stdio.h>
#include <stdlib.h>

#define MAXLEN 80

void write_reverse (char s[], int i);
/* writes the characters in the string backwards,
   e.g., write_reverse("abc",0) writes cba on screen. */
void ptr_write_reverse (char *s); 
/* pointer version of the above write_reverse */
char *reverse_chars (char s[], int i, int *last);
/* returns the string with all characters reversed,
   e.g., reverse_chars("abc",0) returns "cba". */
void print_reverse (int n);
/* prints the number with its digits reversed,
   e.g., print_reverse(123) prints 321 */
int reverse_digits (int n, int acc);
/* returns the number with its digits reversed,
   e.g., reverse_digits(123,0) returns 321 */

int main()
{
   char word[MAXLEN];
   char *revw;
   int n, *last;

   printf("Give a word : ");
   scanf("%s", word);
   printf("Word spelled backwards : ");
   write_reverse(word,0);
   printf("\n");
   printf("with the pointer version : ");
   ptr_write_reverse(word);
   printf("\n");
   last = (int*)calloc(1,sizeof(int));
   revw = reverse_chars(word,0,last);
   printf("Reversed word : %s\n", revw);
   printf("Give a number : ");
   scanf("%d", &n);
   printf("Digits of %d reversed : ", n);
   print_reverse(n);
   printf("\n");
   printf("Number %d with digits reversed : %d\n", n, reverse_digits(n,0));
   return 0;
}

void write_reverse (char s[], int i)
{
   if (s[i] != '\0')
   {
      write_reverse(s,i+1);
      putchar(s[i]);
   }
}

void ptr_write_reverse (char *s)
{
   if (*s != '\0')
   {
      ptr_write_reverse(s+1);
      putchar(*s);
   }
}

char *reverse_chars (char s[], int i, int *last)
{
   char* rev;

   if (s[i] == '\0')
   {
      rev = (char*)calloc(i+1,sizeof(char));
      *last = i;
      rev[*last] = '\0';
   }
   else
   {
      rev = reverse_chars(s,i+1,last);
      rev[*last-i-1] = s[i];
   }
   return rev;
}

void print_reverse (int n)
{
   if (n < 10)
      printf("%d", n);
   else
   {
      printf("%d", n % 10);
      print_reverse(n/10);
   }
}

int reverse_digits (int n, int acc)
{
   if (n < 10)
      return (10*acc + n);
   else
      return reverse_digits(n/10,(acc*10 + (n % 10)));
}