CS 3343/3341
  Introduction to Algorithms  
Loop Implemented
  With Recursion  


Loop Implemented With Recursion:

C Program
// fun.c: print n down to 1
#include <stdio.h>

void f(int );
void fr(int );

void f(int n) {

   while (n > 0) {
      printf("%i ", n);
      n--;
   }
   printf("\n");
}

void fr(int n) {
   if (n > 0) {
      printf("%i ", n);
      fr(--n);
   }
}

int main() {
   f(10);
   fr(10);
   printf("\n");
}
// sum.c: sum of 1 to n
#include <stdio.h>

int s(int );
int sr(int );

int s(int n) {
   int sum = 0;
   while (n > 0) {
      sum = sum + n;
      n--;
   }
   return(sum);
}

int sr(int n) {
   if (n > 0) {
      return n + sr(n-1);
   }
   return(0);
}

int main() {
   printf("%i, ", s(10));
   printf("%i\n", sr(10));
}

OutputOutput
10 9 8 7 6 5 4 3 2 1 
10 9 8 7 6 5 4 3 2 1
55, 55


Revision date: 2012-09-05. (Please use ISO 8601, the International Standard Date and Time Notation.)