C recursive function

Definition

A recursive function is a function that calls itself.

Conditions

In recursive function we need to specify

  • recursive conditions,
  • terminating conditions, and
  • recursive expressions.

Example - Calculate factorials using recursion


#include <stdio.h>
//from  w w w. j a  v  a 2  s  . c o m
unsigned long factorial(unsigned long);

int main(void)
{
  unsigned long number = 10L;
  printf("\nThe factorial of %lu is %lu\n", number, factorial(number));
  return 0;
}

unsigned long factorial(unsigned long n)
{
  if(n < 2L)
    return n;
  else
    return n*factorial(n - 1L);
}

Example - Recursive fibonacci function


#include <stdio.h>
/*from  w  w w  .j a  va  2s.  c om*/
long fibonacci( long n ); 

int main()
{
   long result; 
   long number; 

   printf( "Enter an integer: " );
   scanf( "%ld", &number );

   result = fibonacci( number );

   printf( "Fibonacci( %ld ) = %ld\n", number, result );
   
   return 0;

}

long fibonacci( long n )
{
   if ( n == 0 || n == 1 ) {
      return n;
   } 
   else { 
      return fibonacci( n - 1 ) + fibonacci( n - 2 );
   } 
   
}

The code above generates the following result.

Example - A recursive power function


#include <stdio.h>
/*w w  w.  ja va 2  s . co  m*/
double power(double x, int n);

int main() {
  double x = 0.0;
  int n = 0;
  for(x = 2.0 ; x<= 5.0; x += 0.5)
    for(n = 0 ; n<5 ; n++)
      printf("%.2lf raised to the power %d = %.2lf\n", x, n, power(x,n));
}

/* Function to raise x to the power n.*/
double power(double x, int n) {
  if(n == 0)
    return 1.0;
  else
    return x * power( x , n - 1 );
}

Example - Copy string using recursion


#include <stdio.h>
/*from   ww  w.j  a va2s .c  om*/
void strcopy(char *s1, char *s2);

int main(void)
{
  char str[80];

  strcopy(str, "this is a test");
  printf(str);

  return 0;
}


void strcopy(char *s1, char *s2)
{
  if(*s2) { /* if not at end of s2 */
    *s1++ = *s2++;
    strcopy(s1, s2);
  }
  else *s1 = '\0'; /* null terminate the string */
}




















Home »
  C Language »
    Language Advanced »




File
Function definition
String
Pointer
Structure
Preprocessing