Solved programming problem

Add 1d Array Element with Recursion in C.

Source code

#include<stdio.h>

int sum(int array[],int n,int i)

{

    if(i==n) ///base case

    {

        return 0;

    }

    else

    {

      return (array[i]+sum(array,n,i+1)); ///Recursion

    }

}

int main()

{

    int i,n;

    int array[100];

    printf("Please Enter Array Size: ");

    scanf("%d",&n);

    printf("Please Enter Array Element: ");

    for(i=0; i<n; i++)

    {

       scanf("%d",&array[i]);

    }

     int ans=sum(array,n,0); ///function call

     printf("
Sum of The array is: %d
",ans);

    return 0;

}

Output

Please Enter Array Size: 5
Please Enter Array Element: 1 2 3  4 5

Sum of The array is: 15

Join the discussion

Add your comment