Solved programming problem

Add 1d Array ODD Elements 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

    {

        if(array[i]%2!=0)

        {

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

        }

        else

        {

            sum(array,n,i+1);

        }

    }

}

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 ODD array Elements: %d
",ans);

    return 0;

}

Output

Please Enter Array Size: 5
Please Enter Array Element: 13 4 1 7 5

Sum of The ODD array Elements: 26

Join the discussion

Add your comment