sum of a number using recursion code example

Example 1: javascript recursive sum function

// Write a recursive method that returns the sum of all elements in an array

function recSum(nums) {
    if (nums.length === 1 ) {
        return nums[0];
    }
    if (nums.length === 0 ) {
        return 0;
    }
    let sum = nums[0] + recSum(nums.slice(1,nums.length));
    return sum;
}

Example 2: c program to find the sum of given number using recursion

# include <stdio.h>
int sum(int number);
int main
{
 int n;
 int a;
 printf("enter a number");
 scanf("%d,&n);
 a=sum(n);
 printf("sum=%d",a);
 }
int sum(int number)
{
  if (number==0)
    return 0;
  return(number%10+sum(number/10);
 }

Example 3: recursive function to find the sum of the nth term

void recurse() {
    .....
    recurse()  //recursive call
    .....
}
int main() {
    .....
    recurse(); //function call
    .....
}

Tags:

Misc Example