Calculate the sum of array elements using tail recursion

Before going to write C program for this problem, I would like to brief description about Tail recursion.

Tail Recursion is a recursive function where recursive call is the last thing executed by the function. For example the below C program is tail recursive

/* tail recursive function */
void printNum ( int num )
{
if ( num < 0 )
return;
printf ( " %d ", num );
/* The last statement call should be recursive call */
printNum ( num - 1 );
}

Now, I’m going to write c program to calculate the sum of the array elements using tail recursion. I hope, it would be helpful for you.

/* Sum of the array elements using tail recursion */
#include<stdio.h>
int sumOfArrElem (int * arr, int sizeOfArr, int sumOfArr )
{
if ( sizeOfArr == 0 )
{
return sumOfArr;
}
else
{
return sumOfArrElem(arr,sizeOfArr-1,sumOfArr+arr[sizeOfArr-1]);
}
}
int main ( int argc, char **argv )
{
int acTestArr [] = { 10, 30, 6, 9, 8, 28 };
int sum = 0; /* for sum */
int sizeOfArr; /* for size of array */
/* Calculate size of the acTestArr & assigns to sizeOfArr */
sizeOfArr = sizeof ( acTestArr ) / sizeof ( acTestArr[0] );
  /* Calculates the sum of array elements & assign to sum */
sum = sumOfArrElem ( acTestArr, sizeOfArr, sum );
printf ( "The sum of array elements is %d\n", sum );
return 0;
}

To contribute :

If you like Advance Computing and would like to contribute, you can  mail your article to “computingadvance@gmail.com”. You will get credit as your name , email id, designation with article on this blog.

Leave a Reply