CS 3343/3341
  Introduction to Algorithms  
Spring 2012
  Recursive Loops   

The programs below, in Java and C, produce exactly the same output. What is it?

Mystery Functions, in Java and C
// Functions.java: test recursion
public class Functions {

   void f1(int n) {
      while (n >= 0) {
         System.out.print(n + " ");
         n--;
      }
   }

   void f1r(int n) {
      if (n >= 0) {
         System.out.print(n + " ");
         f1r(n-1);
      }
   }

   void f1s(int n) {
      if (n >= 0) {
         f1s(n-1);
         System.out.print(n + " ");
      }
   }

   public static void main(String[] args) {
      Functions func = new Functions();
      System.out.println("f1:");
      func.f1(10); System.out.println();
      System.out.println("f1r:");
      func.f1r(10); System.out.println();
      System.out.println("f1s:");
      func.f1s(10); System.out.println();
   }
}
// functions.c: test recursion
#include <stdio.h>

static void f1(int n) {
   while (n >= 0) {
      printf("%i ", n);
      n = n - 1;
   }
 }

static void f1r(int n) {
   if (n >= 0) {
      printf("%i ", n);
      f1r(n - 1);
   }
}

static void f1s(int n) {
   if (n >= 0) {
      f1s(n - 1);
      printf("%i ", n);
   }
}

void main() {
   printf("f1:\n");
   f1(10); printf("\n");
   printf("f1r:\n");
   f1r(10); printf("\n");
   printf("f1s:\n");
   f1s(10); printf("\n");
}


Revision date: 2011-11-28. (Please use ISO 8601, the International Standard Date and Time Notation.)